python - 将输入限制为仅整数(文本使 PYTHON 程序崩溃)

标签 python

<分区>

这里是 Python 新手,试图将测验输入限制为数字 1,2 或 3。
如果输入文本,程序会崩溃(因为无法识别文本输入)
这是我所拥有的改编: 欢迎任何帮助。

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...."

最佳答案

使用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

关于python - 将输入限制为仅整数(文本使 PYTHON 程序崩溃),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15099379/

相关文章:

python - Pandas :如何将具有多个值的单元格转换为多行?

python - 在 django 模型查询集中按自定义属性排序的好方法是什么?

python - DB-API SQLite INSERT 语句在 Python 2.7 中抛出 InterfaceError

python - 动态 start_urls 值

python - `with` 中 `concurrent.futures` 的功能

python - 从可能丢失的 dict 值初始化 Python 变量

python - 将图像从 C++ 传递到 Python 3.4

python - 使用 python-docx 合并包含图像的 docx 文件

python - 使用 MySQL 的 Django Web 框架从请求对象获取数据

python - 在Python中解析键值对