2010-12-10 55 views
0

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

我想,如果用户插入一个字符串,while循环踢,给用户:该选项无效.... 如何CA ñ我解决这个问题,而不使用raw_input,因为宽度和高度我想将tham视为数字?

问候,

Favolas

编辑 继丹尼尔的建议,我修改我的代码如下:

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) 

如果用户只输入INT代码按计划工作,但它从用户错误不安全。如果用户犯了错误类型的“Q”它给了这个错误:

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

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

问候,

Favolas

回答

5

必须使用raw_input代替input在Python 2.x版本input假定用户正在输入要评估的有效Python。你最好的选择是采取字符串输入,然后根据需要进行转换。在这种情况下,您需要尝试使用int进行转换。

正如一个提醒,from the documentation

input([prompt])

Equivalent to eval(raw_input(prompt)) .

Warning: This function is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation. (On the other hand, sometimes this is exactly what you need when writing a quick script for expert use.)

+0

嗨丹尼尔。感谢您的回答。遵循你的建议,但仍有一些问题。我编辑了我的原始问题,请看看它。 Favolas – Favolas 2010-12-11 11:09:34

+0

@Favolas,从代码中移除'x = int(x)'。然后它将与'raw_input'完美配合。 – systemovich 2010-12-11 11:34:34

+0

嗨杰弗里。谢谢,但如果我删除这两个x = int(x)如果我运行这个插入12(它的有效)它进入while循环。它解决了用户插入字符串但在另一个字符串上的问题,并停止使用int – Favolas 2010-12-11 12:06:27