python - 检查用户输入是否为数字

标签 python

<分区>

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

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)

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

最佳答案

你可以只使用str.isdigit()方法:

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

上述方法对于负数输入会失败。 '-5'.isdigit() 给出 False。因此,另一种解决方案是使用 try-except:

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

关于python - 检查用户输入是否为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18302780/

相关文章:

python - Series.replace 和 Series.str.replace 有什么区别?

python - Apache Beam - 如何在 Python 中通过键将 PCollection 分成 2 个

python - Pandas:如何对重复行的列中的值求和

python - 配置单元:python UDF提供 “Hive Runtime Error while closing operators”

Python - Mechanize 表单中的输入文本

python - 在Python多处理中共享和编辑numpy数组

python - Pyramid 中的自定义路由谓词

python - ORM 模型更改导致类似 "column … does not exist"的错误

python - 拟合模型时,batch size 和 epoch 的数量应该有多大?

python - 如何让progame只启动一个进程?