Python年转月/分钟/秒程序问题求助:选单一单位却输出全部结果
问题分析与修正方案
你的程序之所以会输出所有转换结果,核心问题是if条件判断的逻辑写法错误:
- 比如你写的
if unit == "Months" or "months",Python会把"months"单独作为一个判断条件,而非空字符串在布尔判断里永远是True,所以不管你输入什么单位,这个条件都会成立 - 第三个判断里还写错了单位,应该是
"Seconds"或"seconds",你写成了"second",少了个s
正确的写法有两种:
- 明确判断两种大小写情况:
Year = int(input("Years: ")) unit = input("Months or Minutes or Seconds: ") if unit == "Months" or unit == "months": convert = Year * 12 print(str(convert)) if unit == "Minutes" or unit == "minutes": convert1 = Year * 525600 print(str(convert1)) if unit == "Seconds" or unit == "seconds": convert2 = Year * 31536000 print(str(convert2))
- 把输入的单位转成小写(或大写),简化判断:
Year = int(input("Years: ")) unit = input("Months or Minutes or Seconds: ").lower() # 统一转成小写 if unit == "months": convert = Year * 12 print(str(convert)) elif unit == "minutes": # 用elif更高效,避免多余判断 convert1 = Year * 525600 print(str(convert1)) elif unit == "seconds": convert2 = Year * 31536000 print(str(convert2))
第二种写法里用elif代替多个if,只要有一个条件满足就不会再执行后面的判断,效率更高,也更符合你的需求。
内容的提问来源于stack exchange,提问作者Nathan Arora
相关产品推荐
相关产品推荐

