Day 4: Control Structures

Control structures in Python are statements that enable you to control the flow of a program’s execution. With control structures, you can execute certain blocks of code based on specific conditions.

There are three types of control structures in Python:

Conditional Statements

In Python, conditional statements are used to execute a block of code if a specific condition is met. The most commonly used conditional statement in Python is the if statement. The if statement is followed by a condition that is either True or False, and if the condition is True, the code block is executed.

The basic syntax of an if statement is as follows:

if condition:
    # code block

The code block is indented and contains the code that will be executed if the condition is True. If the condition is False, the code block will be skipped, and the program will continue to the next statement after the if block.

Here’s an example of how to use an if statement in Python:

x = 10

if x > 5:
    print("x is greater than 5")

In this example, the condition is x > 5. Since the value of x is 10, which is greater than 5, the code block is executed, and the output is “x is greater than 5”.

You can also use the else statement to specify a code block that should be executed if the condition is False. The syntax of an if-else statement is as follows:

if condition:
    # code block if condition is True
else:
    # code block if condition is False

Here’s an example of how to use an if-else statement in Python:

x = 3

if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

In this example, the condition is x > 5. Since the value of x is 3, which is less than 5, the code block after the else statement is executed, and the output is “x is less than or equal to 5”.

You can also use the elif statement to specify multiple conditions. The syntax of an if-elif-else statement is as follows:

if condition1:
    # code block if condition1 is True
elif condition2:
    # code block if condition2 is True
else:
    # code block if condition1 and condition2 are False

Here’s an example of how to use an if-elif-else statement in Python:

x = 10

if x > 20:
    print("x is greater than 20")
elif x > 5:
    print("x is greater than 5 and less than or equal to 20")
else:
    print("x is less than or equal to 5")

In this example, the condition x > 20 is False. The second condition, x > 5, is True since the value of x is 10. Therefore, the code block after the elif statement is executed, and the output is “x is greater than 5 and less than or equal to 20”.

Conditional statements are essential in programming as they allow you to control the flow of the program and execute specific blocks of code based on specific conditions.

Looping Statements

In Python, looping statements are used to execute a block of code repeatedly. There are two types of looping statements in Python: the for loop and the while loop.

The for loop is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each element in the sequence. Here’s an example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

In this example, we’re using a for loop to iterate over the fruits list and print each fruit.

The while loop is used to execute a block of code repeatedly as long as a certain condition is True. Here’s an example:

i = 1
while i <= 5:
    print(i)
    i += 1

In this example, we’re using a while loop to print the values of i from 1 to 5.

It’s important to be careful with looping statements to avoid infinite loops, where the loop never ends. An infinite loop can cause your program to hang or crash. Here’s an example of an infinite loop:

i = 1
while True:
    print(i)
    i += 1

In this example, we’re using a while loop with a condition that is always True, so the loop will never end.

To avoid infinite loops, make sure that your loop has a way to terminate. You can use a break statement to exit a loop prematurely if a certain condition is met. Here’s an example:

i = 1
while True:
    print(i)
    i += 1
    if i > 5:
        break

In this example, we’re using a while loop with a condition that is always True, but we’re using a break statement to exit the loop once i is greater than 5.

Exception Handling Statements

Exception handling statements are used to handle errors that occur during the execution of a program. In Python, exceptions are errors that occur during the execution of a program and can cause the program to terminate. To handle exceptions, you can use the try-except block.

The try statement is used to specify a block of code to be executed. If an error occurs in this block of code, the except statement is used to specify a block of code to be executed to handle the error. The finally statement is used to specify a block of code to be executed regardless of whether an error occurs.

Here’s an example of a try-except block:

try:
    num = int(input("Enter a number: "))
    print("The number is", num)
except:
    print("Invalid input")
finally:
    print("Execution complete")

In this example, the try block asks the user to enter a number, and if the user enters a valid number, the number is printed. If the user enters an invalid input, the except block is executed, and the message “Invalid input” is printed. The finally block is executed regardless of whether an error occurs.

You can also handle specific types of exceptions by specifying the type of exception in the except statement. For example:

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print("The result is", result)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid input")
finally:
    print("Execution complete")

In this example, there are two except statements: one for the ZeroDivisionError exception and one for the ValueError exception. The ZeroDivisionError exception is raised when the user enters 0 as input, and the ValueError exception is raised when the user enters a non-numeric input.

By using exception handling statements, you can make your programs more robust and handle errors gracefully.

Exercise:

  1. Write a program that asks the user for their age and checks if they are old enough to vote. If the user is 18 or older, print a message that says they are old enough to vote. Otherwise, print a message that says they are not old enough to vote.
  2. Write a program that generates a random number between 1 and 10 and asks the user to guess the number. If the user’s guess is correct, print a message that says “Congratulations, you guessed the number!” If the user’s guess is too low, print a message that says “Your guess is too low, try again.” If the user’s guess is too high, print a message that says “Your guess is too high, try again.”
  3. Write a program that calculates the sum of all the even numbers between 1 and 100. Print the result.
  4. Write a program that prints the first 10 numbers in the Fibonacci sequence.
  5. Write a program that asks the user to enter a word and then checks if the word is a palindrome (i.e., the word is spelled the same way forwards and backwards). If the word is a palindrome, print a message that says “The word is a palindrome.” If the word is not a palindrome, print a message that says “The word is not a palindrome.”

These exercises will help you practice using conditional statements, loops, and exception handling in Python. Good luck!