在用户输入后使用 while 循环输出列表

Using a while loop to output a list after user input

我是 python 的新手,我正在尝试让我的程序在用户输入他们的名字后垂直输出变量“电影类型”。我打算使用 while 循环,但一直出现错误“movie_genre”。并且对如何进行感到困惑。

def main():
    #Movie list
    movie_genre = ["Action", ["Horror"], ["Adventure"], ["Musical"], ["Comedy"], ["Sci-Fi"], ["Drama"], ["Romance"], ["Thriller"]]
    name = ''
    

#We introduce the program to the user 
print ("Hello my name is Frank, the theatre clerk!")

#Asks the user to input their name 
print ("May I please know who i have the pleasure of speaking with?")

#User submits name 
name = input("")

#Returns user name + prompt
print(name + ", pleasure to make your acquaintance!")

while name:
#Asks the user for what genre they want to watch 
    i = name ("What are we interested in watching today?")
    for x in zip (*movie_genre):
        print (x)

movie_genre 未在您尝试使用它的同一范围内定义。

这可以通过多种方式解决,要么缩进所有代码,使其与主函数在同一范围内,然后使用 main()

调用该函数

或者

一个更简单的解决方法是将 movie_genre 的定义移动到更靠近您将使用它的地方:

movie_genre = [["Action"], ["Horror"], ["Adventure"], ["Musical"], ["Comedy"], ["Sci-Fi"], ["Drama"], ["Romance"], ["Thriller"]]

if name:
#Asks the user for what genre they want to watch 
    print("What are we interested in watching today?")
    for x in zip(*movie_genre):
        print(x)

您没有显示错误消息,但如果这是您的原始缩进,那么问题是您在函数内部创建了 movie_genre - 因此它是仅存在于函数内部的局部变量,但其余代码在外部功能,它无法访问它。您应该将所有代码移到函数内部,或者您应该将所有代码保留在函数外部。

我会保留所有外部功能 - 所以我可以删除它。

还有其他错误和少数您可以修复的元素

你可以在没有内在的情况下保留性别 [] 然后你就不需要 zip(*...)

movie_genre = ["Action", "Horror", "Adventure", "Musical", "Comedy", "Sci-Fi", "Drama", "Romance", "Thriller"]

for genre in movie_genre:
    print(genre)

您在 i = name(..) 中以奇怪的方式使用 name - name 是一个 string,您不能像函数一样使用它。也许你需要 input() 来请求 selected genre - selected = input(...) - 但我会在显示流派后这样做。

我也不知道你想用 while name 做什么。这将 运行 永远循环,因为您不会在循环内更改 name。也许你需要一些不同的东西 - 即。也许您想重复循环直到用户 select 正确性别 - `while selected not in movie_genre:


完整示例

#Movie list
movie_genre = ["Action", "Horror", "Adventure", "Musical", "Comedy", "Sci-Fi", "Drama", "Romance", "Thriller"]
name = ''

#We introduce the program to the user 
print("Hello my name is Frank, the theatre clerk!")

#Asks the user to input their name 
print("May I please know who i have the pleasure of speaking with?")

#User submits name 
name = input()

#Returns user name + prompt
print(name + ", pleasure to make your acquaintance!")

# --- select genre ---
selected = ""  # default value before loop

while selected not in movie_genre:  # repeate until user select genre

    for genre in movie_genre:
        print(genre)

    #Asks the user for what genre they want to watch 
    selected = input("What are we interested in watching today?")