Python Conditional Statements

Table of Contents

Introduction:

In Python, the if-else statement allows you to execute different blocks of code based on certain conditions. It provides a way to make decisions and control the flow of your program.

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

				
					if condition:
    # Code block to execute if the condition is True
else:
    # Code block to execute if the condition is False

				
			

The condition is an expression that evaluates to either True or False. If the condition is True, the code block immediately following the if statement will be executed. Otherwise, if the condition is False, the code block following the else statement will be executed.

Let’s look at an example to understand it better. Suppose we want to check whether a given number is positive or negative:

				
					number = int(input("Enter a number: "))
if number > 0:
    print("The number is positive.")
else:
    print("The number is negative or zero.")

				
			

In this example, we use the input() function to get a number from the user, convert it to an integer using int(), and store it in the number variable. The if-else statement then checks whether the number is greater than zero. If it is, it prints “The number is positive.” Otherwise, it prints “The number is negative or zero.”

You can also use multiple if-else statements together to handle more complex conditions. Here’s an example that checks whether a number is positive, negative, or zero:

				
					number = int(input("Enter a number: "))
if number > 0:
    print("The number is positive.")
elif number < 0:
    print("The number is negative.")
else:
    print("The number is zero.")

				
			

In this case, the elif statement allows us to check an additional condition. If the first condition is False, it moves to the elif statement and checks whether the number is less than zero. If that condition is True, it prints “The number is negative.” Finally, if both the first and second conditions are False, it executes the code block under the else statement and prints “The number is zero.”

Python conditional statement features:

  1. `if` statement: The `if` statement is the fundamental building block of a conditional statement. It allows you to execute a block of code if a certain condition is true. The syntax of the `if` statement is as follows:
				
					if condition:
        # Code block to execute if the condition is True

				
			
  1. `else` statement: The `else` statement is used in conjunction with the `if` statement. It provides an alternative block of code to execute when the condition in the `if` statement is false. The syntax is as follows:
				
					if condition:
       # Code block to execute if the condition is True
   else:
       # Code block to execute if the condition is False

				
			
  1. `elif` statement: The `elif` statement allows you to check additional conditions after an initial `if` statement. It provides a way to handle multiple cases within the same conditional statement. The syntax is as follows:
				
					if condition1:
       # Code block to execute if condition1 is True
   elif condition2:
       # Code block to execute if condition1 is False and condition2 is True
   else:
       # Code block to execute if all conditions are False

				
			
  1. Nested conditional statements: Python allows you to nest if-else statements within other if-else statements. This means that you can have if-else statements inside the code blocks of other if-else statements. This feature enables handling more complex conditions and creating decision trees.
  1. Logical operators: Python provides logical operators such as `and`, `or`, and `not` that allow you to combine multiple conditions. These operators can be used within the condition of an if statement to create more complex conditions.
  1. Ternary operator: Python supports a ternary operator, which provides a concise way to write conditional expressions in a single line. The syntax is as follows:
				
					value_if_true if condition else value_if_false
				
			

This operator allows you to assign a value based on a condition without writing a full if-else statement.

Python conditional statements advantages:

  1. Decision-making: Conditional statements provide a way to make decisions in your Python programs. They allow you to execute different blocks of code based on the evaluation of specific conditions. This enables your program to respond dynamically to different situations and perform different actions as needed.
  2. Flexibility: Conditional statements provide flexibility in controlling the flow of your program. By using conditions, you can define different paths or branches of execution based on varying inputs or states. This flexibility allows you to handle diverse scenarios and customize the behavior of your program accordingly.
  3. Code organization: Using conditional statements helps in organizing your code. By dividing your code into blocks based on conditions, you can make it more structured and readable. Each block of code within a conditional statement represents a specific case or behavior, making it easier to understand the logic and purpose of different parts of your program.
  4. Error handling: Conditional statements are often used for error handling and exception handling in Python. By checking certain conditions, you can identify and handle specific error scenarios or exceptional cases appropriately. This allows you to anticipate and respond to errors or unexpected inputs, improving the overall robustness of your program.
  5. Code efficiency: Conditional statements can help optimize your code by selectively executing relevant blocks of code based on conditions. This can reduce unnecessary computations or operations, improving the efficiency and performance of your program. For example, you can include conditional checks to avoid executing resource-intensive code when certain conditions are not met.
  6. Complex decision trees: With the ability to nest conditional statements and combine logical operators, you can create complex decision trees in Python. This allows you to handle intricate conditions and multiple cases effectively. By structuring your code in this manner, you can handle a wide range of possibilities and make your programs more adaptable to diverse scenarios.

Python conditional statement disadvantages:

  1. Code complexity: As the number of conditions and branches increases, conditional statements can make the code more complex and harder to understand. Nested if-else statements or multiple elif conditions can make the code difficult to follow and maintain, leading to potential bugs or errors.
  2. Code duplication: In certain cases, conditional statements can result in code duplication. If similar blocks of code need to be executed in different branches of the conditional statements, you may end up duplicating that code, which can lead to maintenance issues. Code duplication can make it harder to update or modify the logic consistently across multiple branches.
  3. Readability and maintainability: While conditional statements can provide flexibility, excessive or poorly organized conditional logic can decrease code readability and maintainability. If the conditional statements become too complex or nested, it may become challenging for other developers (including yourself in the future) to understand the code and make modifications.
  4. Potential for errors: The use of conditional statements introduces the possibility of logical errors, such as incorrect conditions or unintended behavior due to missing conditions. It’s important to carefully design and test the conditions to ensure they cover all relevant cases and produce the expected results.
  5. Scalability: Conditional statements may become less scalable when handling a large number of conditions or cases. If the number of conditions grows significantly, maintaining and extending the conditional logic can become cumbersome. In such cases, alternative approaches, such as using dictionaries or lookup tables, may be more appropriate to handle complex mappings or decision-making.
  6. Code coupling: Conditional statements can introduce tight coupling between different parts of your code, especially if the conditions rely on specific variables or states. This can make it harder to modify or refactor your code in the future without affecting other parts of the program.

Python conditional statement – If statement:

In Python, the if statement allows you to execute a block of code only if a certain condition is true. It provides a way to make decisions and control the flow of your program.The basic syntax of an if statement in Python is as follows:

				
					if condition:
    # Code block to execute if the condition is True

				
			

The `condition` is an expression that evaluates to either `True` or `False`. If the condition is `True`, the code block immediately following the `if` statement will be executed. Otherwise, if the condition is `False`, the code block will be skipped, and the program will continue with the next line of code. Here’s an example:

				
					number = int(input("Enter a number: "))
if number > 0:
    print("The number is positive.")

				
			

In this example, we use the `input()` function to get a number from the user, convert it to an integer using `int()`, and store it in the `number` variable. The if statement then checks whether the number is greater than zero. If it is, it executes the code block under the if statement and prints “The number is positive.”

Python conditional statement – If-else statement:

In Python, the if-else statement allows you to execute different blocks of code based on certain conditions. It provides a way to make decisions and control the flow of your program. The basic syntax of an if-else statement in Python is as follows:

				
					if condition:
    # Code block to execute if the condition is True
else:
    # Code block to execute if the condition is False

				
			

The `condition` is an expression that evaluates to either `True` or `False`. If the condition is `True`, the code block immediately following the `if` statement will be executed. Otherwise, if the condition is `False`, the code block following the `else` statement will be executed. Here’s an example:

				
					number = int(input("Enter a number: "))
if number > 0:
    print("The number is positive.")
else:
    print("The number is negative or zero.")

				
			

In this example, we use the `input()` function to get a number from the user, convert it to an integer using `int()`, and store it in the `number` variable. The if-else statement then checks whether the number is greater than zero. If it is, it executes the code block under the `if` statement and prints “The number is positive.” Otherwise, if the number is not greater than zero, it executes the code block under the `else` statement and prints “The number is negative or zero.”

Python conditional statement – elif statement:

In Python, the `elif` statement allows you to check additional conditions after an initial `if` statement. It provides a way to handle multiple cases and execute different blocks of code based on the conditions. The basic syntax of an `elif` statement in Python is as follows:

				
					if condition1:
    # Code block to execute if condition1 is True
elif condition2:
    # Code block to execute if condition1 is False and condition2 is True
elif condition3:
    # Code block to execute if condition1 and condition2 are False, and condition3 is True
else:
    # Code block to execute if all conditions are False

				
			

You can have as many `elif` statements as needed to handle different conditions. The conditions are evaluated one by one, from top to bottom. If a condition is `True`, the corresponding code block will be executed, and the remaining conditions will be skipped. If none of the conditions are `True`, the code block under the `else` statement will be executed. Here’s an example:

				
					Marks = int(input("Enter the student's marks: "))
if marks >= 90:
    grade = 'A'
elif marks >= 80:
    grade = 'B'
elif marks >= 70:
    grade = 'C'
elif marks >= 60:
    grade = 'D'
else:
    grade = 'F'
print("The student's grade is:", grade)

				
			

In this example, we use the `input()` function to get the student’s score, convert it to an integer using `int()`, and store it in the `score` variable. The `elif` statements check the score against different ranges to determine the letter grade. If the score is greater than or equal to 90, it assigns the grade ‘A’. If the score is between 80 and 89, it assigns ‘B’, and so on. If none of the conditions are met, it assigns ‘F’ as the grade. Finally, we print the grade using the `print()` function.

Python nested conditional statement – nested if-else statements:

In Python, nested if-else statements allow you to have if-else statements within other if-else statements. They provide a way to handle complex conditions and execute different blocks of code based on multiple conditions. The basic syntax of a nested if-else statement in Python is as follows:

				
					if condition1:
    # Code block to execute if condition1 is True
    if condition2:
        # Code block to execute if condition1 and condition2 are True
    else:
        # Code block to execute if condition1 is True and condition2 is False
else:
    # Code block to execute if condition1 is False

				
			

In a nested if-else statement, the inner if-else statement is indented further to the right than the outer if-else statement. The inner if-else statement is evaluated only if the condition of the outer if statement is `True`. Here’s an example:

				
					marks = int(input("Enter the student's score: "))
credit = input("Did the student earn extra credit? (yes/no): ")

if marks >= 90:
    if credit == 'yes':
        grade = 'A+'
    else:
        grade = 'A'
elif marks >= 80:
    if credit == 'yes':
        grade = 'B+'
    else:
        grade = 'B'
else:
    grade = 'F'
print("The student's grade is:", grade)

				
			

In this example, we use the `input()` function to get the student’s score and whether they earned extra credit. The `elif` statements check the score against different ranges to determine the letter grade. However, the grade also depends on whether the student earned extra credit.

If the score is greater than or equal to 90, it checks the `credit` variable. If it is ‘yes’, it assigns the grade ‘A+’. Otherwise, it assigns ‘A’.

Similarly, for scores between 80 and 89, it checks the `credit` variable to assign either ‘B+’ or ‘B’.

If none of the conditions are met, it assigns ‘F’ as the grade.

Finally, we print the grade using the `print()` function.

Python If else Practice Programs

Leave a Comment