DEV Community

V Sai Harsha
V Sai Harsha

Posted on

Master Python - Conditionals

Introduction

Python is renowned for its simplicity and readability, making it an ideal choice for beginners in programming. One fundamental concept in Python, and in programming in general, is the use of conditionals. In this article, we'll explore conditionals in Python, helping you understand how they work and how to use them effectively in your code.

What Are Conditionals?

Conditionals are control structures in programming that allow you to make decisions based on certain conditions. They enable your program to execute different code blocks depending on whether a given condition is true or false. In Python, you can achieve this using the if, elif (short for "else if"), and else statements.

The if Statement

The most basic form of a conditional statement in Python is the if statement. It allows you to execute a block of code if a specified condition is true. Here's a simple example:

age = 18

if age >= 18:
    print("You are an adult.")
Enter fullscreen mode Exit fullscreen mode

In this example, the code inside the if block only runs if the condition age >= 18 is true.

The else Statement

The else statement follows an if statement and is used to execute a block of code when the if condition is false. Here's an example:

age = 15

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

In this case, since age is not greater than or equal to 18, the code inside the else block executes.

The elif Statement

Sometimes, you need to check multiple conditions in a sequence. You can achieve this using the elif statement. Here's an example:

grade = 85

if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
else:
    print("F")
Enter fullscreen mode Exit fullscreen mode

In this example, Python evaluates each condition in order. If the first condition is true, it executes the corresponding block and skips the rest. If none of the conditions are true, it executes the else block.

Logical Operators

Python also provides logical operators (and, or, and not) that allow you to combine multiple conditions. For example:

age = 25
is_student = True

if age >= 18 and not is_student:
    print("You are an adult, not a student.")
Enter fullscreen mode Exit fullscreen mode

In this case, both conditions must be true for the code inside the if block to execute.

Conclusion

Conditionals are a fundamental building block in Python programming. They allow you to create dynamic and decision-based logic in your code. By using if, elif, and else statements, along with logical operators, you can make your programs respond to different situations and conditions. As you continue your Python journey, mastering conditionals will be essential for building more complex and functional programs. Happy coding!

Top comments (0)