2013-02-26 55 views
4

Python新手在這裏,試圖將測驗輸入限制爲數字1,2或3。
如果輸入文本,程序崩潰(因爲文本輸入不被識別)
這裏是我所擁有的改編: 任何幫助最受歡迎。將輸入限制爲僅限整數(文本崩潰PYTHON程序)

choice = input("Enter Choice 1,2 or 3:") 
if choice == 1: 
    print "Your Choice is 1" 
elif choice == 2: 
    print "Your Choice is 2" 
elif choice == 3: 
    print "Your Choice is 3" 
elif choice > 3 or choice < 1: 
    print "Invalid Option, you needed to type a 1, 2 or 3...." 

回答

2

試試這個,假設choice是一個字符串,因爲它似乎是從提到的問題的情況下:

if int(choice) in (1, 2, 3): 
    print "Your Choice is " + choice 
else: 
    print "Invalid Option, you needed to type a 1, 2 or 3...." 
8

使用raw_input()代替,然後轉換爲int(捕捉ValueError如果轉換失敗)。你甚至可以包括一系列測試,並明確提高ValueError()如果給定的選擇是允許值的範圍之外:

try: 
    choice = int(raw_input("Enter choice 1, 2 or 3:")) 
    if not (1 <= choice <= 3): 
     raise ValueError() 
except ValueError: 
    print "Invalid Option, you needed to type a 1, 2 or 3...." 
else: 
    print "Your choice is", choice 
+0

我上傳了我的整個程序http://temp-share.com/show/f3YguH62n底部的百分比也存在問題,有些人會對此發笑。它旨在向學生展示作爲編程的入門介紹 - 我真的需要掌握! – 2013-02-26 21:42:39

+0

@LeecollinsCollins:看看[字符串格式迷你語言](http://docs.python.org/2/library/string.html#format-specification-mini-language),特別是在浮點數格式。這裏有一個特定的'%'百分比格式化功能。 – 2013-02-26 21:45:39