Python 检查整数输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22025764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:06:17  来源:igfitidea点击:

Python check for integer input

pythoninputtypes

提问by user3353003

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

Any help would be most appreciated.

非常感激任何的帮助。

回答by Maxime Lorant

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

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

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.

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

回答by t.animal

You can just use int(raw_input())to convert the input to an int.

您可以仅用于int(raw_input())将输入转换为 int。

Never evaluate untrusted user input using eval, this will allow a malicious user to take over your program!

永远不要使用 eval 评估不受信任的用户输入,这将允许恶意用户接管您的程序!

回答by angelcool.net

Why is no one mentioning regular expressions ? The following works for me, adjust the regex to fit your needs.

为什么没有人提到正则表达式?以下对我有用,调整正则表达式以满足您的需求。

[aesteban@localhost python-practice]$ cat n.py 
import re

userNumber = '' 

while not re.match('^-?[0-9]*\.?[0-9]+$',userNumber):
  userNumber = raw_input("Enter a number please: ")

newNumber = float(userNumber) + 100

print "Thank you!! Your number plus 100 is: " + str(newNumber)

Tests:

测试:

[aesteban@localhost python-practice]$ python n.py 
Enter a number please: I want to make 0 an hour.
Enter a number please: ok ok...
Enter a number please: 200
Thank you!! Your number plus 100 is: 300.0
[aesteban@localhost python-practice]$ python n.py 
Enter a number please: -50
Thank you!! Your number plus 100 is: 50.0
[aesteban@localhost python-practice]$ python n.py 
Enter a number please: -25.25
Thank you!! Your number plus 100 is: 74.75