我想知道如何讓我的代碼不會崩潰,如果用戶鍵入除數字以外的任何內容以進行輸入。我認爲我的其他聲明會覆蓋它,但我得到一個錯誤。如果用戶鍵入字符串,會出錯
Traceback (most recent call last): File "C:/Python33/Skechers.py", line 22, in run_prog = input() File "", line 1, in NameError: name 's' is not defined
在這種情況下,我輸入了字母「s」。
以下是給我提出問題的部分代碼。程序運行完美無瑕,除非您給它字母或符號。
我希望它打印「無效的輸入」,而不是崩潰,如果可能的話。
有一個技巧,我必須做另一個elif語句和isalpha函數?
while times_run == 0:
print("Would you like to run the calculation?")
print("Press 1 for YES.")
print("Press 2 for NO.")
run_prog = input()
if run_prog == 1:
total()
times_run = 1
elif run_prog == 2:
exit()
else:
print ("Invalid input")
print(" ")
我嘗試了一些變化,沒有成功。
elif str(run_prog):
print ("Invalid: input")
print(" ")
我很欣賞任何反饋,即使它是我參考python手冊的特定部分。
謝謝!
奇。這似乎是Python3,但它似乎將輸入(可能是字母's')視爲輸入而不是字符串。爲了看看會發生什麼,你可以嘗試用'raw_input'替換'input'嗎? (順便說一下,因爲'run_prog = input()'行發生錯誤,所以不要在後面的行中查找錯誤,或者想知道爲什麼其他錯誤不會修復它) –
當我做時,它給我一個語法錯誤那。 –
SyntaxError或NameError? –