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

Python中如何使变量赋值与if条件判断正常工作?

问题解决

两个核心错误修正:

  1. 字符串比较未加引号
    代码第7行的m是未定义的变量,而用户输入的sex是字符串类型,必须和字符串'm'做比较。将if sex == m:改为if sex == 'm':。

  2. 输入未转换为整数
    第5行中,input()返回的是字符串,直接和整数52相乘会触发类型错误,需要先把输入转换为整数:
    原代码:ca = input("What is your current age in years? ") * 52
    修改为:ca = int(input("What is your current age in years? ")) * 52

修正后的完整代码:

# This works until line 7
sex = input("Are you male(m) or female(f)? ")
me = 75 * 52
fe = 80 * 52
ca = int(input("What is your current age in years? ")) * 52
print(sex)  # This is returning the input from the first line.
if sex == 'm':
    print(f"You have approximately {me - ca} weeks to live. ")
else:
    print(f"You have approximately {fe - ca} weeks to live. ")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:07:04