英文:
Why does "if" work instead of "elif" in this specific code?
问题
我正在尝试解决我的编码问题的变化,并一直在尝试弄清楚为什么在第二行中使用 "elif" 时代码只能在特定情况下运行,而不是 "if"。但在其他情况下,我的 "elif" 在后面的部分中正常工作。
英文:
I am trying to figure out variations to my coding problem, and have been trying to figure out what "elif" doesn't work in the second line here:
if year % 4 == 0:
elif year % 100 != 0:
print("Leap year.")
elif year % 100 == 0:
if year % 400 !=0:
print("Not leap year.")
elif year % 400 == 0:
print("Leap year.")
else:
print("Not leap year.")
Why is it that in that second line, the code only runs if I use "if" instead of "elif" in that specific line? But in other instances, my "elif" works okay in the later parts?
答案1
得分: 1
elif
在你的第二行不起作用,因为它没有考虑到第1行的if
,因为它的缩进级别不同。
它期望在与elif
相同缩进级别的位置上有另一个if
语句。
英文:
The elif
on your second line does not work because it is not considering the if
on line 1, since it is not the same indention level.
It is expecting another if
statement above the elif
that is in the same indentation level.
答案2
得分: 0
elif语句用于指定一个附加条件,如果前面的if或elif条件为False,则检查该条件。在您的代码中,elif语句紧跟在if语句之后,没有任何先前的条件。
正在工作的您的代码示例:
if year % 4 == 0 and year % 100 != 0:
print("闰年。")
elif year % 100 == 0:
if year % 400 == 0:
print("闰年。")
else:
print("非闰年。")
else:
print("非闰年。")
英文:
The elif statement is used to specify an additional condition to be checked if the previous if or elif condition/conditions evaluate to False. In your code the elif statement appears immediately after an if statement, without any previous condition.
Example of your code that is working:
if year % 4 == 0 and year % 100 != 0:
print("Leap year.")
elif year % 100 == 0:
if year % 400 == 0:
print("Leap year.")
else:
print("Not leap year.")
else:
print("Not leap year.")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论