我正在使用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) + ': ')
Run Code Online (Sandbox Code Playgroud)
如果用户只输入数字,一切正常,但如果用户输入错误并输入,例如q,它会给出:
NameError:未定义名称"q"
我想,如果用户插入一个字符串,while循环开始并给用户:该选项无效....如何在不使用raw_input的情况下解决这个问题,因为宽度和高度我想将tham视为数字?
问候,
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)
Run Code Online (Sandbox Code Playgroud)
如果用户只输入int代码按计划工作,但不能防止用户错误.如果用户出错并输入"q",则会出现此错误:
ValueError: invalid literal for int() with base 10: 'q'
Run Code Online (Sandbox Code Playgroud)
我理解为什么但是如何解决这个问题?
问候,
Favolas