python - 如何仅使用 If、elif 语句解决基本的里氏量表问题
问题描述
我是一个完整的初学者,但正在通过练习编写一个读取输入并显示描述符的程序。
对于以下代码:
- 预期结果是“流星”
- 当前结果是“非常轻微”
我知道这是基本的,但必须从某个地方开始。
我究竟做错了什么?
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")
解决方案
你得到了一些倒退的条件。
我为解决它所做的就是使代码(对我自己)更具可读性,然后,就像魔术一样,错误消失了。
我是说,如果你能快速阅读你的代码,这可能意味着你可以快速调试它,这意味着它的错误更少。
- 只使用
<
and<=
,而不是>
and>=
,总是用你的眼睛而不是你的逻辑来看待手头的条件 - 无需将数字转换为
3.0
浮点数。
工作代码:
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