开发者

python give option if user inputs string

开发者 https://www.devze.com 2023-01-30 14:02 出处:网络
I\'m using Python 2.6.6 I have this code: height = 20 width = 10 x = input(\'Please insert a number between \' + str(width + 1) + \' and \' + str(height) + \': \')

I'm using Python 2.6.6

I have this code:

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) + ': ')

If the user only inputs number, everything works OK but if the user makes a mistake and type, for example q, it gives :

NameError: name 'q' is not defined

I want, if the user inserts a string, the while loop kicks in and give the user: That option is not valid.... How can I solve this without using raw_input since width and height I want to treat tham as numbers?

Regards,

Favolas

EDIT Following Daniel suggestion, I've modifie开发者_如何学JAVAd my code to this:

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)

If the user only inputs int code works as planned but its not safe from user errors. If the users, makes a mistake and types 'q' it gives this error:

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

I understand why but how do I solve this?

Regards,

Favolas


You must use raw_input instead of input in Python 2.x. input assumes that the user is inputting valid Python to be evaluated. Your best bet is to take the string input and then convert it as needed. In this case, you will want to try converting with int.

Just as a reminder, 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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号