func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
这里我试图将用户限制在0-6之间。所以,如果他超出范围,他就无法继续
答案 0 :(得分:0)
首先,要获得用户的输入,根据您使用的python版本,您需要执行以下操作:
对于python 2:
user = raw_input("Enter a number between 0 and 6: ")
对于python 3:
user = input("Enter a number between 0 and 6: ")
现在,要检查用户输入的值是否在0到6之间,您需要进行以下检查:
if 0 <= int(user) <= 6:
...
OR
if int(user) in range(7):
...
OR
if int(user) >= 0 and int(user) <= 6:
...
所有这些都是有效的。请务必注意,user
将是一个字符串,因此int(user)
。
然后在函数中,如果它们输入的值不在0到6之间,则可以引发异常:
raise ValueError("Invalid number input, must be within 0 and 6")
所以最后你会得到这样的东西:
>>> import random
>>> pc_num = random.randint(0, 6) #Between 0 and 6, inclusive.
>>> while true:
user_num = int(input("Enter a number between 0 and 6: "))
if 0 <= user_num <= 6:
if user_num < pc_num:
print("low")
elif user_num > pc_num:
print("high")
else:
print("correct")
break
else:
raise ValueError("Invalid number input, must be within 0 and 6")
答案 1 :(得分:0)
您可以使用while循环从用户输入读取,然后验证用户的输入,如果它满足您的需要,您只需打破循环,否则,您可以继续循环以请求输入。
对于Python3:
while True:
try:
user = int(input('Choose a number: '))
except ValueError:
print("Not a number")
exit(-1)
if 0 <= user <= 6:
break
else:
print("Make sure the input is between 0 to 6")
# process with the user variable
print(user)