简体   繁体   English

确定输入是否为数字

[英]Determining if an input is a number

How do I find out if my user's input is a number? 如何确定用户输入的数字是否为数字?

input = raw_input()

if input = "NUMBER":
    do this
else:
    do this

What is "NUMBER" in this case? 在这种情况下,“ NUMBER”是什么?

Depends on what you mean by "number". 取决于您所说的“数字”。 If any floating point number is fine, you can use 如果任何浮点数都可以,则可以使用

s = raw_input()
try:
    x = float(s)
except ValueError:
    # no number
else:
    # number

If you're testing for integers you can use the isdigit function: 如果要测试整数,则可以使用isdigit函数:

x = "0042"

x.isdigit()

True 真正

An answer I found elsewhere on StackOverflow [I forget where] gave the following code for checking if something was a number: 我在StackOverflow的其他地方找到的答案[我忘了在哪里]提供了以下代码来检查某物是否为数字:

#This checks to see if input is a number
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

string = raw_input('please enter a number:') 字符串= raw_input('请输入一个数字:')

Checking if a character is a digit is easy once you realize that characters are just ASCII code numbers. 一旦意识到字符只是ASCII码数字,就很容易检查字符是否为数字。 The character '0' is ASCII code 48 and the character '9' is ASCII code 57. '1'-'8' are in between. 字符“ 0”是ASCII码48,字符“ 9”是ASCII码57。介于“ 1”-“ 8”之间。 So you can check if a particular character is a digit by writing: 因此,您可以通过编写以下命令来检查特定字符是否为数字:

validNumber=False validNumber = False

while not validNumber: 无效时:

string = raw_input('please enter a number:') 字符串= raw_input('请输入一个数字:')

i=0 i = 0

validNumber=True validNumber =真

while i 当我

if not (string[i]>='0' and string[i]<='9'): 如果不是(string [i]> ='0'和string [i] <='9'):

validNumber=False validNumber = False

print 'You entered an invalid number. 打印“您输入的号码无效。 Please try again' 请再试一次'

break 打破

i=i+1 i = i + 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM