≡ Menu

9 Python if, if else, if elif Command Examples

Python If CommandSimilar to other programming languages, in Python, conditional situations can be handled using if command.

In this tutorial, we’ve explained the following with examples:

  1. Basic Python if Command Example for Numbers
  2. Python if Command Operators
  3. Basic Python if Command Example for String Comparison
  4. Multiple Commands in If Condition Block using Indentation
  5. Python if else Command Example
  6. Python if else if Command Example
  7. Python Compound If Statement Example
  8. AND, OR, NOT in Python if Command
  9. Python if Command Error Messages

This is the Python if statement syntax. The following examples will show how this syntax can be used properly.

if_stmt ::=  "if" expression ":" suite
             ( "elif" expression ":" suite )*
             ["else" ":" suite]

1. Basic Python if Command Example for Numbers

The following example illustrates how to use if command in python when we are doing a conditional testing using numbers.

# cat if1.py
days = int(input("How many days are in March?: "))
if days == 31:
  print("You passed the test.")
print("Thank You!")

In the above example:

  • 1st line: Here, we are asking for user input. The input will be an integer, which will be stored in the variable days.
  • 2nd line: This is the if command, where we are comparing whether the value of the variable days is equal to the numerical value 31. The colon at the end is part of the if command syntax, which should be given.
  • 3rd line: This line starts with two space indent at the beginning. Any line (one or more) that follows the if statement, which has similar indentation at the beginning is considered part of the if statement block. In this example, we have only one line after if statement, which is this 3rd line, which has two spaces in the beginning for indent. So, this line will be executed when the condition of the if statement is true. i.e If the value of the variable days is equal to 31, this 3rd will get executed
  • 4th line: This line is outside the if statement block. So, this will get executed whether the if statement is true or false.

The following is the output of the above example, when the if statement condition is true.

# python if1.py
How many days are in March?: 31
You passed the test.
Thank You!

The following is the output of the above example, when the if statement condition is false.

# python if1.py
How many days are in March?: 30
Thank You!

If you are new to python, this will give you a excellent introduction to Python Variables, Strings and Functions

2. Python if Command Operators

The following are the various operators that you can use in the if command for conditional checks.

Condition Operator
Greater than >
Greater than or equal >=
Less than <
Less than or equal to <=
Equal to ==
Not equal to !=
For object identity is
For negated object identity is not

3. Basic Python if Command Example for String Comparison

Similar to the previous example, we can also use Python if command for string comparison as shown in the example below.

# cat if2.py
code = raw_input("What is the 2-letter state code for California?: ")
if code == 'CA':
  print("You passed the test.")
print("Thank You!")

In the above:

  • 1st line: Here we are getting the raw input from the user and storing it in the code variable. This will be stored as string.
  • 2nd line: In this if command, we are comparing whether the value of the code variable is equal to the string ‘CA’. Please note that we have enclosed the static string value in single quote (not double quote). The : at the end is part of the if command syntax.
  • 3rd line: As explained in the previous example, this line will get executed when the if command condition is true, as this line has indentation with spaces at the beginning.
  • 4th line: This will get executed whether the if command condition is true or false.

The following is the output of the above example code for both if condition true and false.

# python if2.py
What is the 2-letter state code for California?: CA
You passed the test.
Thank You!

# python if2.py
What is the 2-letter state code for California?: NV
Thank You!

4. Multiple Commands in If Condition Block using Indentation

In the previous example, we had only one statement to be executed when the if condition is true.

The following example shows where multiple lines will get executed when the if condition is true. This is done by doing proper indentation at the beginning of the statements that needs to be part of the if condition block as shown below.

# cat if3.py
code = raw_input("What is the 2-letter state code for California?: ")
if code == 'CA':
  print("You passed the test.")
  print("State: California")
  print("Capital: Sacramento")
  print("Largest City: Los Angeles")
print("Thank You!")

In the above:

  • 1st line: Here we are getting the raw input from the user and storing it in the code variable. This will be stored as string.
  • 2nd line: In this if command, we are comparing whether the value of the code variable is equal to the string ‘CA’. Please note that we have enclosed the static string value in single quote (not double quote). The : at the end is part of the if command syntax.
  • 3rd line – 6th line: All these lines have equal indentation at the beginning of the statement. In this example, all these 4 print statements have 2 spaces at the beginning. So, these statements will get executed then the if condition becomes true.
  • 4th line: This print statement doesn’t have similar indentation as the previous commands. So, this is not part of the if statement block. This line will get executed irrespective of whether the if command is true or false.

The following is the output of the above example, when the if statement condition is true. Here all those 4 print statements that are part of the if condition block gets executed.

# python if3.py
What is the 2-letter state code for California?: CA
You passed the test.
State: California
Capital: Sacramento
Largest City: Los Angeles
Thank You!

The following is the output of the above example, when the if statement condition is false.

# python if3.py
What is the 2-letter state code for California?: NV
Thank You!

5. Python if else Command Example

The following example shows how to use if..else command in Python.

# cat if4.py
days = int(input("How many days are in March?: "))
if days == 31:
  print("You passed the test.")
else:
  print("You failed the test.")
print("Thank You!")

In the above example:

  • 1st line: Here, we are asking for user input. The input will be an integer, which will be stored in the variable days.
  • 2nd line: This is the if command, where we are comparing whether the value of the variable days is equal to the numerical value 31. The colon at the end is part of the if command syntax, which should be given.
  • 3rd line: This line starts with two space indent at the beginning. Any line (one or more) that follows the if statement, which has similar indentation at the beginning is considered part of the if statement block true condition.
  • 4th line: This has the else keyword for this if block. The colon at the end is part of the if..else command syntax, which should be given.
  • 5th line: This line starts with two space indent at the beginning. Any line (one or more) that follows the else statement, which has similar indentation at the beginning is considered part of the if statement block false condition.
  • 6th line: This line is outside the if statement block. So, this will get executed whether the if statement is true or false.

The following example is also similar to above example, but this if..else uses string variable for comparision.

# cat if5.py
code = raw_input("What is the 2-letter state code for California?: ")
if code == 'CA':
 print("You passed the test.")
else:
 print("You failed the test.")
print("Thank You!")

The following is the output of the above examples, when the if statement condition is false. i.e The else block will get executed here.

# python if4.py
How many days are in March?: 30
You failed the test.
Thank You!

# python if5.py
What is the 2-letter state code for California?: NV
You failed the test.
Thank You!

6. Python if else if Command Example

In Python, if else if is handled using if elif else format.

The following example shows how to use if..elif..else command in Python.

# cat if6.py
code = raw_input("Type a 2-letter state code that starts with letter C: ")
if code == 'CA':
  print("CA is California")
elif code == 'CO':
  print("CO is Colorado")
elif code == 'CT':
  print("CT is Connecticut")
else:
  print("Invalid. Please enter a valid state code that starts with letter C")
print("Thank You!")

In the above:

  • When the first if code == ‘CO’ condition fails, then it goes to the next elif command.
  • When the elif code == ‘CO’ condition fails, then it goes to the next elif code command.
  • When the elif code == ‘CT’ condition fails, then it just executes whatever is available as part of the final else: block.
  • At any point when the 1st if condition becomes true, or any one of the remaining elif condition becomes true, then it executes the statement that is part of its block and stops checking further condition.
  • This also means that when any of the if condition or elif condition becomes true, the statement that is part of the else block will not get executed.
  • Also, just like previous example, the colon at the end of if, elif, else command is part of the Python syntax, which should be specified.

The following is the output when the first if condition becomes true.

# python if6.py
Type a 2-letter state code that starts with letter C: CA
CA is California
Thank You!

The following is the output when the first elif condition becomes true.

# python if6.py
Type a 2-letter state code that starts with letter C: CO
CO is Colorado
Thank You!

The following is the output when the second elif condition becomes true.

# python if6.py
Type a 2-letter state code that starts with letter C: CT
CT is Connecticut
Thank You!

The following is the output when the if condition is false, and all the remaining elif condition is also false. Here this, executes the else block.

# python if6.py
Type a 2-letter state code that starts with letter C: NV
Invalid. Please enter a valid state code that starts with letter C
Thank You!

7. Python Compound If Statement Example

The following example shows how you can use compound conditional commands in the if statement.

# cat if7.py
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
if a < b < c: 
  print("Success. a < b < c")

In the above:

  • The print block will get executed only when the if condition is true. Here, we are using a compound expression for the if statement where it will be true only when a is less than b and b is less than c.

The following is the output when if condition becomes true.

# python if7.py
Enter a: 10
Enter b: 20
Enter c: 30
Success. a < b < c

The following is the output when if condition becomes false.

# python if7.py
Enter a: 10
Enter b: 10
Enter c: 20

8. AND, OR, NOT in Python if Command

You can also use the following operators in the python if command expressions.

Operator Condition Desc
and x and y True only when both x and y are true.
or x or y True if either x is true, or y is true.
not not x True if x is false. False if x is true.

 
The following example shows how we can use the keyword “and” in python if condition.

# cat if8.py
x = int(input("Enter a number > 10 and < 20: "))
if x > 10 and x < 20:
  print("Success. x > 10 and x < 20")
else:
  print("Please try again!")

In the above:

  • The if statement will be true only when both the condition mentioned in the if statement will be true.
    i.e x should be greater than 10 AND x should also be less than 20 for this condition to be true. So, basically the value of x should be in-between 10 and 20.

The following is the output when if condition becomes true. i.e When both the expressions mentioned in the if statement is true.

# python if8.py
Enter a number > 10 and < 20: 15
Success. x > 10 and x < 20

The following is the output when if condition becomes false. i.e Only one of the expression mentioned in the if statement is true. So, the whole if statement becomes false.

# python if8.py
Enter a number > 10 and < 20: 5
Please try again!

9. Python if Command Error Messages

The following are some of the error messages that you might see when using the if command.

This IndentationError error happens when you don’t give proper indentation for the statement that is following the if command.

# python if9.py
  File "if3.py", line 4
    print("State: California")
                             ^
IndentationError: unindent does not match any outer indentation level

The following SyntaxError happens when you don’t specify the colon : at the end of the python if statement

# python if9.py
  File "if.py", line 2
    if days == 31
                ^
SyntaxError: invalid syntax

The same SyntaxError will happen when you specify an operator that is invalid. In this example, there is no operator called -eq in python. So, this if command fails with syntax error. You’ll also get similar syntax error when you specify elseif instead of elif.

# python if9.py
  File "if.py", line 2
    if days -eq 31:
                 ^
SyntaxError: invalid syntax

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 0 comments… add one }

Leave a Comment