- How To Fix SyntaxError: invalid syntax in if statement in Python
- Why does the SyntaxError: invalid syntax error occur in the If statement?
- Solution for SyntaxError: invalid syntax in if statement in Python
- Lowercase “if”
- Use the correct comparison operator
- Don’t forget the colon.
- Summary
- Python if else syntaxerror invalid syntax
- # SyntaxError: invalid syntax in if statement in Python
- # Using a single equals sign when comparing
- # Use double equals when comparing values
- # Make sure the line of the if statement ends with a colon
- # Forgetting to indent your code properly
- # Having an empty block of code
- # The code above the if statement might be causing the error
- # The else statement should also end with a colon
- # Make sure you don’t have spelling errors
- # Additional Resources
- if, else, elif
- Using not With if Statements
- if Statements and Truthiness
- if Statements and Functions
- Nested if Statements
- How Not To Use if Statements
- else
- elif Means Else, If.
How To Fix SyntaxError: invalid syntax in if statement in Python
The error SyntaxError: invalid syntax in if statement in Python occurs when the syntax of the if statement is incorrect, such as capitalizing If , miswriting the “ == ” operator, or forgetting to put a colon. In this article, we will show the causes and solutions.
Why does the SyntaxError: invalid syntax error occur in the If statement?
When learning Python, it will be elementary to encounter basic syntax errors in Python, the SyntaxError: invalid syntax error in the If statement can happen because we capitalize the letter If , using the “ = ” sign instead of the “ == ” . Or maybe we forgot the colon at the end of the sentence. Let’s take a look at a few examples that create errors.
Python is a case-sensitive language, so when capitalizing If word, we will get SyntaxError: invalid syntax error.
Error Example:
price1 = 199 price2 = 299 # Error occurs when capitalizing "If" If price1 == price2: print("price 1 equals price 2")
SyntaxError: invalid syntax
Errors can also occur when using the wrong operator equals comparison conditions. The example below uses the “ = ” operator for comparison.
Error Example:
price1 = 199 price2 = 299 # Use "=" operator for comparison if price1 = price2: print("price 1 equals price 2")
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
Sometimes forgetting to put a colon at the end of the “if” statement will cause the error
Error Example:
price1 = 199 price2 = 299 # Forget to put a colon at the end of the "if" statement if price1 == price2 print("price 1 equals price 2")
Solution for SyntaxError: invalid syntax in if statement in Python
We have understood a few causes of errors. The solution is straightforward. Pay attention to the syntax when you write the if statement.
Lowercase “if”
Python is a case-sensitive language, so the correct syntax is that we should lowercase this if word. Then the Error will be fixed
price1 = 199 price2 = 299 # Lowercase this "if" word if price1 == price2: print("price 1 equals price 2") else: print("price 1 not equals price 2")
price 1 not equals price 2
Use the correct comparison operator
To compare in Python, we use the operator “ == “, not the operator “ = ” because the sign “ = ” is an assignment in Python.
price1 = 199 price2 = 199 # Use the operator "==" to compare if price1 == price2: print("price 1 equals price 2") else: print("price 1 not equals price 2")
Don’t forget the colon.
To avoid errors, you should remember to put a colon at the end of the statement and the end of the “else” word.
price1 = 199 price2 = 199 # Remember to put a colon at the end of the statement if price1 == price2: print("price 1 equals price 2") else: print("price 1 not equals price 2")
Summary
The article has covered a few simple syntax errors in the if statement that Python beginners often encounter. Pay attention to the syntax while writing the statement. We will never encounter the same Error. We hope you understand and fix the Error soon.
Carolyn Hise has three years of software development expertise. Strong familiarity with the following languages is required: Python, Typescript/Nodejs, .Net, Java, C++, and a strong foundation in Object-oriented programming (OOP).
Python if else syntaxerror invalid syntax
Last updated: Feb 17, 2023
Reading time · 4 min
# SyntaxError: invalid syntax in if statement in Python
The Python «SyntaxError: invalid syntax» is often caused when we use a single equals sign instead of double equals in an if statement.
To solve the error, use double equals == if comparing values and make sure the line of the if statement ends with a colon.
# Using a single equals sign when comparing
Here is an example of how the error occurs.
Copied!name = 'Bobby Hadz' # ⛔️ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? if name = 'Bobby Hadz': print('success')
The error is caused because we used a single equals sign instead of double equals.
# Use double equals when comparing values
If comparing values, make sure to use double equals.
Copied!name = 'Bobby Hadz' # ✅ Using double equals when comparing if name == 'Bobby Hadz': # 👇️ this runs print('success')
Always use double equals (==) when comparing values and single equals (=) when assigning a value to a variable.
Copied!# ✅ assignment single (=) equals name = 'bobby hadz' # ✅ comparison double (==) equals if name == 'bobby hadz': print('success')
# Make sure the line of the if statement ends with a colon
Make sure the line of the if statement ends with a colon : .
Copied!name = 'bobby hadz' if name == 'bobby hadz': # 👈️ must end with colon print('success')
If you forget the colon at the end of the line, the error occurs.
# Forgetting to indent your code properly
Another common cause of the error is forgetting to indent your code properly.
Copied!name = 'bobby hadz' if name == 'bobby hadz': print('one') # ⛔️ badly indented code print('two')
Use a tab to indent your code consistently in the entire if block.
Copied!name = 'bobby hadz' if name == 'bobby hadz': print('one') # ✅ proper indentation print('two')
The code in the if statement should be consistently indented.
Never mix tabs and spaces when indenting code in Python because the interpreter often has issues with lines indented using both tabs and spaces.
You can either use tabs when indenting code or spaces, but never mix the two.
# Having an empty block of code
If you need to leave a code block empty before you get to implement it, use a pass statement.
Copied!my_str = '100' if int(my_str) == 100: print('success') else: pass
The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.
Copied!class Employee: pass
Using a pass statement is necessary because leaving the else block empty would cause a SyntaxError .
Copied!my_str = '100' if int(my_str) == 100: print('success') else: # ⛔️ Error
# The code above the if statement might be causing the error
If the error is not resolved, look at the code that’s right above the if statement.
Make sure you haven’t forgotten to close a parenthesis ) , a square bracket ] or a curly brace > .
Copied!my_str = '100' # ⛔️ SyntaxError: invalid syntax if int(my_str == 100: print('success')
The code sample above has a missing closing parenthesis, which causes the error.
Make sure all your quotes «» , parentheses () , curly braces <> and square brackets [] are closed.
Copied!my_str = '100' # ✅ has a closing parenthesis now if int(my_str) == 100: print('success')
# The else statement should also end with a colon
If you have an if/else statement, make sure the else statement also ends with a colon and its code is indented consistently.
Copied!name = 'Alice' if name == 'Alice': # 👇️ this runs print('success') else: print('failure')
If you have an if or else statement that you haven’t yet implemented, use a pass statement.
Copied!name = 'Alice' if name == 'Alice': print('success') else: pass
The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.
# Make sure you don’t have spelling errors
You might get a SyntaxError exception if you have spelling errors.
Python is case-sensitive, so make sure to use lowercase keywords like if and else instead of If or Else .
Copied!my_str = '100' # ✅ keywords are case-sensitive if int(my_str) == 100: print('success') else: print('condition not met')
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
if, else, elif
if in Python means: only run the rest of this code once, if the condition evaluates to True . Don’t run the rest of the code at all if it’s not.
Anatomy of an if statement: Start with the if keyword, followed by a boolean value, an expression that evaluates to True , or a value with “Truthiness”. Add a colon : , a new line, and write the code that will run if the statement is True under a level of indentation.
Remember, just like with functions, we know that code is associated with an if statement by it’s level of indentation. All the lines indented under the if statement will run if it evaluates to True .
Remember, your if statements only run if the expression in them evaluates to True and just like with functions, you’ll need to enter an extra space in the REPL to run it.
Using not With if Statements
If you only want your code to run if the expression is False , use the not keyword.
>>> b = False >>> if not b: . print("Negation in action!") . Negation in action!
if Statements and Truthiness
if statements also work with items that have a “truthiness” to them.
- The number 0 is False-y, any other number (including negatives) is Truth-y
- An empty list , set , tuple or dict is False-y
- Any of those structures with items in it is Truth-y
>>> message = "Hi there." >>> a = 0 >>> if a: # 0 is False-y . print(message) . >>> b = -1 >>> if b: # -1 is Truth-y . print(message) . Hi there. >>> c = [] >>> if c: # Empty list is False-y . print(message) . >>> d = [1, 2, 3] >>> if d: # List with items is Truth-y . print(message) . Hi there.
if Statements and Functions
You can easily declare if statements in your functions, you just need to mindful of the level of indentation. Notice how the code belonging to the if statement is indented at two levels.
>>> def modify_name(name): . if len(name) < 5: . return name.upper() . else: . return name.lower() . >>> name = "Nina" >>> modify_name(name) 'NINA'
Nested if Statements
Using the same technique, you can also nest your if statements.
>>> def num_info(num): . if num > 0: . print("Greater than zero") . if num > 10: . print("Also greater than 10.") . >>> num_info(1) Greater than zero >>> num_info(15) Greater than zero Also greater than 10.
How Not To Use if Statements
Remember, comparisons in Python evaluate to True or False . With conditional statements, we check for that value implicitly. In Python, we do not want to compare to True or False with == .
Warning — pay attention, because the code below shows what you shouldn’t do.
# Warning: Don't do this! >>> if (3 < 5) == True: # Warning: Don't do this! . print("Hello") . Hello # Warning: Don't do this! >>> if (3 < 5) is True: # Warning: Don't do this! . print("Hello") . Hello
If we want to explicitly check if the value is explicitly set to True or False , we can use the is keyword.
>>> a = True # a is set to True >>> b = [1, 2, 3] # b is a list with items, is "truthy" >>> >>> if a and b: # this is True, a is True, b is "truthy" . print("Hello") . Hello >>> if a is True: # we can explicitly check if a is True . print("Hello") . Hello >>> if b is True: # b does not contain the actual value of True. . print("Hello") . >>>
else
The else statement is what you want to run if and only if your if statement wasn’t triggered.
An else statement is part of an if statement. If your if statement ran, your else statement will never run.
>>> a = True >>> if a: . print("Hello") . else: . print("Goodbye") . Hello
>>> a = False >>> if a: . print("Hello") . else: . print("Goodbye") . Goodbye
In the REPL it must be written on the line after your last line of indented code. In Python code in a file, there can’t be any other code between the if and the else .
You’ll see SyntaxError: invalid syntax if you try to write an else statement on its own, or put extra code between the if and the else in a Python file.
>>> if a: . print("Hello") . Hello >>> else: File "", line 1 else: ^ SyntaxError: invalid syntax
elif Means Else, If.
elif means else if. It means, if this if statement isn’t considered True , try this instead.
You can have as many elif statements in your code as you want. They get evaluated in the order that they’re declared until Python finds one that’s True . That runs the code defined in that elif , and skips the rest.
>>> a = 5 >>> if a > 10: . print("Greater than 10") . elif a < 10: . print("Less than 10") . elif a < 20: . print("Less than 20") . else: . print("Dunno") . Less than 10