为什么在这个特定的代码中使用 “if” 而不是 “elif” ?

huangapple go评论61阅读模式
英文:

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.")

huangapple
  • 本文由 发表于 2023年5月28日 10:46:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349744.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定