我对编程很陌生。我试图找出如何检查用户输入(存储为字符串)是否为整数且不包含字母。我在论坛上查了一些资料,最后得出这样的结论:
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")
现在,这是如图所示的工作方式,我想做什么(询问他们的年龄直到他们输入一个整数),然而对于这样一个简单的事情来说,这是相当长的。我试图找到一个,但我得到了太多的数据,我还不明白。在
有没有一个简单的方法,甚至是一个简单的函数来完成这个过程?在
您可以根据需要删除不必要的}-ing来缩短这段时间。在
correctvalue
变量和break
ing或{使用isdigit()
所以像这样:
^{pr2}$这适用于非负整数(即,没有符号标记):
其思想是不断循环,直到用户输入一个只包含数字的字符串(这就是^{} 所做的)。在
相关问题 更多 >
编程相关推荐