![](/img/trans.png)
[英]how do create while loop input for accept only 1 or 2 as input in python?
[英]Python Beginner (need assistance) - How do I make a While loop only accept certain user inputs?
Python初學者使用3.8.1。 我試圖讓這個 while 循環只接受答案 (true) 或 (false),但我遇到了一些困難。 有人想幫忙嗎? 謝謝!
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\"!")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.