I'm using Python to make a calculator for leap years. Through several corrections, something was still missing and I ended up using Thonny.
The program told me to change everything from else to elif, but gives me a syntax error for the colon like this:
year = int(input("Which year do you want to check? "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year")
elif:
print("Not a leap year")
elif:
print("Leap year")
elif: year % 4 /= 0:
print("Not a leap year")
Traceback (most recent call last):
File "/Users/op108/Leap year calc.py", line 6
elif:
^
SyntaxError: invalid syntax
CodePudding user response:
Your error is caused by the Python's keyword elif.
if (condition):
...
elif (condition):
...
else:
...
You can't use the keyword elif without specifying a condition after it, and if you do it you shouldn't put : between elif and its condition.
An other error in your code is caused by /= operator, that in Python isn't the contrary of ==: did you mean !=?
In your case:
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year")
else:
print("Not a leap year")
else:
print("Leap year")
else:
print("Not a leap year")
I would suggest to write it using or and and in conditions instead of all these nested ifs:
if (year%4 == 0 and (year0 != 0 or year@0 == 0)):
print("Leap year")
else:
print("Not a leap year")
CodePudding user response:
On line 6 (and line 8 as well), you need to use else instead of elif, since you are not checking an additional conditional. elif is appropriate on line 10 (since you are checking another condition), but you have a syntax problem there as well (see the comment on /=).
CodePudding user response:
The problem is arising due to the elif on lines 6 and 8. You must specify a condition when you are using elif. In your case, you should use else instead of elif on lines 6 and 8 as follows:
year = int(input("Which year do you want to check? "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year")
else:
print("Not a leap year")
else:
print("Leap year")
elif year % 4 != 0:
print("Not a leap year")
Also, on line 10 your syntax is wrong, where you should use != instead of /=. However, this an overkill and you really should just use else on line 10 as well, as you have already checked the opposite condition in line 2.
