Python给定选项如果用户输入字符串

0 投票
1 回答
2784 浏览
提问于 2025-04-16 08:22

我正在使用 Python 2.6.6

我有这段代码:

height = 20
width = 10
x = input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ')
while x < (width + 1) or x > 20:
     print 'That option is not valid'
     x = input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ')

如果用户只输入数字,一切都正常,但如果用户犯了错误,比如输入了字母 q,就会出现:

NameError: name 'q' is not defined

我想要的是,如果用户输入了一个字符串,程序就会进入一个循环,并提示用户:这个选项无效……我该怎么做才能解决这个问题,而不使用 raw_input,因为我希望宽度和高度被当作数字处理?

问候,

Favolas

编辑 根据 Daniel 的建议,我修改了我的代码如下:

height = 20
width = 10
x = raw_input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ')
x = int(x)
while x < (width + 1) or x > 20:
    print 'That option is not valid'
    x = raw_input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ')
    x = int(x)

如果用户只输入整数,代码按计划工作,但它并不能防止用户出错。如果用户犯了错误,输入了 'q',就会出现这个错误:

ValueError: invalid literal for int() with base 10: 'q'

我明白为什么会这样,但我该如何解决这个问题呢?

问候,

Favolas

1 个回答

5

在Python 2.x中,你必须使用raw_input,而不是input。因为input会假设用户输入的是有效的Python代码,并且会尝试去执行它。最好的做法是先把输入的内容当作字符串处理,然后再根据需要进行转换。在这种情况下,你可能想用int来转换成整数。

提醒一下,根据文档

input([prompt])

这相当于eval(raw_input(prompt))

警告:这个函数对用户的错误不太安全!它期望输入的是一个有效的Python表达式;如果输入的内容在语法上不正确,就会出现SyntaxError错误。如果在执行过程中出现问题,可能还会引发其他异常。(不过,有时候在写快速脚本时,这正是你需要的,特别是给专家使用时。)

撰写回答