問題描述
變量被評估為任何東西 (Variable Being Evaluated as Anything)
以下代碼有問題。這應該是一個基於文本的小型遊戲的開始。我想接受用戶輸入,然後輸出一條消息(例如幫助菜單或遊戲開始)。
def start (): # This runs when the program starts
print("THE LAST RANGER")
print ("Type Start to Begin")
print ("Type About for Credits")
print ("Type Help for Instructions")
prompt_start()
def Waking_up(): # This should run when the user enters "Start"
print ("SIR... Sir. We need to get you out of here, come on.")
def About(): #This should run when the user enters "About"
print ("Welcome to THE LAST RANGER created by Michael Frazer.")
#add more to this at some point
def Help(): #This should run when the user enters "Help"
print ("This is the help menu")
def prompt_start(): #This function takes the users input
global input_0
input_0 = input()
start () #This runs the "start" function defined in the first lines
if input_0 == "Start" or "start": #These should evaluate the users input
Waking_up ()
elif input_0 == "About" or "about":
About ()
elif input_0 == "Help" or "help":
Help ()
else:
print ("Enter Valid Command")
我的問題是輸入變量被評估為字面上的任何東西。例如行
if input_0 == "Start" or "start": #These should evaluate the users input
Waking_up ()
即使輸入不等於“Start”,也會運行“Waking_up”函數。如果用戶輸入“Help”之類的內容,程序似乎認為“Help”等於“Start”並運行喚醒功能。我試過和 3 個朋友一起調試這個,我們都沒有主意。感謝您的幫助。
參考解法
方法 1:
"start" is evaluating to true because you don't have the full expression. Try:
if input_0 == "Start" or input_0 == "start": #These should evaluate the users input
Waking_up ()
方法 2:
Just change the following:
if input_0 == "Start" or input_0 == "start":
Waking_up ()
elif input_0 == "About" or input_0 =="about":
About ()
elif input_0 == "Help" or input_0 == "help":
Help ()
else:
print ("Enter Valid Command")
This will work as you want and will only evaluate the corresponding input(s) instead of "Start" all the time.
Depending on what you're doing with the program, consider filtering the user's input as well (such as converting the input string to .lower()
and only have your if/elif/else
commands accept lowercase input ‑‑ may save you some time. Just a suggestion from a fellow python newbie.
(by Michael Frazer、Ryan、Sludge)