limit input to integer only (text crashes PYTHON program)
本问题已经有最佳答案,请猛点这里访问。
这里是python新手,尝试将小测验输入限制为数字1、2或3。如果输入文本,程序将崩溃(因为无法识别文本输入)以下是对我所拥有的内容的改编:欢迎任何帮助。
1 2 3 4 5 6 7 8 9 | 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...." |
使用
1 2 3 4 5 6 7 8 | 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 |
尝试这样做,假设
1 2 3 4 | 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...." |