top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Python-if-else-statement

Introduction 

The Python if-else statement is a fundamental control structure that allows alternative code blocks to be executed based on specified criteria. It is used within software to make judgments by assessing a given condition as true or false. 

For more sophisticated decision-making scenarios, nested if-else statements might be employed. To test many conditions sequentially, multiple elif (short for "else if") clauses are used. The if-else statement increases code adaptability, allowing developers to create flexible programs that respond dynamically to changing circumstances.

The if-else statement is a fundamental component of Python's control flow methods, allowing programmers to create dynamic and responsive applications. Developers use this to construct robust applications that adapt to changing conditions and give customized outputs. Python's reputation as a user-friendly and powerful programming language is flexible for newbies and professionals. 

In this tutorial, let's delve into if-else statement, looping statements in Python, Elif statement in Python and many more. 

Overview 

The if-else statement is a fundamental control structure in Python that is used to define decision-making logic in programs. It helps developers to raise conditions that regulate the execution of various code blocks based on the criteria. This begins with an if statement evaluating the conditions, followed by an optional else statement that gives an alternate code path if the first condition is false. The related code block is run when the condition given in the if statement evaluates to true. If the condition is true, the code block included within the alternative expression executes.

If-Else Statement Example in Python

Code:

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

Explanation:

  • x is assigned the value 3.

  • The if statement checks whether x is greater than 5. Since 3 is not greater than 5, this condition is false.

  • The program proceeds to the else block because the if condition is false.

  • The code inside the else block is executed, which prints the message "x is not greater than 5".

  • The output of the program will be: "x is not greater than 5".

This example illustrates how the "if-else" statement allows you to execute different blocks of code depending on whether a given condition is true or false.

Nested If Statement Example in Python

Code:

x = 15
y = 7

if x > 10:
    print("x is greater than 10")
    if y > 5:
        print("y is also greater than 5")
    else:
        print("y is not greater than 5")
else:
    print("x is not greater than 10")

Explanation:

  • x is assigned the value 15 and y is assigned the value 7.

  • The outer "if" statement checks whether x is greater than 10. Since 15 is indeed greater than 10, the code inside this "if" block is executed.

  • The first print statement prints "x is greater than 10".

  • The inner "if" statement checks whether y is greater than 5. Since 7 is greater than 5, the code inside this nested "if" block is executed.

  • The second print statement prints y is also greater than 5".

  • The program completes the execution of the nested "if" statements.

  • The program then moves to the "else" block of the outer "if" statement, but since it's not relevant in this case, this block is not executed.

  • The program finishes without printing “x is not greater than 10".

If Elif-Else Statement 

Code:

x = 7

if x > 10:
    print("x is greater than 10")
elif x > 5:
    print("x is greater than 5 but not greater than 10")
else:
    print("x is not greater than 5")

Explanation:

  • x is assigned the value 7.

  • The first "if" statement checks whether x is greater than 10. Since 7 is not greater than 10, this condition is false.

  • The program moves to the "elif" (short for "else if") statement. This checks whether x is greater than 5. Since 7 is indeed greater than 5, this condition is true, and the corresponding block of code is executed.

  • The print statement inside the "elif" block prints "x is greater than 5 but not greater than 10".

  • Since the "elif" condition was true, the program skips the "else" block.

  • The program completes its execution.

What Happens When the 'If Condition' Does Not Meet? 

When the if condition stated in an if-else statement is not met in Python, the code in the accompanying if block is not run. Instead, the program evaluates the else block and executes the code contained within it. This behavior enables developers to define alternative actions or results if the first condition is not met.

When the software meets an if-else expression, it assesses the if part's condition. When the condition emerges as true, the program skips the code block within the if statement and instead executes the code within the else block. This provides a way for dealing with instances in which the condition being tested is false. 

Types of Control Flow in Python Examples

The if-statement 

Code:

x = 10

if x > 5:
    print("x is greater than 5")

Explanation:

  • x is assigned the value 10.

  • The "if" statement checks whether x is greater than 5. Since 10 is indeed greater than 5, this condition is true.

  • The indented block of code inside the "if" statement is executed.

  • The print statement inside the indented block prints "x is greater than 5".

  • The program completes its execution.

Flowchart of if Statement in Python

Explanation:

  • Start: The process starts here.

  • Read Input: If needed, you might read input values or variables here.

  • Condition Check: Draw a diamond shape labelled with the condition you're checking (e.g., "x > 5").

  • Condition True Path (Yes): If the condition is true, follow the arrow labelled "Yes" to the next step.

  • Execute Code: This is where you write the code that will be executed if the condition is true.

  • End If: The process reaches here after the code inside the "if" statement has been executed.

  • Condition False Path (No): If the condition is false, follow the arrow labelled "No" to the next step.

  • End If: The process reaches here after skipping the code inside the "if" statement.

  • End: The process ends here.

ShortHand If-Else Statement Example

Code:

x = 10
result = "x is greater than 5" if x > 5 else "x is not greater than 5"
print(result)

Explanation:

  • x is assigned the value 10.

  • The ternary conditional expression checks whether x is greater than 5.

  • If the condition is true (which it is, since 10 is greater than 5), the value "x is greater than 5" is assigned to the result variable.

  • If the condition is false, the value "x is not greater than 5" is assigned to the result variable.

  • The print statement prints the value stored in the result variable.

Indentation in Python 

In Python, indentation plays a crucial role in defining the structure and scope of your code. Unlike many other programming languages that use braces {} to delimit blocks of code, Python uses indentation to group statements and indicate the level of nesting.

Here are the key points to remember about indentation in Python:

  • Indentation Level: Code blocks are indented by a consistent number of spaces or tabs. A common convention is to use 4 spaces for each level of indentation.

  • Consistency is Key: You must be consistent with your choice of indentation throughout your code. Mixing spaces and tabs can lead to syntax errors and confusion.

  • Indentation Determines Scope: The level of indentation defines the scope of statements. Statements indented at the same level are considered part of the same block of code.

  • Colon Indication: A colon (:) is used to indicate the beginning of an indented code block. It's often used after control statements like "if," "else," "while," "for," and function definitions.

Here's an example of how indentation is used to define code blocks:

if condition:
    # This code block is indented and will be executed if the condition is true.
    statement1
    statement2
else:
    # This code block is also indented and will be executed if the condition is false.
    statement3
    statement4
# This statement is not indented and is outside any code block.
statement5

Incorrect indentation can lead to syntax errors, so it's important to ensure your code is properly indented. Most code editors and integrated development environments (IDEs) provide features that help you manage indentation correctly. We should always remember that consistent and readable indentation is not only a requirement in Python but also contributes to writing clean and maintainable code.

Advantage of if else in Python

  • Conditional Execution: The primary advantage of the "if-else" statement is that it allows you to execute different code blocks based on whether a certain condition is true or false. This ability is essential for making decisions and responding to various situations in your program.

  • Code Clarity: "if-else" statements make your code more readable and self-explanatory. By using conditional statements, you explicitly show the logic you intend to implement, making it easier for others (and your future self) to understand the code's intention.

  • Logical Flow: "if-else" statements enable you to create logical pathways in your code. You can handle different scenarios and cases based on different conditions, leading to a more comprehensive and organised code structure.

  • Efficient Resource Usage: "if-else" statements can help you optimise your code's execution by running specific code blocks only when necessary. This can improve performance and memory utilisation, especially in larger programs.

  • Error Handling: You can use "if-else" statements to handle errors or exceptional cases. For example, you might include error-handling code in the "else" block to gracefully handle situations where expected conditions aren't met.

  • User Interaction: "if-else" statements are commonly used to handle user input and interactions in programs. They allow your program to respond appropriately to user choices and actions.

  • Algorithm Design: When designing algorithms, "if-else" statements are a core tool for creating decision-making branches that guide the algorithm's behavior based on data or conditions.

  • Flexibility: "if-else" statements provide flexibility in structuring your code. You can nest them, combine them, or use them alongside other control structures like loops, giving you powerful tools for designing complex logic.

Conclusion 

The **if-else statement** in Python is a critical tool for integrating conditional logic into applications. When the condition in the **if** section evaluates to **false**, the control moves to the corresponding **else** section. This approach ensures that programs can cover a wide range of scenarios and provide unique outputs based on whether or not the condition is met. 

The **if-else** statement promotes simplified code by allowing the user to choose between two code pathways, improving code efficiency and readability. Python's usage of this construct enables developers to create adaptive solutions for a variety of situations, contributing to the language's reputation for having user-friendly syntax and diverse programming skills.

FAQs 

1. What is the error of an if-else statement in Python?

An **if-else statement** issue in Python might pop up when there is a syntactic problem or logical discrepancy inside the condition or code blocks. Missing colons after the **if** or **else** clauses, incorrect indentation, and mismatched data types in the condition are all common problems. These mistakes prohibit the code from running correctly and must be fixed for the application to function properly.

2. What are the rules for if statements in Python?

The rules for **if statements** in Python are as follows:

  • Begin with the keyword **if**, followed by a parenthesized condition.

  • The condition should return a Boolean value (either **True** or **False**).

  •  If the condition is **True**, the code block in the **if** statement is performed.

  • An **else** statement can optionally come after an **if** statement, executing its code block if the condition is **False**.

  •  **Elif** clauses can be used to verify extra requirements after the initial **if**, reducing superfluous tests for more complex situations.

  •  To specify code blocks consistently in Python, the **if** and **else** blocks must be appropriately indented.

3. Can you stop an if statement in Python? 

An **if statement** in Python cannot be immediately terminated or interrupted. The program proceeds to execute the succeeding code sequentially after the condition in the **if** statement is evaluated and the appropriate block of code is executed. Depending on the context, one can use **return**, **break**, or **continue** statements to control the flow of execution within the **if** block, but they will not terminate the entire **if statement**.

Leave a Reply

Your email address will not be published. Required fields are marked *