Python If Statement

The Python if statement is just a regular conditional statement (similar to conditional statements in other languages) which allows your program to make decisions based on the result of the specified condition.

In this Python tutorial, we will look at the syntax of the Python if statement and how to use it in your Python scripts to make decisions and make your scripts smarter.

The Python tutorial below explains.

Python If Statement Syntax

The syntax of the if statement in Python is shown below. As shown, it can be used for multiple conditions:

if condition:
	# do a particular action only if the condition is true
elif other condition:
	# do a particular action if this other condition is true
else:
	# do this particular action if nothing else was true

As we should know, condition (as used in the pseudocode above) is an expression which evaluates to either true or false, that is, a boolean value.

Python If Statement Example

Take a look at the Python script below:

#!/usr/bin/python
 
number = 5
 
# get a choice from the user
choice = int(raw_input('Guess a number: '))
 
if choice == number:
        print 'You are correct!'
elif choice < number:
        print 'The correct number is higher than that'
else:
        print 'The correct number is lower than that'

As you can see, the script asks the user to input a number and then compares it (using an if statement) to the secret number. If the user guessed correctly, they will get message saying they are correct.

If the guess was not correct, the elif clause would be executed. This part of the script checks if the choice the user made is less than the secret number. If it is, they are told that the correct number is higher than that.

The final else does not have a condition attached to it. This will get executed if none of the previous conditions were met. Since we already checked for equality, and then if the choice was less than the secret number, the only other possibility is that the choice was greater than the secret number, so we need not explicitly state that condition since it is implied by simple logic. Of course, if they guessed too high, they get a message that the secret number is lower than that.

Try it for yourself. You should get something similar to below:

# python python.py
Guess a number: 3
The correct number is higher than that
# python python.py
Guess a number: 7
The correct number is lower than that
# python python.py
Guess a number: 5
You are correct!

Note that you do not need to have all three parts of the if statement. You can easily omit the elif portion and the else portion based on your requirements. Those parts of the if statement are only there to allow the script to take action or do further comparisons if the initial condition was not met.

We hope this tutorial on the Python If Statement was helpful.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...