在Python3中查找字符串是否为数字的更简单方法

在Python3中查找字符串是否为数字的更简单方法,python,python-3.x,Python,Python 3.x,我对编程很陌生。我试图找出如何检查用户输入(以字符串形式存储)是否为整数且不包含字母。我在论坛上查阅了一些资料,最后得出以下结论: while 1: #Set variables age=input("Enter age: ") correctvalue=1 #Check if user input COULD be changed to an integer. If not, changed variable to 0 try: variable =

我对编程很陌生。我试图找出如何检查用户输入(以字符串形式存储)是否为整数且不包含字母。我在论坛上查阅了一些资料,最后得出以下结论:

while 1:

#Set variables
    age=input("Enter age: ")
    correctvalue=1

#Check if user input COULD be changed to an integer. If not, changed variable to 0
    try:
        variable = int(age)
    except ValueError:
        correctvalue=0
        print("thats no age!")

#If value left at 1, prints age and breaks out of loop.
#If changed, gives instructions to user and repeats loop.
    if correctvalue == 1:
        age=int(age)
        print ("Your age is: " + str(age))
        break
    else:
        print ("Please enter only numbers and without decimal point")
现在,它的工作原理如图所示,满足了我的要求(询问这些人的年龄,直到他们输入一个整数),但是对于这样一件简单的事情来说,它相当长。我试图找到一个,但我得到了太多的数据,我还不明白


是否有一个简单的较短的方法或甚至是一个简单的函数来完成此操作?

您可以通过删除不必要的
correctvalue
变量和
break
ing或
continue
-ing(如有必要)来缩短此操作

while True:
    age=input("Enter age: ")    
    try:
        age = int(age)
    except ValueError:
        print("thats no age!")
        print ("Please enter only numbers and without decimal point")
    else:
        break

print ("Your age is: " + str(age))
while True:

    age = input("Enter age: ")

    try:
        age = int(age)
    except ValueError:
        print("That's no age!")
        print("Please enter only numbers and without decimal point")
        continue

    print ("Your age is: " + str(age))
    break

您的代码可以像这样缩短一点。我打算建议将
correctvalue
变量从整数
1
0
更改为布尔值
True
False
,但无论如何它都是多余的<代码>继续可用于根据需要重复循环

while True:
    age=input("Enter age: ")    
    try:
        age = int(age)
    except ValueError:
        print("thats no age!")
        print ("Please enter only numbers and without decimal point")
    else:
        break

print ("Your age is: " + str(age))
while True:

    age = input("Enter age: ")

    try:
        age = int(age)
    except ValueError:
        print("That's no age!")
        print("Please enter only numbers and without decimal point")
        continue

    print ("Your age is: " + str(age))
    break
使用isdigit()

比如说:

while True:

    #Set variables
    age=input("Enter age: ")

    #Check 
    if not age.isdigit():
        print("thats no age!")
        continue

    print("Your age is: %s" % age)
    age = int(age)  
    break

这适用于非负整数(即,无符号标记):


其思想是不断循环,直到用户输入一个只包含数字的字符串(这就是原因)。

实际上它不会变得更短。Python有
True
False
——不要使用
0
1
作为标志。另外,无论您使用哪一个,它都是
如果correctvalue:
。我对该站点非常陌生,但这不属于代码审查吗?OP发布工作代码并要求改进。尽管它可以满足这个特定年龄段的需求,但它不处理负数。目前,问题标题要求进行整数检查。根据大多数哲学/惯例,这并不更好。太棒了!正是我想要的。谢谢。您不需要在while循环的顶部使用
variable='
。我还认为
try:int(x)except ValueError:
表单在这种情况下比我的短一行:)如果
except
包含一个
continue
,为什么要使用
else
?好问题:)我想在try语句后面还有一些代码,但是当我删除它时忘记删除
continue