My code is:
>>> x = 25
>>> if x%2 == 0:
... if x%10 == 0:
... print("foo")
... if x%7 == 0:
... print("bar")
>>> else:
print("baz")
Python keeps telling me that it has a syntax error as the picture shows. Can someone tell my why?
I asked GPT-4 on Microsoft Copilot and it told me that the code is without error.
>Solution :
Explanation
Looking at your image, I can see that you have not saved your code and are instead running it in the REPL.
The >>> indicates a new part of code is being run in the REPL, causing the else: part to be run without the context of the first if statement.
The REPL does not see the if statement before and thinks you are trying to use else without a corresponding if.
Solution
You can either use IDLE‘s built-in features to save your code in a python file, or copy and paste all of your code into the REPL at the same time.
x = 25
if x % 2 == 0:
if x % 10 == 0:
print("foo")
elif x % 7 == 0:
print("bar")
else:
print("baz")
Further reading
If … else tutorial on W3 schools