If else statement in Python

problem

You’re learning Python and you came across the idea of control flow that can happen using the if statement. In Python if we wish to change the course of actions by checking for a logical condition we use this mechanism. In this post we will see a simple example that given the user’s age it prints if they are adult or not.

SOLUTION

Let’s suppose we have a program that reads from the user their age and prints to the output if they’re adult or not.

To read from the user’s console we use the input() function as follows:

if_else.py
				
					age = int(input (“Please enter your age: ”))
				
			

The age variable holds the number entered by the user. We also used the int() function that converts a number from a string to an integer. For example “18” to 18 so we can deal with it in numerical fashion

if statement

Next, let’s add the if condition:

if_else.py
				
					if age >= 18: #check if they’re adult
	print(“You’re adult”)
else:
	print(“Not adult”)
print(“End”)
				
			

The if statement above accepts a boolean expression (age >=18) and based on that the program flow moves accordingly. If the expression “age >= 18” returns True, then it prints “You’re adult” and then it prints “End”.

If it’s False it goes to the else section and prints the “Not adult” message followed by “End”.

Hence we call it control flow. The program tends to flow in successive order, meaning that it will be executing commands one after the other one; line by line.

The if statement changes that. In the above code snippet, it goes to line 1 and then either at line 2 or at line 4 and then at line 5.

Also, other mechanisms change the flow like a for-loop.

running
let’s run it in the terminal as follows:
				
					python3 if_else.py
				
			
output

> With input 18

if else python

> With input 17

if else python example

conclusion

In this post we saw how to use a very simple if – else statement in python and how the flow of a program changes based on a logical condition (boolean expression).

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x