2

我正在尝试比较用户收到的输入,以检查输入是否实际上是数字。这是我到目前为止所拥有的:

numstring = input("Choose a number between 1 and 10")

然后比较我有这样的方法:

def check(a):
   if int(a) == int:
       print("It's a number!")
   else:
       print("It's not a number!")

它总是打印出它不是一个数字,即使它是。

这个程序的目标:我正在做一个猜谜游戏:

import random

numstring = input("Choose a number between 1 and 10")

def check(a):
    if int(a) == int:
        print("It's a number!")
    else:
        print("It's not a number!")

    if abs(int(a)) < 1:
        print("You chose a number less than one!")
    elif abs(int(a)) > 10:
        print("You chose a number more than ten!")
    else:
        randomnum = random.randint(1, 10)
        randomnumstring = str(abs(randomnum))
        if randomnum == abs(int(a)):
            print("You won! You chose " + a + "and the computer chose " + randomnumstring)
        else:
            print("You lost! You chose " + a + " and the computer chose " + randomnumstring)


check(numstring)

谢谢你的帮助!实际的代码有效,但只是无法检查它。

4

3 回答 3

10

You can just use str.isdigit() method:

def check(a):
    if a.isdigit(): 
        print("It's a number!")
    else:
        print("It's not a number!")

The above approach would fail for negative number input. '-5'.isdigit() gives False. So, an alternative solution is to use try-except:

try:
    val = int(a)
    print("It's a number!")
except ValueError:
    print("It's not a number!")
于 2013-08-18T19:17:30.640 回答
5

int(a) and int are not equal because int() returns an integer and just int with no () is a type in python2.(or class in python3)

>>> a = '10'
>>> int(a)
10
>>> int
<type 'int'>

If you're only dealing with integers then use try-except with int as others have shown. To deal with any type of number you can use ast.literal_eval with try-except:

>>> from ast import literal_eval
>>> from numbers import Number
def check(a):
    try:
        return isinstance(literal_eval(a), Number)
    except ValueError:
        return False

>>> check('foo')
False
>>> check('-100')
True
>>> check('1.001')
True
>>> check('1+1j')
True
>>> check('1e100')
True
于 2013-08-18T19:17:52.483 回答
4

Try to cast an input to int in try/except block:

numstring = input("Choose a number between 1 and 10")

try:
    a = int(numstring)
    print("It's a number!")
except ValueError:
    print("It's not a number!")

If you are using python 2, consider switching to raw_input() instead of input(). input() accepts any python expression and this is bad and unsafe, like eval(). raw_input() just reads the input as a string:

numstring = raw_input("Choose a number between 1 and 10")

try:
    a = int(numstring)
    print("It's a number!")
except ValueError:
    print("It's not a number!")

Note that raw_input() has been renamed to input() in python 3.

Also see:

Hope that helps.

于 2013-08-18T19:17:40.913 回答