Python Basics: Understanding Conditionals, Booleans, and Error Handling

Python Basics: Understanding Conditionals, Booleans, and Error Handling

Conditionals, Boolean Data Types and Error Handling

Boolean Data Types:

Booleans are the simplest data types in Python:

  • True: Represents a positive condition

  • False: Represents a negative condition

  •       is_raining = True
          if is_raining:
              print("Bring an umbrella!")
    

    In Python, conditionals are used to perform different actions based on whether a certain condition is true or false. The most common conditional statements in Python are if, elif, and else

  • Conditionals control the flow of a program based on boolean logic. They evaluate whether statements are True or False and execute code accordingly.

  • Example of If, elif and else statement below

  • symbol == equation check, = assign value


calc_of_units = 24
name_of_units = "hours"


def days_to_units(num_of_days):
    if num_of_days > 0 :
        return f"{num_of_days} days are {num_of_days * calc_of_units} {name_of_units}"


def validate_exe():
    if user_inp.isdigit():
        user_inp_num = int(user_inp)
        calc_value = days_to_units(user_inp_num)
        print(calc_value)
    else: 
        print("not a valid num")


user_inp = input("input no of days i will convert it to hours\n")
validate_exe()

Nesting Conditionals:

We can also nest conditionals, meaning we can have an if inside another if:

x = 10
if x > 5:
    if x < 15:
        print("x is between 5 and 15")
calc_of_units = 24
name_of_units = "hours"


def days_to_units(num_of_days):

        return f"{num_of_days} days are {num_of_days * calc_of_units} {name_of_units}"


def validate_exe():
    if user_inp.isdigit():
        user_inp_num = int(user_inp)
        if user_inp_num > 0 :
             calc_value = days_to_units(user_inp_num)
             print(calc_value)
        elif user_inp_num == 0:
             print("you entered 0")
    else: 
        print("not a valid num")


user_inp = input("input no of days i will convert it to hours\n")
validate_exe()

Error Handling with Try/Except

  • In Python, try and except blocks are used for handling exceptions. They allow us to attempt code execution while gracefully handling potential errors.
try:
    x = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")

--------
calc_of_units = 24
name_of_units = "hours"


def days_to_units(num_of_days):

        return f"{num_of_days} days are {num_of_days * calc_of_units} {name_of_units}"


def validate_exe():
    try:
        user_inp_num = int(user_inp)
        if user_inp_num > 0 :
             calc_value = days_to_units(user_inp_num)
             print(calc_value)
        elif user_inp_num == 0:
             print("you entered 0")
    except ValueError: 
        print("not a valid num")


user_inp = input("input no of days i will convert it to hours\n")
validate_exe()
  • finally: print("This will always run.")