Python if statements, if else statements and conditions tutorial
March 29 10:01PM • 5 min readIn this Article You will:
- Learn how to work with If statements in python
- Learn how to use else statements in python
- Learn how to use conditions in python
If statements are nessecary in python if you want a block of code to run if a certain condition is fulfilled. This can be useful when you want your code to run at a certain moment. For example, the following code will only print "So many Apples!" if the value of the "apple" variable is greater than 2:
if apple >= 2:
print("So many Apples!")
If statement syntax
In python, the If statement follows a syntax of:
if condition:
action
Where an action will be performed if a condition is true.
There are several mathematical operators in python that will compare different variables/numbers such as:
- a >= b
- a < b
- a == b
Going back to the if statement syntax, our condition will return a boolean value, either true or false. If our condition returns true, then the code, or action, part of our if statement will execute.
Conditions demonstration
#create a variable called number of apples and set it to 7
number_of_apples = 7
number_of_apples > 7
False
Now run this code:
number_of_apples >= 7
True
if number_of_apples >= 7:
print("Yay, so many apples!")
Yay, so many apples!
Else Statements
Else statements are used in conjunction with if statements. We can combine them to check for multiple conditions. The syntax is as follows:
if condition:
action1
else:
action2
For example, if we wanted to create a code to print "Not enough apples!" if we had less than 7 apples but also be able to print "Too many apples!" if we had more than 7 apples", we would need to use an else statement:
if number_of_apples < 7:
print("Not enough apples!")
else:
print("Too many apples!")
Here, the code inside the else statement is triggered and executes because the condition of the if statement returned False. This means that our code will print:
Too many apples!
To recap, if statements check if a condition is True and execute an action (run a block of code). We can use an else statement to execute another action (run another block of code) if the condition is False.
Congratulations for reaching the end of this article! you should now have a basic understanding of if and else statements.