Python检查整数输入 [英] Python check for integer input

查看:137
本文介绍了Python检查整数输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图允许用户输入我的程序,但是当他们输入字符串时,我的程序失败.到目前为止,这是一个更大的程序,但正在尝试纠正该问题:

I am trying to allow a user to input into my program, however when they enter a string my program fails. It is for a bigger program but was trying to correct the problem, I have so far:

data = raw_input('Enter a number: ')
number = eval(data)
if type(number) != int:
     print"I am afraid",number,"is not a number"
elif type(number) == int:
    if data > 0:
        print "The",number,"is a good number"
    else:
        print "Please enter a positive integer"

当用户输入字符串时,它返回:

when the user enters a string, it returns:

number = eval(data)
  File "<string>", line 1, in <module>
NameError: name 'hel' is not defined

任何帮助将不胜感激.

推荐答案

您正在使用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.

这篇关于Python检查整数输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆