尝试做一个 boolean 测试循环,用户需要输入一个介于 10 和 1000 之间的数字,包括 10 和 1000,他们需要留在这个循环中,直到他们输入正确的数字,然后我将完成 else 语句.
我试过这个:
while (num_years < 10) and (num_years > 1000): # boolean test , note == (= will give you an error!)
print("Your input must be 10 and 1000")
input("Enter number of years to simulate (currently " + str(num_years) + "): ")
else:
print()
还有这个:
while (num_years == range(10, 1000)): # boolean test , note == (= will give you an error!)
print("Your input must be 10 and 1000")
input("Enter number of years to simulate (currently " + str(num_years) + "): ")
else:
print()
最佳答案
您可以尝试这样的操作,因为它还会检查用户输入的数字是否有效:
while True:
number = input("Enter number of years to simulate (10-1000): ")
try:
years = int(number)
if years >= 10 and years <= 1000:
break
else:
print("Your input must be between 10 and 1000 inclusive")
except ValueError:
print("That's not an int!")
print("Simulating %d years..." % years)
示例用法:
Enter number of years to simulate (10-1000): asd
That's not an int!
Enter number of years to simulate (10-1000): 5
Your input must be between 10 and 1000 inclusive
Enter number of years to simulate (10-1000): 245
Simulating 245 years...
试一试 here!
关于python - 我想返回 "duo"列表中顶级元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42171241/