How to print different outputs based on Python if-else conditions?

PythonPythonBeginner
Practice Now

Introduction

Python's if-else statements are a fundamental part of programming, allowing you to make decisions and execute different code based on specific conditions. In this tutorial, we'll explore how to leverage these statements to print different outputs, and apply them to real-world scenarios. By the end, you'll have a solid understanding of conditional logic and be able to write more dynamic and versatile Python programs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") subgraph Lab Skills python/conditional_statements -.-> lab-415723{{"`How to print different outputs based on Python if-else conditions?`"}} end

Understanding Python If-Else Statements

Python's if-else statements are fundamental control structures that allow your program to make decisions based on certain conditions. They enable you to execute different blocks of code depending on whether a particular condition is true or false.

Basic Syntax

The basic syntax for an if-else statement in Python is as follows:

if condition:
    ## code block to be executed if the condition is true
else:
    ## code block to be executed if the condition is false

The condition in the if statement is evaluated, and if it is True, the code block under the if statement is executed. If the condition is False, the code block under the else statement is executed instead.

Nested If-Else Statements

You can also have nested if-else statements, where an if-else statement is placed inside another if-else statement. This allows you to create more complex decision-making logic in your program.

if condition1:
    ## code block to be executed if condition1 is true
    if condition2:
        ## code block to be executed if both condition1 and condition2 are true
    else:
        ## code block to be executed if condition1 is true but condition2 is false
else:
    ## code block to be executed if condition1 is false

Chained If-Else Statements

Additionally, you can chain multiple if-elif-else statements together to handle more than two possible conditions.

if condition1:
    ## code block to be executed if condition1 is true
elif condition2:
    ## code block to be executed if condition1 is false and condition2 is true
elif condition3:
    ## code block to be executed if condition1 and condition2 are false but condition3 is true
else:
    ## code block to be executed if all the above conditions are false

The elif (short for "else if") statements allow you to check multiple conditions, and the else statement serves as a catch-all for any remaining cases.

By understanding the basic syntax and the different variations of if-else statements, you can effectively use them to control the flow of your Python programs and make decisions based on various conditions.

Printing Conditional Outputs

Once you have understood the basics of if-else statements in Python, you can use them to print different outputs based on the evaluated conditions. This allows you to provide customized responses or feedback to the user or other parts of your program.

Simple If-Else Printing

The simplest way to print different outputs based on an if-else condition is to use the print() function within the corresponding code blocks.

age = 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

In this example, if the age variable is greater than or equal to 18, the program will print "You are an adult." Otherwise, it will print "You are a minor."

Printing with Variables

You can also incorporate variables into the printed outputs to make the messages more dynamic and informative.

name = "LabEx"
score = 85
if score >= 90:
    print(f"{name} scored an excellent grade of {score}.")
else:
    print(f"{name} scored a grade of {score}.")

By using f-strings (formatted string literals), you can seamlessly integrate variables into the printed output.

Printing with Nested Conditions

When working with nested if-else statements, you can print different outputs based on the evaluation of multiple conditions.

temperature = 25
humidity = 80
if temperature > 30:
    if humidity > 70:
        print("It's hot and humid outside.")
    else:
        print("It's hot and dry outside.")
else:
    if humidity > 70:
        print("It's cool and humid outside.")
    else:
        print("It's cool and dry outside.")

In this example, the program will print different messages depending on the combination of temperature and humidity levels.

By understanding how to print conditional outputs, you can create more informative and interactive programs that provide tailored responses to the user or other parts of your application.

Applying If-Else in Real-World Scenarios

Now that you have a solid understanding of if-else statements and how to print conditional outputs, let's explore some real-world scenarios where you can apply these concepts.

Grading System

Imagine you are building a grading system for a school. You can use if-else statements to determine the letter grade based on a student's numerical score.

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print(f"The student's grade is: {grade}")

This code will print the appropriate letter grade based on the student's score.

Age-Restricted Content

Another common scenario is age-restricted content, such as a movie rating system or access to certain features on a website.

age = 16
if age >= 18:
    print("You can access the adult content.")
else:
    print("You are not old enough to access the adult content.")

By checking the user's age, you can determine whether they are allowed to access the restricted content.

Weather Forecast

Let's consider a weather forecast application. You can use if-else statements to provide different weather information based on the current conditions.

temperature = 25
precipitation = 0.8
if temperature > 30 and precipitation > 0.5:
    print("It's hot and rainy outside. Remember to bring an umbrella.")
elif temperature > 30 and precipitation <= 0.5:
    print("It's hot and dry outside. Don't forget to stay hydrated.")
elif temperature <= 30 and precipitation > 0.5:
    print("It's cool and rainy outside. Grab a jacket before going out.")
else:
    print("It's cool and dry outside. Enjoy the pleasant weather!")

This code will print different messages based on the temperature and precipitation levels.

By exploring these real-world scenarios, you can see how if-else statements and conditional printing can be applied to create more intelligent and user-friendly applications.

Summary

In this Python tutorial, you've learned how to use if-else statements to print different outputs based on specific conditions. You've explored various real-world scenarios where this technique can be applied, and gained a deeper understanding of conditional logic in Python. With this knowledge, you can now write more robust and flexible programs that can adapt to different situations and user inputs.

Other Python Tutorials you may like