---
# System prepended metadata

title: COHORT III WEEK 9

---

<strong>DAY 1</strong>

<strong>LOOPS</strong>
Loops in Python are used to repeat actions efficiently. The main types are:

1. For loops (counting through items) and
2. While loops (based on conditions).

<strong>FOR LOOPS</strong>
In Python, we use a for loop to iterate over sequences such as lists, strings, dictionaries, etc.
For example,
        
    languages = ['Swift', 'Python', 'Go']

    # access elements of the list one by one
    for lang in languages:
        print(lang)
        
        #OUTPUT
        Swift
        Python
        Go
        
In the above example, we have created a list named languages. Since the list has three elements, the loop iterates 3 times.

The value of lang is

Swift in the first iteration.
Python in the second iteration.
Go in the third iteration.
    
Example: Loop Through a String

If we iterate through a string, we get individual characters of the string one by one.

    language = 'Python'

    # iterate over each character in language
    for x in language:
        print(x)
        
    # Output

    P
    y
    t
    h
    o
    n
    
    
Here, we have printed each character of the string language using a for loop.

<strong>for Loop with Python range()</strong>

In Python, the range() function returns a sequence of numbers. For example,

    #generate numbers from 0 to 3
    values = range(0, 4)
Here, range(0, 4) returns a sequence of 0, 1, 2 ,and 3.

Since the range() function returns a sequence of numbers, we can iterate over it using a for loop. For example,

    # iterate from i = 0 to i = 3
    for i in range(0, 4):
    print(i)
    
    #Output

    0
    1
    2
    3
    
Here, we used the for loop to iterate over a range from 0 to 3.


BREAK AND CONTINUE STATEMENT

The break and continue statements are used to alter the flow of loops.

<strong>The break Statement</strong>

The break statement terminates the for loop immediately before it loops through all the items. For example,

    languages = ['Swift', 'Python', 'Go', 'C++']

    for lang in languages:
        if lang == 'Go':
            break
        print(lang)

    #Output

    Swift
    Python
    
Here, when lang is equal to 'Go', the break statement inside the if condition executes which terminates the loop immediately. This is why Go and C++ are not printed.
    
<strong>The continue Statement</strong>

The continue statement skips the current iteration of the loop and continues with the next iteration. For example,

    languages = ['Swift', 'Python', 'Go', 'C++']

    for lang in languages:
        if lang == 'Go':
            continue
        print(lang)

    #Output

    Swift
    Python
    C++
    
Here, when lang is equal to 'Go', the continue statement executes, which skips the remaining code inside the loop for that iteration.

However, the loop continues to the next iteration. This is why C++ is displayed in the output.
    
<strong>DAY 2</strong>

<strong>WHILE LOOPS</strong>

In Python, we use a while loop to repeat a block of code until a certain condition is met. For example,

    number = 1

    while number <= 3:
        print(number)
        number = number + 1

    #Output

    1
    2
    3
    
In the above example, we have used a while loop to print the numbers from 1 to 3. The loop runs as long as the condition number <= 3 is True.

while Loop Syntax

    while condition:
        # body of while loop
Here,

The while loop evaluates condition, which is a boolean expression.
If the condition is True, body of while loop is executed. The condition is evaluated again.
This process continues until the condition is False.
Once the condition evaluates to False, the loop terminates.

NOTE: We should update the variables used in condition inside the loop so that it eventually evaluates to False. Otherwise, the loop keeps running, creating an infinite loop.


PYTHON WHILE LOOP WITH A BREAK STATEMENT

We can use a break statement inside a while loop to terminate the loop immediately without checking the test condition. For example,

    while True:
        user_input = input('Enter your name: ')

        # terminate the loop when user enters end
        if user_input == 'end':
            print(f'The loop is ended')
            break  

        print(f'Hi {user_input}')

    #Output

    Enter your name: Kevin
    Hi Kevin
    
    Enter your name: end
    The loop is ended
    
Here, the condition of the while loop is always True. However, if the user enters end, the loop termiantes because of the break statement.

PYTHON WHILE LOOP WITH AN ELSE CLAUSE

In Python, a while loop can have an optional else clause - that is executed once the loop condition is False.

For example,
    
    counter = 0

    while counter  <  2:
        print('This is inside loop')
        counter = counter + 1
    else:
        print('This is inside else block')

    #Output

    This is inside loop
    This is inside loop
    This is inside else block
    
Here, on the third iteration, the counter becomes 2 which terminates the loop. It then executes the else block and prints This is inside else block.

Note: The else block will not execute if the while loop is terminated by a break statement.

<strong>Python if...else Statement</strong>
In computer programming, the if statement is a conditional statement. It is used to execute a block of code only when a specific condition is met. For example,

Suppose we need to assign different grades to students based on their scores.

If a student scores above 90, assign grade A
If a student scores above 75, assign grade B
If a student scores above 65, assign grade C
These conditional tasks can be achieved using the if statement.

<strong>Python if Statement</strong>

An if statement executes a block of code only when the specified condition is met.

    Syntax

    if condition:
        # body of if statement
        
Here, condition is a boolean expression, such as number > 5, that evaluates to either True or False.

If condition evaluates to True, the body of the if statement is executed.
If condition evaluates to False, the body of the if statement will be skipped from execution.

<strong>DAY 3</strong>

<strong>MATCH...CASE STATEMENT</strong>

The match…case statement allows us to execute different actions based on the value of an expression.

The syntax of the match...case statement in Python is:
    match expression:

      case value1:
        # code block 1 

      case value2:
        # code block 2 

      ...
      
Here, expression is a value or a condition to be evaluated.

If expression is equal to

value1, the code block 1 is executed.
value2, the code block 2 is executed.
In a match statement, only one of the options will be executed. Once a match is found, the corresponding block of code runs, and the rest are skipped.

Now, let's look at a few examples of the match..case statement.

operator = input("Enter an operator: ")

    x = 5
    y = 10

    match operator:
        case '+':
            result = x + y
        case '-':
            result = x - y
        case '*':
            result = x * y
        case '/':
            result = x / y        

    print(result)

    Output 1

    Enter an operator: *
    50
    
The operator variable stores the input from the user, which represents a mathematical operator. The match statement evaluates the value of operator and runs the corresponding code block.

If operator is:

+ : result = x + y is executed.
- : result = x - y is executed.
* : result = x * y is executed.
* / : result = x / y is executed.

While this program works for inputs +, -, *, and /, it will result in an error if we enter any other character as an operator.

    Output 2

    Enter an operator: %
    
    ERROR!
    NameError: name 'result' is not defined
    
We are getting this error because the input value (%) doesn't match with any cases.

To solve this problem, we can use the default case.

The default case
We use the default case, which is executed if none of the cases are matched. Here's how we use a default case:

    match expression:

       case value1:
          ....
       case value2:
          ...
       case _:     # default case
          ....
Here, _ represents the default case.

Let's solve the above error using the default case.

Example 2: The default case

    operator = input("Enter an operator: ")

    x = 5
    y = 10

    match operator:
        case '+':
            result = x + y
        case '-':
            result = x - y
        case '*':
            result = x * y
        case '/':
            result = x / y
        case _:
            result = "Unsupported operator"

    print(result)

    #Output

    Enter an operator: %
    Unsupported operator

Using match...case with | Operator

The match...case statement in Python is very flexible. For an instance, it is possible to match an expression against multiple values in case clauses using the | operator.

For example,

    status = int(input("Enter the status code: "))

    match status:
        case 200 | 201 | 202:
            print("Success")
        case 400 | 401 | 403:
            print("Client error")
        case 500 | 501 | 502:
            print("Server error")
        case _:
            print("Unknown status")

    #Output 1

    Enter the status code: 500
    Server error
    
    Output 2

 
Using Python if statement in Cases

In Python, we can also use the if statement in the case clauses. This is called guard, which adds an additional condition to an expression.

If the guard condition (the if statement) evaluates to False, the match statement skips that case and continues to the next one.

For example,

    subject = input("Enter a subject: ")
    score = int(input("Enter a score: "))

    match subject:
        # if score is 80 or higher in Physics or Chemistry
        case 'Physics' | 'Chemistry' if score >= 80:
            print("Excellent in Science!")
        
        # if score is 80 or higher in English or Grammar
        case 'English' | 'Grammar' if score >= 80:
            print("Excellent in English!")

        # if score is 80 or higher in Maths
        case 'Maths' if score >= 80:
            print("Excellent in Maths!")
        
        case _:
            print(f"Needs improvement in {subject}!")

    Output1

    Enter a subject: Chemistry
    Enter a score: 95
    Excellent in Science!
    
Here, case 'Physics' | 'Chemistry' if score >= 80: is executed because the subject matches "Chemistry" and the score 95 satisfies the if condition (score >= 80).

In case clauses, we used if statement to add an additional condition. Here, it checks whether the score is 80 or higher.

Note: When we use an if statement in cases, the if condition is evaluated only after a case match is found.















    
        
        
        
        
        
        