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

Python学校作业代码运行异常:性别输入后死循环或无响应

问题根因
  • 循环条件逻辑错误:while 判断使用了逻辑或or,从布尔运算规则来看,任意输入都会满足至少一个!=判断,循环条件永远为真,程序进入死循环。
  • 代码缩进与逻辑顺序错误:女性性别的判断分支写在while循环外部,死循环状态下永远不会执行到该部分代码;同时原循环内没有设置重新输入性别的入口,输入非法值后也无法修正输入。
修复方案

调整逻辑为先做输入合法性校验,输入不属于指定性别范围时循环要求用户重新输入,校验通过后再执行对应问候输出,修正后代码如下:

name = input("Enter name :")
gender = input("are you a m/M or a f/F:")
# 校验输入合法性,输入错误时要求重输
while gender not in ['M', 'm', 'f', 'F']:
    print("输入不合法,请重新输入")
    gender = input("are you a m/M or a f/F:")
# 校验通过后输出问候
if gender in ['M', 'm']:
    print("Hello Mr", name, ",")
elif gender in ['F', 'f']:
    print("Hello Miss", name, ",")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:06:05