我试图创建一个函数,从用户接收3个不同的输入并验证它们以确保它们都是正整数。这是我目前的代码
def get_positive_number(prompt):
condition = False
while condition == False:
time = (input("Number of time units:"))
if not time.isnumeric() or int(time) == 0:
print("{} is not a valid number".format(time))
condition = False
elif int(time) > 0
timeInt = int(time)
condition = True
while condition == False:
atoms = (input("Number of atoms to simulate:"))
if not atoms.isnumeric() or int(atoms) == 0:
print("{} is not a valid number".format(atoms))
condition = False
elif int(atoms) > 0
atomInt = int(atoms)
condition = True
while condition == False:
radius = (input("Radius of beaker:"))
if not radius.isnumeric() or int(radius) == 0:
print("{} is not a valid number".format(radius))
condition = False
elif int(radius) > 0
RadInt = int(time)
condition = True
pass
答案 0 :(得分:0)
将来,我鼓励您搜索代码以进行大量重复。您的代码中有很多语句几乎是彼此的完全相同的副本。在回复发布的问题时,以下代码可用于检索三个正整数,从函数作为列表返回:
def get_positive_integers():
positiveNums = []
for i in range(0, 3):
num=-1
while num < 0:
num = int(input("Enter a positive number {}".format(i)))
positiveNums.append(num)
return positiveNums
话虽这么说,如果你想要特定的提示(如在你的示例代码中),你可以将它们作为列表传递给函数,并使用.format()
函数来插入它们。