Python If Else Statements Tutorial

Python If Else Statements Tutorial

Last updated on 26th Sep 2020, Blog, Tutorials

About author

Akash (Sr Technical Project Manager )

High level Domain Expert in TOP MNCs with 8+ Years of Experience. Also, Handled Around 16+ Projects and Shared his Knowledge by Writing these Blogs for us.

(5.0) | 16452 Ratings 895

Python if else statements are conditional statements, they run a particular block of code based on the results of an expression. In a Python if statement, if the provided boolean expression is True, the code contained in the statement is executed. if else Python statements work the same way, except if the expression is False the code under the else statement is run instead.When you’re writing a program, you may want a block of code to run only when a certain condition is met.

Python Conditionals

Conditional statements are a part of every major programming language.By using a conditional statement, you can make sure that certain code in your programs is executed only when a set condition is met.

For instance, suppose you are building an application that gives a student a letter-based grade, depending on the numerical grade they scored on a math test. If the student receives over 80%, they should be given an A, if they receive over 70% they should be given a B, and so on. In this scenario, conditional statements would be useful.

if Statement

The if statement evaluates whether a statement is equal to true or false, and will only run a block of code if the statement is equal to true.

Syntax

If (Boolean expression): Block of code  #Set of statements to execute if the condition is true. Here, the condition will be evaluated to a Boolean expression (true or false). If the condition is true, then the statement or program present inside the if block will be executed and if the condition is false, then the statements or program present inside the if block will not be executed.

Let’s see how it looks on a flow chart

condition-evaluate-flow-chart

If you observe the above flow-chart, first the controller will come to an if condition and evaluate the condition if it is true, then the statements will be executed, otherwise the code present outside the block will be executed.

Consider the following example

  • sandwich_order = “Ham Roll”
  • if sandwich_order == “Ham Roll”:
  • print(“Price: $1.75”)
  • Our code returns: Price: $1.75

In this example, we have declared a variable called sandwich_order. This variable has been assigned the value Ham Roll.

Then, we use an if statement to check whether sandwich_order is equal to Ham Roll. If our condition is true, our print() statement will be executed. If our condition is false, nothing will happen.

In this example, our sandwich_order variable is equal to Ham Roll, which means that our if statement is executed.

Now, let’s see what happens when we change our sandwich order to Cheese Roll:

  • sandwich_order = “Cheese Roll”
  • if sandwich_order == “Ham Roll”:
  • print(“Price: $1.75”)

Our code returns nothing. This is because our sandwich order is not equal to Ham Roll, and so the print() statement in our code is not given the chance to execute.

if else Statement

So far, we have used an if statement to test for whether a particular condition is met.But, what if we want to do something if a condition is not met? That’s where the if…else Python statement comes in. 

Suppose we are building an app that checks whether a customer at a local restaurant has run up a tab. If the customer has run up a tab over $20, they need to pay it off before they can order more food; if not, nothing should happen.

Subscribe For Free Demo

Error: Contact form not found.

Syntax

if(Boolean expression): Block of code #Set of statements to execute if condition is true else: Block of code #Set of statements to execute if condition is false

Here, the condition will be evaluated to a Boolean expression (true or false). If the condition is true then the statements or program present inside the if block will be executed and if the condition is false then the statements or program present inside else block will be executed.

Let’s see the flowchart of if-else

rest-of-the-code-conditions

If you observe the above flow chart, first the controller will come to if condition and evaluate the condition if it is true and then the statements of if block will be executed otherwise else block will be executed and later the rest of the code present outside if-else block will be executed.

To accomplish this task, we could use the following code:

  • tab = 29.95
  • if tab > 20:
  • print(“This user has a tab over $20 that needs to be paid.”)
  • else:
  • print(“This user’s tab is below $20 that does not require immediate payment.”)

Our code returns: This user has a tab over $20 that needs to be paid.

Let’s walk through how our code works. First, we declare a variable called tab which tracks a customer’s tab. Then, we use an if statement to check whether the customer’s tab is greater than 20. If it is, then the print() statement after our if statement is executed; if not, the print() statement after our Python if…else statement is executed.

In this case, because our customer’s tab is over $20, the contents of our if statement are executed, which returns a message telling the customer they have a tab to pay.

If we change our program and set the customer’s tab to $0, the following is returned:

This user’s tab is below $20 which does not require immediate payment.

This is because, if the customer’s tab is not over $20, the contents of our else statement are executed instead of our if statement. 

elif Statement

In our above example, we created a conditional statement with two possible outcomes.

If the user’s tab was over $20, a message was printed to the console. If a user’s tab was under $20, a different message was printed to the console.

In some cases, though, we may want to evaluate multiple conditions and create outcomes for each of those conditions. That’s where the elif condition comes in.

Syntax

  • if (condition):
  • Set of statement to execute if condition is true
  • elif (condition):
  • Set of statements to be executed when if condition is false and elif condition is true
  • else:
  • Set of statement to be executed when both if and elif conditions are false

The elif statement (short for else if) is an else condition that allows you to evaluate another condition in an if statement.

Let’s return to our sandwich example from earlier. Suppose we want to have four potential outputs from our program, depending on the sandwich filling a customer chooses. These are:

  • Ham Roll: $1.75
  • Cheese Roll: $1.80
  • Bacon Roll: $2.10
  • Other Filled Roll: $2.00

We could use the following code to calculate the cost of the customer’s order:

  • sandwich_order = “Bacon Roll”
  • if sandwich_order == “Ham Roll”:
  •  print(“Price: $1.75”)
  • elif sandwich_order == “Cheese Roll”:
  • print(“Price: $1.80”)
  • elif sandwich_order == “Bacon Roll”:
  •  print(“Price: $2.10”)
  • else:
  • print(“Price: $2.00”)
  • Our code returns: Price: $2.10.

Our code has four possible outcomes:

  • If a customer orders a ham roll, the contents of the “if” statement are executed. This prints “Price: $1.75” to the console.
  • If a customer orders a cheese roll, the contents of the first “elif” statement are executed. This prints “Price: $1.80” to the console.
  • If a customer orders a bacon roll, the contents of the second “elif” statement are run. This prints “Price: $2.10” to the console.
  • If a customer orders a roll with a different filling, “Price: $2.10” is printed to the console.

In this example, we used an if statement to test for a specific condition, two elif blocks to test for alternative conditions, and an else statement to return a default value if none of our conditions were met.

We could add in more elif statements to our above code if we wanted. So, if we introduced a new Tuna Roll to our sandwich menu, we could add in a new elif statement that prints the price of the new menu item.

Nested if Statements

Nested if statements allow you to check to see if a second condition is met, but only if another condition is met first.

The term nested if statement refers to an if statement that is contained within another if statement. 

Let’s return to our sandwich example from earlier. Suppose we want to check whether a customer has ordered a roll that is on our menu first before we check the prices of the customer’s order.

If the customer has ordered another custom sandwich that is not on our menu (such as a buttered roll, or a jam roll), a message should be printed to the screen with our default price for non-menu items. But if a customer has ordered a sandwich that is on our menu, we should then check to see the price of that sandwich.

python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

Nested if-else Syntax

  • if(condition):
  •  #Statements to execute if condition is true
  •  if(condition):
  •  #Statements to execute if condition is true
  • else:
  •  #Statements to execute if condition is false
  • else:
  •  #Statements to execute if condition is false

Here we have included if-else block inside an if block, you can also include if-else block inside else block.

We could do so using this code:

  • sandwich_order = “Other Filled Roll”
  • if sandwich_order != “Other Filled Roll”:
  • if sandwich_order == “Ham Roll”:
  •  print(“Price: $1.75”)
  • if sandwich_order == “Cheese Roll”:
  • print(“Price: $1.80”)
  • elif sandwich_order == “Bacon Roll”:
  • print(“Price: $2.10”)
  • else:
  • print(“Price: $2.00”)
  • Our code returns: Price: $2.00.

Let’s break down how our code works.

First, our program evaluates whether our sandwich order is not equal to Other Filled Roll. Then, if this conditional expression evaluates to True—if we have ordered a sandwich on the menu—our program will compare the sandwich we have ordered with the list of sandwiches on our menu.

However, if we have ordered a filled roll that is not on our menu—which would be equal to Other Filled Roll—then the contents of the else statement in our code are executed instead of the contents of our if statement.

In this example, we have ordered a filled roll that is not on our menu. This means that the statement if sandwich_order != Other Filled Roll evaluates to False, so the code in our if statement is executed.

Now, suppose we ordered a ham roll instead. This would cause our first if statement to evaluate to true—Ham Roll is not equal to Other Filled Roll—which means our order will be compared to the list of sandwich prices we have specified.

So, our code would then evaluate if sandwich_order == Ham Roll, which evaluates to true. Then, our program would print out the corresponding price for the ham roll to the console.

Conclusion

Conditional statements like if, if…else and elif allow you to control the flow of your programs.

By using a conditional statement, you can instruct a program to only execute a block of code when a condition is met. If a condition is not met, then a block of code will not be executed.

This tutorial discussed, with reference to examples, the basics of conditional statements in Python. Now you’re ready to start using these statements in your own code, like a Python expert!

  • Python provides conditional statements which are helpful for verification and validation purposes.
  • In Python we have 2 types of looping statements which help us to execute certain statements or block of code repeatedly
  • We use ‘while loop’ when we don’t know the number of times that we need to iterate and if we know how many times we need to iterate then ‘for loop’ is the best.
  • Python provides 3 control statements which help to control the flow of execution of a program.

In this tutorial, we learned about the Conditional Statements in Python. These are the statements which alter the control flow of execution in our program.

We have different types of conditional statements like if, if-else, elif, nested if and nested if-else statements which control the execution of our program.

If the statement evaluates a Boolean expression to true or false, if the condition is true then the statement inside the if block will be executed in case if the condition is false then the statement present inside the else block will be executed only if you have written the else block.

We have one more statement called elif statement where the else statement is combined with an if statement, which executes depending on the previous if or elif statements.

Are you looking training with Right Jobs?

Contact Us

Popular Courses