且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 检查整数输入

更新时间:2023-11-28 14:39:46

您正在使用 eval,它计算在当前上下文中作为 Python 表达式传递的字符串.你想做的只是

You're using eval, which evaluate the string passed as a Python expression in the current context. What you want to do is just

data = raw_input('Enter a number: ')
try:
    number = int(data)
except ValueError:
    print "I am afraid %s is not a number" % data
else:
    if number > 0:
        print "%s is a good number" % number
    else:
        print "Please enter a positive integer"

这将尝试将输入解析为整数,如果失败,则显示错误消息.

This will try to parse the input as an integer, and if it fails, displays the error message.