簡體   English   中英

Python 初學者(需要幫助)-如何使 While 循環僅接受某些用戶輸入?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM