2013-07-04 15 views
2

我想知道如何讓我的代碼不會崩潰,如果用戶鍵入除數字以外的任何內容以進行輸入。我認爲我的其他聲明會覆蓋它,但我得到一個錯誤。如果用戶鍵入字符串,會出錯

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手冊的特定部分。

謝謝!

+1

奇。這似乎是Python3,但它似乎將輸入(可能是字母's')視爲輸入而不是字符串。爲了看看會發生什麼,你可以嘗試用'raw_input'替換'input'嗎? (順便說一下,因爲'run_prog = input()'行發生錯誤,所以不要在後面的行中查找錯誤,或者想知道爲什麼其他錯誤不會修復它) –

+0

當我做時,它給我一個語法錯誤那。 –

+0

SyntaxError或NameError? –

回答

3

相反,你的想法,你的腳本是在Python 3.x中被運行系統某處安裝了Python 2.x,腳本正在運行,導致它使用2.x的不安全/不適當的input()

+0

好的,我剛剛安裝了2.7,現在raw_input在3.3.2中工作...我不知道這是因爲我安裝了2.7還是因爲我沒有正確安裝。我的問題已經徹底解決了! –

+1

'raw_input()'在3.3.2中不存在。您的腳本正在由2.7二進制文件運行。 –

+0

太棒了。我會仔細閱讀,因爲我現在對細節很好奇。謝謝您的意見! –

1

您顯示的錯誤消息表示input()試圖評估鍵入爲Python表達式的字符串。這反過來意味着你實際上並沒有使用Python 3; input只在2.x中做到這一點。無論如何,我強烈建議你這樣做,因爲它明確了你想要的輸入類型。

while times_run == 0: 
    sys.stdout.write("Would you like to run the calculation?\n" 
        "Press 1 for YES.\n" 
        "Press 2 for NO.\n") 
    try: 
     run_prog = int(sys.stdin.readline()) 
    except ValueError: 
     run_prog = 0 

    if not (1 <= run_prog <= 2): 
     sys.stdout.write("Invalid input.\n") 
     continue 

    # ... what you have ... 
+1

'input()'固定在3.x. –

+0

在Python 3中不是這樣。請參見[here](http://docs.python.org/3.1/library/functions.html#input) –

+0

@ IgnacioVazquez-Abrams ... *檢查* ...因此它是。那麼我猜測OP實際上不會使用3.x。 – zwol

1

你可以這樣做:

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() 

elif run_prog not in [1,2]: 
     print('Please enter a number between 1 and 2.') 

如果用戶寫s文本Please enter a number between 1 and 2會出現

相關問題