我是 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)
uj5u.com熱心網友回復:
您沒有顯示錯誤訊息,但如果這是您的原始縮進,那么問題是您movie_genre在函式內部創建 - 所以它是僅存在于函式內部的區域變數,但其余代碼在函式外部并且無法訪問它。您應該將所有代碼移動到函式內部,或者將所有代碼保留在函式外部。
我將保留所有外部功能 - 所以我可以洗掉它。
還有其他錯誤和一些可以修復的元素
你可以保持性別沒有內在[],然后你就不需要zip(*...)
movie_genre = ["Action", "Horror", "Adventure", "Musical", "Comedy", "Sci-Fi", "Drama", "Romance", "Thriller"]
for genre in movie_genre:
print(genre)
你name以奇怪的方式使用i = name(..)- nameis astring并且你不能像函式一樣使用它。也許您需要input()要求選擇genre-selected = input(...)但我會在顯示流派后這樣做。
我也不知道你想做什么while name。這將永遠回圈運行,因為您不會name在回圈內部進行更改。也許你需要一些不同的東西——即。也許你想重復回圈,直到用戶選擇正確的性別 - `雖然沒有在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?")
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/442748.html
上一篇:如何恢復暫停的(tty輸入)行程[unix/mac]?
下一篇:Tabview滾動行為
