You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python循环,仅接受Yes/No输入并提示非法响应?

Fixing Your While Loop Input Validation

Hey there! No worries about asking "simple" questions—every programmer starts out learning these basics, and it's totally okay to need a hand with input validation. Let's adjust your code to only accept "Yes" or "No" (case-insensitive) as valid responses, and show "Invalid response" for any other input.

Here's the revised code:

name = input("What's your name? ")

# First, get a valid Yes/No response about understanding
while True:
    understanding = input(f"{name}, do you understand while loops in Python (Yes or No)? ")
    # Convert input to lowercase to handle case insensitivity
    lower_response = understanding.lower()
    if lower_response in ['yes', 'no']:
        break  # Exit the loop once we have a valid response
    else:
        print("Invalid response")

# Now handle the teaching loop until user says Yes
while lower_response != 'yes':
    print(f"Ok, {name}, while loops in Python repeat as long as a certain Boolean condition is met.")
    # Re-validate input each time we ask again
    while True:
        understanding = input(f"{name}, now do you understand Python while loops? (Yes or No)? ")
        lower_response = understanding.lower()
        if lower_response in ['yes', 'no']:
            break
        else:
            print("Invalid response")

print(f"Great news {name}! It's good to hear that you understand these loops now! Let's move on!")

Key Changes Explained:

  • Input Validation Loops: We added nested while True loops that keep running until the user enters a valid "Yes" or "No". This ensures we never proceed with invalid input.
  • Case Insensitivity: Using .lower() lets us accept variations like "YES", "No", or "yEs" as valid, which makes the program more user-friendly.
  • Clear Error Feedback: Whenever the user types something that's not Yes/No, we immediately print "Invalid response" and ask again.

This structure keeps your original teaching logic intact but adds the strict input validation you needed.

内容的提问来源于stack exchange,提问作者Joe2509

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:12:36