下面是我的代码,应该取3个正整数作为用户的输入。然而,它并没有按照预期工作。在
def getPositiveNumber(prompt):
timeUnits = (input("This is the numnber of time units to simulate > "))
numAtoms = (input("How many atoms should we simulate ? "))
radBeaker = (input("The radius of the beaker is ? "))
while True:
if timeUnits.isnumeric() and numAtoms.isnumeric() and radBeaker.isnumeric():
print("All your values are integers")
break
else:
timeUnits = input("This is the number of units to simulate. >")
numAtoms = input("How many atoms should we simulate ? ")
radBeaker = input("The radius of the beaker is ? ")
return timeUnits, numAtoms, radBeaker
这会导致在最初的3个输入被放置之后再次询问输入,但是如果我输入一个非数字,我希望它在初始部分之后再次询问。在
您可以分开测试来检查输入是否是函数的正整数
接下来,您可以创建一个函数来请求一个正整数。为此,请避免使用
^{pr2}$str.isnumeric
方法,因为它也为浮点返回True
。而是使用str.isdigit
方法。在request_input
将永远循环,直到收到正整数。这些简单的模块可以组合起来实现您想要的。特别是您的情况:编写三个几乎完全相同的代码片段来读取三个整数是没有意义的。你需要一个得到一个数的函数。您可以调用此函数三次,事实上,可以根据需要调用任意次数:
该函数依赖于这样一个事实,即
int()
识别的任何字符串都是有效的整数。如果是,则将号码返回给调用者。如果不是,则由int()
引发一个异常,使循环继续。在示例:
^{pr2}$试试这个:
相关问题 更多 >
编程相关推荐