Blog header background

Conditional Statements in Python – Explained with Examples

Updated on July 25, 2024

7 min read

Copy link
Share on WhatsApp

Conditional statements are fundamental for controlling program execution. They allow developers to make decisions and execute specific code in the program. In this article, we will learn everything about Conditional statements in Python, with examples.

What are Conditional Statements?

Conditional statements are a fundamental aspect of any programming language. They allow the execution of certain blocks of code based on specific conditions. The Python language conditional statements are straightforward and powerful, providing a way to control a program’s flow. They are fundamental in controlling a program’s flow and essential for writing logical and efficient code in Python language.

brochure-banner-bg

POSTGRADUATE PROGRAM IN

Multi Cloud Architecture & DevOps

Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems.

If Conditional Statement in Python

The ‘if’ statement evaluates a condition; if the condition is true, the indented block of code under the ‘if’ statement is executed. If the condition is false, it will execute the else part of the code.

Syntax

if condition:

# Statements to execute if

# condition is true

The following program demonstrates the conditional statement in Python.

Program 1

# if statement example

if 10 > 5:

print("10 greater than 5")

print("Program ended")

Output

10 greater than 5

Program ended

Program 2

number1 = int(input("Enter the first Number = "))

number2 = int(input("enter the second Number = ") )
 
if number1 > number2:

print("First Number is Bigger than Second Number")

 Output

Enter the first Number = 20

enter the second Number = 10

First Number is Bigger than Second Number

If-else Conditional Statement in Python

The ‘if-else’ statement provides an alternative code block to execute if the condition is false, then the else portion will be executed.

Syntax of Python if-else

if (condition):

# Executes this block if

# condition is true

else:

# Executes this block if

# condition is false

The following program demonstrates the Python language.

Program 1

# if..else statement example
x = 20
if x == 4:
    print("Yes")
else:
    print("No")

Output

No

Program 2:

number = 30


if number > 10:
   number = number+1
   print(number)

Output

31

Nested if…else Conditional Statements in Python

Nested if..else means an if-else statement inside another if statement. In simple words, it allows the developer to place an ‘if’ or ‘else’ statement inside another ‘if’  or ‘else’ statement. This is very useful for making complex decisions where you must evaluate multiple conditions sequentially.

Syntax

The basic syntax for nested ‘if…else’ statements in Python is as follows:

if condition1:
    # code to execute if condition1 is true
    if condition2:
        # code to execute if condition2 is true
    else:
        # code to execute if condition2 is false
else:
    # code to execute if condition1 is false
    if condition3:
        # code to execute if condition3 is true
    else:
        # code to execute if condition3 is false

The following program demonstrates the conditional statement in Python.

Program

num = 44
 
if num == 55:
    print("Number is 55")
 
else:
 
    if num == 99:
        print("Number is 99")
 
    else:
 
        if num == 44:
            print("Number is 44")
 
        else:
            print("Number is not match with any condition")

Output

Number is 44
skill-test-section-bg

82.9%

of professionals don't believe their degree can help them get ahead at work.

If-elif-else Conditional Statements in Python

In Python,  ‘if-elif-else’ conditional statements are used to execute blocks based on multiple conditions. This structure allows you to check multiple expressions for truth and execute a corresponding code block for the first true condition. An optional ‘else’ block can be executed if none of the conditions are true, and an optional ‘else’ block can be executed.

Syntax

Here is the basic syntax of if-elif-else conditional statements in Python:

if condition1:
    # code to execute if condition1 is true
elif condition2:
    # code to execute if condition2 is true
elif condition3:
    # code to execute if condition3 is true
else:
    # code to execute if all conditions are false

The following program demonstrates the if-elif-else statement:

Program

# if-elif statement example
num = 33
 
if num == 55:
    print("Number is 55")
 
elif num == 99:
    print("Number is 99")
 
elif num == 33:
    print("Number is 33")
 
else:
    print("num value is not equal to 33")

Output

Number is 33

Program

x = 0


if x> 0:
    print("Number is Positive")
elif x< 0:
    print("Number is Negative")
else:
    print("Zero")

Output

Zero

Ternary Expression Conditional Statements in Python

The ternary expression is also called a conditional operator. It determines if a condition is true or false and then returns the appropriate value as the result. The ternary operator is useful when we assign a value to a variable based on a simple condition.

Syntax

The syntax for a ternary expression in Python is as follows.

value_if_true if condition else value_if_false

The following program demonstrates conditional statements working.

Program 1

age = 18
status = "Adult" if age >= 18 else "Minor"
print(status)

Output

Adult

In the above program, we check the user’s age. If the user is over 18, it will print Adult; otherwise, it will print Minor.

Program 2: Nested Ternary Expression

score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "D" if score >= 60 else "F"
print(grade)

Output

B

Program 3: Nested Ternary Expression

number = 5
result = "Even" if number % 2 == 0 else "Odd"
print(result)  

Output

Odd

 The following program demonstrates that all the conditional statements are working.

Program

# Getting input from the user
number = int(input("Enter a number: "))


# If Conditional Statement
if number > 0:
    print("The number is positive.")


# If-else Conditional Statement
if number % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")


# Nested if-else Conditional Statement
if number >= 0:
    if number == 0:
        print("The number is zero.")
    else:
        print("The number is positive.")
else:
    print("The number is negative.")


# If-elif-else Conditional Statement
if number > 0:
    print("The number is positive.")
elif number < 0:
    print("The number is negative.")
else:
    print("The number is zero.")


# Ternary Expression Conditional Statement
result = "even" if number % 2 == 0 else "odd"
print(f"The number is {result}.")

Output

Enter a number: 2

The number is positive.

The number is even.

The number is positive.

The number is positive.

The number is even.

Advantages and Disadvantages of Conditional Statements

Let’s see the advantages and disadvantages of using conditional statements in Python.

Advantages Disadvantages
Conditional statements are easy to understand and use for basic decision-making tasks Nested Conditionals make code more difficult to read and maintain.
Helps in controlling the flow of the program based on conditions Multiple conditions may slow down execution if not used efficiently
It can handle multiple scenarios and complex decision-making processes. Complex conditional statements can be hard to debug and test
Simple if-else structures are generally easy to read and understand Repetitive conditions can lead to code duplication if not managed properly.
Allow for specific error handling and edge case management Overuse can lead to tangled code structures, known as spaghetti code.
Provides a clear, logical flow of operations based on different conditions Conditional statements are only as good as the logic defined. Flawed logic leads to incorrect outcomes.
Break down complex decision-making processes into complex, manageable parts This introduces additional overhead in terms of code execution time and complexity

Best Practices for Using Conditional Statements

  • Use Clear and Descriptive Conditions: Write conditions that are easy to understand using descriptive variable names and straightforward logic. This improves readability and makes the code easier to maintain.
  • Limit the Depth of Nesting: A conditional statement is a deeply nested condition that can make code hard to read and maintain. Reduce nesting by flattening your code, using logical operators, or returning early from functions.
  • Use Ternary Operators for Simple Conditions: The Developer can use ternary operators for single-line conditional assignment operators. They make the code more concise and maintain readability.
  • Avoid Deeply Nested Code: Refactor deeply nested code into separate functions or use guard clauses to exit early, simplifying the overall structure.

Conclusion

In this article, we learned how conditional statements are a fundamental aspect of Python programming. You can write more dynamic, flexible, and logical code by understanding ‘if’, ‘if-elif-else’, nested ‘if’, and ternary operators. Best practices include using clear and descriptive conditions, limiting the depth of nesting, and handling all possible cases, which ensures that your code remains readable, maintainable, and efficient. Mastering conditional statements is essential for developing robust Python applications.

FAQs
What are conditional statements in Python?
Conditional statements in Python allow you to execute specific blocks of code based on whether a certain condition is true or false. They control the flow of your program’s execution based on given inputs or conditions.
Are conditional statements case-sensitive in Python?
Python's conditional statements (e.g. ‘if’, ‘elif’, and ‘else’) are not case-sensitive. However, variable names and values compared in conditions are case-sensitive unless specified otherwise.
What is the purpose of conditional statements in Python?
In Python, conditional statements are essential for controlling the program's flow. They allow you to make decisions based on the values of variables or the results of comparisons. Conditional statements in Python are used to execute specific blocks of code based on whether a condition is true or false.

Updated on July 25, 2024

Link
Loading related articles...