Python 3.x Python初学者(需要帮助)-如何使While循环只接受某些用户输入?
Python初学者使用3.8.1。我试图得到这个while循环,只接受正确或错误的答案,但我遇到了一些困难。有人想帮忙吗?谢谢Python 3.x Python初学者(需要帮助)-如何使While循环只接受某些用户输入?,python-3.x,Python 3.x,Python初学者使用3.8.1。我试图得到这个while循环,只接受正确或错误的答案,但我遇到了一些困难。有人想帮忙吗?谢谢 for i in range(0, int(v)): v = input("Enter question : ") while True: try: f = input("Enter answer : ")
for i in range(0, int(v)):
v = input("Enter question : ")
while True:
try:
f = input("Enter answer : ")
except ValueError:
continue #here I'm trying to make the program re-ask the previous input again if the answer is not (true) or (false) as in a true/false quiz
else:
pass #here the program should simply pass to next user input when the answer is either (true) or (false).
while True意味着while循环将永远运行,因为True是一个不会更改的内置值。您可以做的是检查输入是否有效,然后中断while循环
for i in range(0, int(v)):
v = input("Enter question : ")
while True:
f = input("Enter answer : ")
# If the answer in lowercase is "true" or "false", then break out of the while loop
if f.lower() in ('true', 'false'):
break
# Prompt the user again if the answer isn't "true" or "false"
else:
print("Invalid input. Pass in \"True\" or \"False\"!")
谢谢就像我想的那样。你知道怎么用数字代替文字吗?我不知道你想用什么数字,但如果你处理的是像整数这样的简单情况,那么你能做的就是这样。如果f.isdigit和intf为0,则1:可以。谢谢你的帮助!