Python中如何使变量赋值与if条件判断正常工作?
问题解决
两个核心错误修正:
字符串比较未加引号
代码第7行的m是未定义的变量,而用户输入的sex是字符串类型,必须和字符串'm'做比较。将if sex == m:改为if sex == 'm':。输入未转换为整数
第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
相关产品推荐
相关产品推荐

