Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does python tell me that there is a syntax error in my code?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading