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

Python验证循环异常:输入非法答案时未重复询问目标问题

问题原因

你的循环验证失效是因为条件判断逻辑错误:比如if diabetes == 'y' or 'yes'这种写法,Python会把它解析成(diabetes == 'y') or 'yes',而'yes'是一个非空字符串,永远被视为True,所以不管输入什么内容,第一个if条件都会成立,直接执行break,根本不会进入else分支提示用户重新输入。

修正方案

1. 修复条件判断逻辑

把每个判断条件改成检查输入是否在允许的选项列表中,同时统一转为小写,兼容用户输入大写(比如Y/YES)的情况:

# Calculate Family Disease Scores

diabetes = ''
while True:
    diabetes = input('\n Do you have a family history of Diabetes? (Answer yes or no)').strip().lower()
    if diabetes in ['y', 'yes']:
        diabetesScore = 10
        break
    elif diabetes in ['n', 'no']:
        diabetesScore = 0
        break
    else:
        print('Please answer Yes or No')

cancer = ''
while True:
    cancer = input('\n Do you have a family history of cancer? (Answer yes or no)').strip().lower()
    if cancer in ['y', 'yes']:
        cancerScore = 10
        break
    elif cancer in ['n', 'no']:
        cancerScore = 0
        break
    else:
        print('Please answer Yes or No')

alzheimers = ''
while True:
    alzheimers = input('\n Do you have a family history of alzheimers? (Answer yes or no)').strip().lower()
    if alzheimers in ['y', 'yes']:
        alzheimersScore = 10
        break
    elif alzheimers in ['n', 'no']:
        alzheimersScore = 0
        break
    else:
        print('Please answer Yes or No')

# 计算总风险分
total_score = diabetesScore + cancerScore + alzheimersScore
print(f"\nTotal family disease risk score: {total_score}")

2. 优化代码(避免重复逻辑)

三个问题的处理逻辑完全一致,可以封装成一个通用函数,减少代码冗余:

def get_family_history_score(disease_name):
    while True:
        response = input(f'\n Do you have a family history of {disease_name}? (Answer yes or no)').strip().lower()
        if response in ['y', 'yes']:
            return 10
        elif response in ['n', 'no']:
            return 0
        else:
            print('Please answer Yes or No')

# Calculate Family Disease Scores
diabetesScore = get_family_history_score('Diabetes')
cancerScore = get_family_history_score('cancer')
alzheimersScore = get_family_history_score('alzheimers')

total_score = diabetesScore + cancerScore + alzheimersScore
print(f"\nTotal family disease risk score: {total_score}")

关键改进点

  • 使用.strip()去除输入前后的空格,避免用户输入空格导致判断失败
  • 使用.lower()统一转为小写,兼容Y/YES/No等多种输入格式
  • 用in ['y', 'yes']替代错误的or逻辑,确保只有输入符合选项时才会跳出循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:20:34