Python Crash Course for Beginners | Mastering the Python if…else Statement: A Comprehensive Guide with Examples

Python Crash Course for Beginners | Mastering the Python if…else Statement: A Comprehensive Guide with Examples

 

Decision-making is a fundamental concept in programming, allowing developers to create applications that can respond to different scenarios. The Python if…else statement is a primary tool for implementing this concept, providing a way to control the flow of a program based on specific conditions. In this article, we will delve into the Python if…else statement, offering coding examples and explanations to help you understand its functionality and usage.

Python if…else Statement Basics

The if…else statement in Python is used to perform actions based on certain conditions. It consists of two main components: the ‘if’ block, which is executed when the specified condition is true, and the ‘else’ block, which is executed when the condition is false.

Syntax

The general syntax for the Python if…else statement is as follows:

if condition:
# Code to execute when the condition is true
else:
# Code to execute when the condition is false

The ‘condition’ can be any expression that evaluates to a boolean value (True or False). If the condition is true, the code within the ‘if’ block is executed. If the condition is false, the code within the ‘else’ block is executed.

Example 1: Simple if…else Statement

Let’s begin with a simple example to understand the basic usage of the if…else statement in Python.

age = 18

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

In this example, the variable ‘age’ is assigned the value 18. The if…else statement checks if the age is greater than or equal to 18. If the condition is true (age >= 18), the program prints “You are eligible to vote.” Otherwise, it prints “You are not eligible to vote.”

Python if…elif…else Statement

In some cases, you may need to test multiple conditions and execute different code blocks based on which condition is met. This can be achieved using the if…elif…else statement in Python.

Syntax

The general syntax for the Python if…elif…else statement is as follows:

if condition_1:
# Code to execute if condition_1 is true
elif condition_2:
# Code to execute if condition_2 is true
elif condition_3:
# Code to execute if condition_3 is true
...
else:
# Code to execute if none of the conditions are true

In this structure, ‘elif’ is short for ‘else if.’ The conditions are evaluated in order, from top to bottom. When a true condition is encountered, its corresponding code block is executed, and the rest of the conditions are skipped. If none of the conditions are true, the code within the ‘else’ block is executed.

Example 2: Using the if…elif…else Statement

Let’s look at an example to understand how to use the if…elif…else statement in Python.

grade = 75

if grade >= 90:
    print("You scored an A.")
elif grade >= 80:
    print("You scored a B.")
elif grade >= 70:
    print("You scored a C.")
elif grade >= 60:
    print("You scored a D.")
else:
    print("You scored an F.")

In this example, the variable ‘grade’ is assigned the value 75. The if…elif…else statement checks the grade value and prints the corresponding letter grade. Since 75 is greater than or equal to 70 and less than 80, the program prints “You scored a C.”

Nested if…else Statements

Sometimes, you may need to perform additional tests within an if or else block. In such cases, you can use nested if…else statements, which are essentially if…else statements within other if…else statements.

Syntax

The general syntax for nested if…else statements is as follows:

if condition_1:
    # Code to execute if condition_1 is true
    if condition_2:
        # Code to execute if condition_2 is true
    else:
        # Code to execute if condition_2 is false
else:
    # Code to execute if condition_1 is false

Example 3: Nested if…else Statement

Let’s look at an example that demonstrates the use of nested if…else statements in Python.

age = 25
citizenship = "US"

if age >= 18:
    if citizenship == "US":
        print("You are eligible to vote in US elections.")
    else:
        print("You are not eligible to vote in US elections.")
else:
    print("You are not eligible to vote.")

In this example, the variables ‘age’ and ‘citizenship’ are assigned the values 25 and “US”, respectively. The outer if…else statement checks if the age is greater than or equal to 18. If the condition is true, the inner if…else statement checks if the citizenship is “US”. If both conditions are true, the program prints “You are eligible to vote in US elections.” If only the age condition is true, the program prints “You are not eligible to vote in US elections.” If the age condition is false, the program prints “You are not eligible to vote.”

In summary, the Python if…else statement is a powerful tool for controlling the flow of a program based on specific conditions. By understanding and mastering the if…else, if…elif…else, and nested if…else statements, you can create more dynamic and responsive applications.

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!