SyntaxError: invalid syntax when using IF in Python – How to Resolve it

Hi friends! In this post, we will be talking about, how you can resolve the error message SyntaxError: invalid syntax when using IF statements in Python.

 

About the SyntaxError: invalid syntax error message in Python

The SyntaxError message, is one of the most common error messages someone who is just starting with Python programming might get.

Even though there might be many reasons for getting the SyntaxError message in Python, in this post, we are talking about the case where you might got the above error message when using IF statements in Python.

 

Let’s Reproduce the Error Message in Python

In order to reproduce the SyntaxError message when using IF statements in Python, for better understanding it, let’s consider the below code example:

# Problematic IF Statement
username="DemoUser"

if username.isalpha()
    print ("Valid value")
else
    print("Invalid value")

In the above code, we try to check if the value of the “username” variable is a string.

If however we execute the code, we get the below error message:

 File "c:\Demos\ErrorHandling.py", line 5
if username.isalpha()
                     ^
SyntaxError: invalid syntax

 

Why do we get the SyntaxError Message?

The reason we get the SyntaxError message for the above code, where we are using the IF…ELSE statement, is because in Python, after each one of the below statements, we always need to put a : in the end of the statement:

  • if
  • elif
  • else
  • for
  • while
  • class
  • def

 

Let’s Fix our Example’s Code

So now, let’s try to fix our example’s code by including the : character after the “if” and “else” statements:

# Correct IF Statement
username="DemoUser"

if username.isalpha():
    print ("Valid value")
else:
    print("Invalid value")

Now, if you run the above code, you will see that it executes without any issues.


Read Also:

 

Subscribe to the GnoelixiAI Hub newsletter on LinkedIn and stay up to date with the latest AI news and trends.

Subscribe to my YouTube channel.

 

Reference: aartemiou.com (https://www.aartemiou.com)
© Artemakis Artemiou

Rate this article: 1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)

Loading...