Python Workout 017 - Python Control Tower: Mastering Conditional Statements

Title: Python Control Tower: Mastering Conditional Statements

Description:

Python’s control flow is crucial for creating dynamic and responsive programs. In this workout, step into the world of if, else, and elif statements to make decisions and guide your code’s execution based on specific conditions.

Scenario:

You’re building a basic program that provides feedback based on user input. If a user enters a number, the program should classify it as positive, negative, or zero. Moreover, it should check if the number is even or odd. How can conditional statements help you create this responsive feedback system?

Objectives:

By the end of this workout, you should be able to:

  1. Understand the structure and usage of if, else, and elif statements in Python.

  2. Implement nested conditional statements for multi-layered decision making.

  3. Recognize common pitfalls and best practices in Python’s control flow.

Interactive Task:

Given your knowledge of Python’s conditional statements, answer the following:

  1. How would you structure an if statement to check if a number (let’s call it num) is positive?

    • Your Approach: ________________________
  2. Building on the previous task, how would you extend your code to classify num as positive, negative, or zero using elif and else?

    • Your Approach: ________________________
  3. To determine if num is even or odd, what condition would you use inside an if statement?

    • Your Answer: ________________________

Questions:

  1. In Python, which of the following is the correct way to check if a variable x is equal to 5?

    • i) if x = 5:

    • ii) if x == 5:

    • iii) if x: 5

    • iv) if x === 5:

  2. When should you use elif instead of a series of if statements?

    • i) When you want to check multiple unrelated conditions.

    • ii) When you have a single condition that requires a single response.

    • iii) When you want to execute only one block of code among several conditions.

    • iv) When you want all conditions to be checked, even if one is true.

Duration: 20 minutes

Difficulty: Beginner

Period:
This workout is released on Tuesday, October 10, 2023, and will end on Friday, October 20, 2023. But you can always come back to any of the workouts and solve them.

Hi There,

Here is my solution to this workout:

Questions:

  1. In Python, which of the following is the correct way to check if a variable x is equal to 5?
    Answer:
  • ii) if x == 5:
  1. When should you use elif instead of a series of if statements?
    Answer:
  • iii) When you want to execute only one block of code among several conditions.

Interactive Task:

  1. How would you structure an if statement to check if a number (let’s call it num ) is positive?

Approach:
In Python, you can structure an if statement to check if a number (let’s call it num) is positive as follows:

if num > 0:
    print("The number is positive.")

This code will print “The number is positive.” if the value of num is greater than zero. If num is not greater than zero (i.e., it’s either negative or zero), the print statement will not be executed. This is because the condition in the if statement (num > 0) will not be true.

  1. Building on the previous task, how would you extend your code to classify num as positive, negative, or zero using elif and else ?

Approach:
You can extend the previous code to classify a number (num) as positive, negative, or zero using elif and else in Python as follows:

if num > 0:
    print("The number is positive.")
elif num < 0:
    print("The number is negative.")
else:
    print("The number is zero.")

In this code:

  • The if statement checks if num is greater than zero. If this condition is true, it prints “The number is positive.”
  • If the first condition is not met, the elif statement checks if num is less than zero. If this condition is true, it prints “The number is negative.”
  • If neither the if nor the elif conditions are met (which means num is not greater than zero and not less than zero), the else statement executes and prints “The number is zero.” This happens when num equals zero.
    This way, the code classifies num as positive, negative, or zero.
  1. To determine if num is even or odd, what condition would you use inside an if statement?

Answer:
To determine if a number (num) is even or odd in Python, you can use the modulus operator (%). The condition inside the if statement would be num % 2 == 0. Here’s how you can structure it:

if num % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")

In this code:

  • The if statement checks if the remainder of num divided by 2 is 0. If this condition is true (which means num is evenly divisible by 2), it prints “The number is even.”
  • If the condition in the if statement is not met (which means num is not evenly divisible by 2), the else statement executes and prints “The number is odd.”

This way, the code determines if num is even or odd.

Thanks for the workout.
Keith

Answer:

Interactive Task:

  1. num_sign = "positive" if num > 0 else pass
  2. num_sign = "positive" if num > 0 else ("negative" if num < 0 else "zero")
  3. even_odd = "even" if num % 2 == 0 else "odd"

Questions:

  1. ii) if x == 5:
  2. iii) When you want to execute only one block of code among several conditions.

Problem Solution Script:

"""
Even-Odd & Sign Check
================================================
Author: Udit Kumar Chatterjee
Email: quantumudit@gmail.com
================================================

This script provides a function to check whether a given integer is positive, negative, 
or zero, and if it's even or odd. The function returns a tuple with two strings: 
the first indicates the number's sign (positive, negative, or zero), and 
the second specifies its parity (even or odd).
"""


def check_num(num: int) -> tuple:
    """
    Determine whether a given number is positive, negative, or zero and whether it is even or odd.

    Args:
        num (int): The integer number to be checked.

    Returns:
        tuple: A tuple containing two strings:
            - The first string indicates whether the number is "positive," "negative," or "zero."
            - The second string indicates whether the number is "even" or "odd."
    """
    num_sign = "positive" if num > 0 else "negative"
    even_odd = "even" if num % 2 == 0 else "odd"

    return (num_sign, even_odd)


if __name__ == "__main__":
    NUM_INPUT = input("Provide a number: ")
    try:
        number = int(NUM_INPUT)
        if number == 0:
            print("The number is zero")
        else:
            result = check_num(num=number)
            print(f"The number {number} is a {result[0]} {result[1]} number")
    except ValueError:
        print("Input number is not an integer")