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.
1 2 3 4 5 |
age = 19 if age > 18: print("You can vote ") print("You are good to vote") |
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.
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.
1 2 3 4 5 6 7 8 |
age = 15 if age > 18: print("You can vote ") print("You are good to vote") else: print("You can not vote ") |
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.
Sometimes you need to check more than two possible conditions, and for this we can use Python IF…ELIF…ELSE Statements.
1 2 3 4 5 6 7 8 9 10 |
age = int(input("Please enter your age : ")) if age < 10: print("Admission Is 20$") elif age < 18: print("Admission Is 30$") else: print("Admission Is 50$") |
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.
Now let’s learn how you can use a list with Python IF…ELIF…ELSE Statements
1 2 3 4 5 6 7 8 9 10 |
entered_user = input("Please enter your username : ") users = ["parwiz", "geekscoders", "tom", "bob"] if entered_user in users: print("You are a valid user") else: print("Your are not a valid user") |
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.