Back to Basics: Conditional Logic with Python if else if

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

This tutorial will teach you a simple way to build conditional logic using Python. We’ll go from the basics, teaching how functions and if else statements work in python. From there we’ll move on to building more complex conditional loops and finally wrapping up with ways of making decisions based off other data you’ve gathered

Conditional Logic is a common programming language feature. It allows for the execution of different instructions based on the result of an evaluation. The “nested if else in python” is one of those conditional logic features.

Back to Basics: Conditional Logic with Python if else if

Whether you’re new to Python programming or returning after a sabbatical, you may need to brush up on decision-making and branching statements. The Python if else, if, and otherwise statements are used often in decision-making and branching, and they are one of the most important principles in computer programming.

In this lesson, you’ll learn about the many if, otherwise if, else situations that might occur when building a Python program. Let’s get this party started!

Understanding Python Loops and Flow Control: A Beginner’s Guide

Prerequisites

This will be a hands-on presentation in this course. You’ll learn via real-world scenarios that you’ll encounter while creating a basic Weather app. If you want to follow along, make sure you have the following items on hand:

  • Python 3 is installed, however Python 3.8 is used in this lesson.
  • VS Code is suggested as a code editor for running Python code.

How Do You Install Python 3.6? Related:How Do You Install Python 3.6?

With the If Statement, you may test for a single condition.

You’ll need your software to do actions only when specific criteria are satisfied when you create it. You’ll have to alter the flow of your programs as a result.

Let’s start with an if statement, which allows you to adjust the flow of the code. Let’s see how to do actions by putting a single condition to the test.

When a conditional statement evaluates to true, an if statement runs code. As you can see in the grammar below, the: symbol occurs after the condition in Python.

if condition: assertion (s)

In Python, be aware of whitespaces (or the absence thereof). To create code chunks, Python uses whitespace indentation. Python understands such statements as if they were block code, with the same quantity of spaces before them.

If the condition evaluates to false, the computer skips the code beneath the if statement and moves on to the code after the if statement.

Python considers all non-zero numbers to be true, whereas all other values are considered false.

Flowcharts may help you better comprehend decision-making and branching when it comes to decision-making and branching. For testing a single condition, see the flowchart below.

Using if to test a single condition Using if to test a single condition

Using Code to Demonstrate a Simple If Statement

You will code for features that may be included in a barebones Weather App to better grasp the principles in this tutorial. The first feature will greet new users with a greeting message.

1. Open your code editor, create a new file, and save it as index.py in the folder of your choice.

2. Add the following code to the index.py file. This will be the only condition checked since you only want to show a message to new users. If the new user variable is true, the if condition evaluates it and outputs a welcome message to the terminal.

# Set the new user variable to True to indicate that this is the user’s first visit to the program. If new user: new user: new user: new user: new user: new user: new user: welcome(‘WeatherApp’) print(‘WeatherApp’) print(‘WeatherApp’) print(‘We # A message to the new user is printed.

3. Execute the following command in your terminal to run the index.py Python program, as shown in the picture.

A python script is being run.A python script is being run.

Using the Else Block to Cover All Outcomes

The code you wrote in the last section only operated on one condition. In your coding travels, you’ll come into situations where you’ll need to run a series of statements if the initial if condition fails.

If the first statement returns false, an else statement is used to run a separate piece of code as a backup. If the condition is True, statement(s) 1 is executed in the format below. If the condition returns False, statement(s) 2 is executed.

if condition: assertion (s)_1 else: statement(s)_2

See the flowchart below for a visual representation of this topic.

If-Else condition flowchart If-Else condition flowchart

Using Code to Demonstrate a Simple If-Else Statement

Continuing with the example of greeting the user, you will now add a feature that will show a welcome back message to old users.

1. Open your code editor and the index.py file you previously prepared.

2. Add the following code to the index.py file when modifying it. Unlike previously, the new user variable is set to False, causing the else code block to be executed.

# Set the new user variable to False to indicate that the user is returning to the program and to activate the else clause new user = False if new user: welcome(‘WeatherApp’) print(‘WeatherApp’) print(‘WeatherApp’) print(‘We # Otherwise, it prints a message to the new user: welcome(‘Welcome Back’) print(‘Welcome Back’) print(‘Welcome # Displays a message to the user who is returning.

3. Execute the following command in your terminal to run the index.py Python program, as shown in the picture.

The else block's statement(s) execute. The else block’s statement(s) execute.

Using Else-If Statements to Test Additional Conditions

There may be occasions when you need to check for various criteria and run the appropriate code blocks in programming. To that purpose, Python features the elif keyword, which stands for else-if in plain English and allows for more conditional testing.

Starting with the first if statement condition, Python examines each condition in the order supplied. When a condition evaluates to true, the code block associated with it executes, and all following conditions are bypassed. The else code block is executed if none of the criteria are true.

The if-elseif-else syntax is as follows, as demonstrated in the flowchart below.

elif condition2: statement(s) 2 else: statement(s) 3 if condition1: statement(s) 1 elif condition2: statement(s) 2

A flowchart for the if-elseif-else expression in Python. A flowchart for the if-elseif-else expression in Python.

Using If-Else Statements to Demonstrate If-Else Statements in Code

Perhaps you’d want to add a feature to the example Weather app that greets users with the words “Good Morning,” “Good Afternoon,” or “Good Evening,” depending on the time of day. You would check the current hour of the day on a real-world app. To make things easy, the code assumes that the time is 15 o’clock (3 pm).

1. Open your code editor and the index.py file you previously prepared.

2. Substitute the code sample below for the current code. The hour variable is set to the integer value of 15 in this example. The if statement first shows “Good Morning” if the hour variable is less than 12, then “Good Afternoon” if the hour variable is less than 16, and lastly “Good Evening” if the previous two conditions are false.

# Create and set a variable to the integer value of 15 corresponding to 3 pm. hour = 15 if hour < 12: print(‘Good Morning’) # Display if the hour integer variable is less than 12 elif hour < 16: print(‘Good Afternoon’) # Display if the hour integer variable is less than 16 else: print(‘Good Evening’) # Display if the hour integer variable is not one of the above conditions

3. Execute the following command in your terminal to run the index.py Python program, as shown in the picture.

Display the "Good Afternoon" text.Display the words “Good Afternoon.”

The result always says “Good Afternoon” since the algorithm expects a constant hour.

Using Nesting to Handle Complex Conditional Logic

You’ll encounter situations when you’re working on a feature that requires complicated conditional logic. Python enables you to layer if-elseif-else statements in certain situations.

For each outer if-elseif-else construct, add an extra if statement within a code block to generate nested if statements. As seen in the example below, you may nest as many if statements as you wish.

elif condition3: if condition4: statement(s) 3 else: statement(s) 4 if condition1: if condition2: statement(s) 1 else: statement(s) 2 elif condition4: statement(s) 3 else: statement(s) 4

Code Demonstration of Nested If Statements

You’ll include a function in your Weather app to assist users in dealing with rainy circumstances. The user will not need to take any action if there is minimal possibility of rain. If there is a probability of rain, you will encourage the user to take appropriate measures depending on the likelihood of rain, such as carrying an umbrella or using an Uber.

1. Open your code editor and the index.py file you previously prepared.

2. Substitute the code sample below for the current code. The first if statement determines if the likelihood of rain is higher than 0.2 or 20%. If the possibility is larger than 20%, use the nested if statement to determine if the rain probability is less than 0.5 or 50%. Because the rain is most likely 0.6, the first if statement evaluates as true, and the nested if statement evaluates as false, resulting in the console showing “Take an Uber.”

# Declare the variable rain_probability with the float (decimal) value of 0.6 (60%) rain_probability = 0.6 if rain_probability >= 0.2: # If the change of rain is greater than 20% (0.2) if rain_probability < 0.5: print(‘Take an Umbrella when going out’) # Display if the chance of rain is less than 50% (0.5) else: print(‘Take an Uber’) # Display if the chance of rain is greater than 50% (0.5) else: print(‘No rain’) # Display if the chance of rain is less than 20% (0.2)

3. Execute the following command in your terminal to run the index.py Python program, as shown in the picture.

Displaying the text "Take an Uber". The text “Take an Uber” is shown.

Using the or and and Operators with If Conditions

Your if-elseif-else statements had only checked a single conditional statement up to this time. Complex conditions may be tested using Python logical operators like or and and. Logical operators combine two or more conditions and determine whether they are true or false as a whole.

In an If Statement, demonstrating the or Logical Operator

The logical or operator is the first operator, and it evaluates a statement as true if at least one of the requirements is met.

1. Open your code editor and the index.py file you previously prepared.

2. Substitute the code sample below for the current code. The today variable is assigned to Sunday, and the if statement checks to see whether it includes either Saturday or Sunday. Display the text “Enjoy your Weekend” if one of the requirements is met.

# Declare Sunday as the today variable today = ‘Sunday’ # If either Saturday or Sunday is selected as the today variable, if today ==’Saturday’ or today ==’Sunday’, show the following text: print(‘Have a great weekend’)

3. Execute the following command in your terminal to run the index.py Python program, as shown in the picture.

Displaying the text "Enjoy your Weekend" while evaluating an or condition.While analyzing an or condition, the phrase “Enjoy your Weekend” is shown.

In an If Statement, the and Logical Operator is shown.

Now we’ll look at the second logical operator, and, as seen below. When all of the criteria are true, the and operator evaluates a statement as true.

1. Open your code editor and the index.py file you previously prepared.

2. Substitute the code sample below for the current code. The variables user type and is user logged in are defined here. If both variables are true, the example shows showing the text “You can access the premium features.”

user type = ‘pro’ # Declare the user type variable and set it to “pro” # Declare and set the is user logged in variable to True: is user logged in = True if is user logged in and user type ==’pro’: print(‘The premium features are available to you’) # Display if both the is user logged in and the user type variables are set to “pro.”

Execute the following command in your terminal to run the index.py Python program, as seen in the picture.

Displaying the text "You can access the premium features" while evaluating an or condition.While analyzing an or condition, displaying the sentence “You can access the premium features.”

The examples given here were as straightforward as possible. Don’t be deceived; you may examine many circumstances at the same time. It’s also feasible to utilize both or and and at the same time!

Conclusion

This lesson covered how Python if else if statements work, as well as other logical operators. You learnt these principles by putting them into practice, which will help you create more complicated applications. Are you ready to take your game to the next level? Next, learn about Python loops and flow control.

Conditional statements in Python are a very important part of programming. They allow you to create a decision and run different code depending on the outcome. This is done with the “if else if” statement. Reference: conditional statements in python pdf.

Frequently Asked Questions

How do you do an if and condition in Python?

A: It depends on what you want to do. There are plenty of ways that this can be done, but here is one way using a list comprehension.

How do you write a conditional statement in Python?

A: You can use if statements in both Python and a programming language. If you want to say, If the user is male, then you could do this with an if statement like so:
if gender == male: print(Welcome! I am programmed by a man)

What is else condition in Python?

A: In Python, the “else” clause is used when you want to perform an alternative set of commands if a condition was not met.

Related Tags

  • if else statement in python example
  • if else python 3
  • python conditional statements and loops
  • types of conditional statements in python
  • elif statement in python

Table of Content