Python Tutorial
About Lesson

In this lesson we are going to learn about Python IF…ELIF…ELSE Statements, So when you are coding or programming, sometimes you need to examine some conditions and decide which actions should be occurred based on those conditions. In Python the keywords if, elif , and else are used for conditional statements. so first we want to learn about if statement.

 

 

So in the above example first we have created an age variable, and we have assigned the value of 19 to the variable, after that we are checking the condition using if statement, we are checking that if our age is greater than 18, it means that our condition is true and we want to execute some codes in the body of the if statement. and if our condition is false we are not going to do anything, you can have as many lines of code as you want in the block following the if statement.

 

 

 

So now if you run the code, because the condition is true and you will receive the print output in the console.

Python IF...ELIF...ELSE Statements
Python IF…ELIF…ELSE Statements

 

 

 

If the value of age is less than 18, this program would produce no output, OK now sometimes you need to define an action or set of actions that are executed when the conditional test fails. so for this we can use else statement.

 

In the code our if condition is false, and in this case it will not execute the code in the if body, but it executes the code in the else body, because the else condition is true.

 

 

Run the code and this is the result.

Python Else Statements
Python Else Statements

 

 

 

Sometimes you need to check more than two possible conditions, and for this we can use Python IF…ELIF…ELSE Statements.

 

In this code we are checking multiple conditions, and based on the user input we want to take actions, if the user enters age between 1 and 9 we want to print the admission 10$, in the elif case if the user enters the age between 10 and 17 we want to print 30$, and in the else case if the user enters the value from 18 above we want to print 50$.

 

 

 

Run the code and this is the result.

Python Elif statement
Python Elif statement

 

 

 

Now let’s learn how you can use a list with Python IF…ELIF…ELSE Statements

 

In this code we want to get the username from users, we have created a list of users, and we want to check if the entered username is in our list, if it was in the list we want to print valid user, and in the else case we want to print invalid user.

 

 

Run the code and this is the result.

Python Condition Statements
Python Condition Statements

 

Thank you for visiting my website! If you enjoyed the free courses, please consider supporting my works on Patreon.
Exercise Files
No Attachment Found
No Attachment Found