我是一个完全的初学者,但通过一个练习来编写一个程序来读取输入和显示描述符。
关于以下代码:
预期结果是"Meteoric"
我知道这是基本的,但要从某个地方开始。
我做错了什么?
mag = float(10)
# Determine the richter
if mag < float(2.0):
print("Micro")
elif mag >= float(2.0) < float(3.0):
print("Very Minor")
elif mag >= float(3.0) < float(4.0):
print("Minor")
elif mag >= float(4.0) < float(5.0):
print("Light")
elif mag >= float(5.0) < float(6.0):
print("Moderate")
elif mag >= float(6.0) < float(7.0):
print("Strong")
elif mag >= float(7.0) < float(8.0):
print("Major")
elif mag >= float(8.0) < float(10.0):
print("Great")
elif mag >= float(10.0):
print("Meteoric")
else:
print("Error")发布于 2020-10-23 11:10:30
你把一些条件倒过来了。
我为解决这个问题所做的就是让代码更易读(对我自己来说),然后,就像魔法一样,错误消失了。
我的意思是,如果您能够快速阅读代码,这可能意味着您可以快速调试它,这意味着它有较少的bug。
<和<=,而不使用>和>=,以便始终用眼睛而不是从逻辑中看到手边的条件--3.0等数字转换为浮动。G 210
工作代码:
mag = float(10)
# Determine the richter
if mag < 2.0:
print("Micro")
elif 2.0 <= mag < 3.0:
print("Very Minor")
elif 3.0 <= mag < 4.0:
print("Minor")
elif 4.0 <= mag < 5.0:
print("Light")
elif 5.0 <= mag < 6.0:
print("Moderate")
elif 6.0 <= mag < 7.0:
print("Strong")
elif 7.0 <= mag < 8.0:
print("Major")
elif 8.0 <= mag < 10.0:
print("Great")
elif 10.0 <= mag:
print("Meteoric")
else:
print("Error")问题是:
像mag >= float(2.0) < float(3.0):这样的条件
翻译成
mag >= float(2.0) and float(2.0) < float(3.0):
这和
True and True:
那就是
True
你得到了Very Minor
https://stackoverflow.com/questions/64498674
复制相似问题