Python if…else Statement: Making Decisions in Your Code

Python if…else Statement Introduction:

In the world of programming, making decisions based on certain conditions is a fundamental aspect. Python, being a versatile and powerful language, provides a robust control structure called the if...else statement. This statement enables developers to execute different blocks of code based on the evaluation of a condition. In this article, we will explore the if...else statement in Python, understand its syntax, and examine some examples to illustrate its usage.

Understanding the Syntax:

The general syntax of the if...else statement in Python is as follows:

if condition:
    # code to execute if the condition is True
else:
    # code to execute if the condition is False

The condition in the if statement can be any expression that evaluates to either True or False. If the condition evaluates to True, the code block immediately following the if statement is executed. On the other hand, if the condition evaluates to False, the code block following the else statement is executed.

Basic Example:

Let’s begin with a simple example to illustrate the usage of if...else statement:

age = 20

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

In this example, the if condition checks whether the variable age is greater than or equal to 18. If it is, the first code block is executed, printing the message “You are eligible to vote!” However, if the condition evaluates to False, indicating that the age is less than 18, the code block following the else statement is executed, printing the message “You are not eligible to vote yet.”

See Also  Python Namespace and Scope

Multiple Conditions:

The if...else statement can handle more than two outcomes by using the elif (short for “else if”) keyword. This allows us to evaluate additional conditions. Consider the following example:

marks = 85

if marks >= 90:
    print("Excellent!")
elif marks >= 70:
    print("Good job!")
elif marks >= 50:
    print("You passed.")
else:
    print("Sorry, you failed.")

In this example, multiple conditions are checked one after the other. The code block under the first condition is executed if the marks variable is greater than or equal to 90. If the first condition is False, the code block under the next elif condition is evaluated. If none of the conditions are True, the code block under the else statement is executed.

Nested if…else Statements:

It is also possible to nest if...else statements within each other to create more complex decision-making structures. This is useful when you need to evaluate multiple conditions based on different scenarios. Here’s an example:

x = 10
y = 5

if x > y:
    if x % y == 0:
        print("x is divisible by y")
    else:
        print("x is not divisible by y")
else:
    print("x is not greater than y")

In this example, the outer if statement checks if x is greater than y. If it is, the nested if statement verifies if x is divisible by y. Depending on the evaluation of these conditions, the appropriate message is printed.

x = 10

if x > 0:
    print("x is positive")
else:
    print("x is non-positive")

In this example, we have a variable x assigned a value of 10. The if condition checks whether x is greater than 0. Since x is indeed greater than 0, the condition evaluates to True, and the code inside the if block is executed. As a result, the output will be:

x is positive

If we modify the value of x to -5, the condition x > 0 will evaluate to False, and the code inside the else block will be executed instead. In that case, the output will be:

x is non-positive

The if...else statement in Python is a powerful tool for making decisions in your code. By evaluating conditions, you can control the flow and behaviour of your program. Whether you need to handle simple conditions

0 0 votes
Article Rating

Related articles

Python Regular Expressions

Python Regular Expressions: Effortlessly match, search, and manipulate text patterns with precision and flexibility. Boost your text processing capabilities now

Python @property Decorator: Simplifying Property Management

Python's @property decorator simplifies property management. It transforms methods into attributes, providing controlled access to data with clean syntax.

Python Decorators: Enhancing Functionality with Elegance

Python decorators: Enhance function and class behavior dynamically. Add functionalities like logging, caching, and authentication with elegance and simplicity.

Python Closures: Mastering Function Encapsulation

Encapsulate state, create specialized functions and implement advanced patterns in just a few lines of code. Unleash the flexibility of Python Closures

Python Generators: Efficient Approach to Iteration

Python generators provide a memory-efficient and concise way to create iterators. They generate values on the fly, improving performance when working with large

Case Studies

Compass Music Platform

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...

NewsWeek Magazine

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...

Beauty & Makeup Shop

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...
0
Would love your thoughts, please comment.x
()
x