尝试做一个布尔测试循环,其中用户需要输入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()
答案 0 :(得分:1)
您可以尝试这样的事情,因为它还会检查用户是否输入了有效的数字:
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!
答案 1 :(得分:0)
好的,首先:
(num_years < 10) and (num_years > 1000)
这总是假的,因为一个数字不能同时小于10且大于1000。
其次
num_years == range(10, 1000)
将永远不会有效,因为左边有(可能)整数,右边有generator。
但是你可能会尝试这样的事情:
possible_years = range(10,101)
num_years = 50
while num_years in possible_years: # or 9 < num_years < 100
print("Your input must be 10 and 1000")
entered_years = input("Enter number of years to simulate (currently " + str(num_years) + "): ")
num_years = int(entered_years) # remeber to check if entered_years is int before this line!
else:
print()
但是仍有一个问题,您需要检查用户是否输入了整数。
答案 2 :(得分:0)
您永远不会更改num_years
的值,因此条件永远不会改变。修复你的布尔逻辑:
num_years = 0
while (num_years < 10) or (num_years > 1000):
print("Your input must be 10 and 1000")
num_years = int(input("Enter number of years to simulate (currently {}): ".format(num_years)))
else:
print()
但是,如果您需要覆盖非数字值然后使用try: except: pass
块,则假设有人输入了数字:
try:
num_years = int(input("Enter number of years to simulate (currently {}): ".format(num_years)))
except ValueError:
pass
注意:=
是赋值而非等同性测试。使用in
来测试值是list
还是range
。
答案 3 :(得分:0)
您需要做的是使用while循环来检查输入是否有效。如果不是,它将再次循环。此外,您永远不会将输入分配给变量。
n = None
while n is None or not 10 <= n <= 1000:
if n is not None: # Only happens if it's not the first input
print('Invalid number, please try again')
try:
n = int( input('Enter number of years to simulate (10-1000): ') ) # Convert the
# string to an int
except:
pass
print( 'Simulating {} years...'.format(n) )
一旦输入有效数字,它将继续并说模拟,因为
not 10 <= n <= 1000
将评估为假。
您可以通过以下链接进行试用:https://repl.it/FftK/0
答案 4 :(得分:0)
n =无 n是无或不是10 <= n <= 1000:
if n is not None: # Only happens if it's not the first input
print('Invalid number, please try again')
try:
n = int( input('Enter number of years to simulate (10-1000): ') ) # Convert the
# string to an int
except:
pass
打印(&#39;模拟{}年......&#39; .format(n))