Open In Colab

3. Control Flow#

At the most basic level, “control flow” refers to the order in which the statements, instructions, or function calls of a program are executed or evaluated. In Python and most other programming languages, control flow is a fundamental concept that allows a program to be more than just a simple, linear sequence of commands.

Here are the main types of control flow mechanisms in Python:

  1. Sequential: This is the most basic and common type. The computer executes Python commands one after the other in the order they’re given.

Example:

print("Hello,")
print("world!")
  1. Conditional statements (if, elif, else): These are used when you want some blocks of code to only run when certain conditions are met.

Example:

x = 10
if x > 0:
    print("x is positive")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")
  1. Loops (for, while): Loops are used when you want to repeat a block of code multiple times.

Example of a for loop:

for i in range(5):
    print(i)

Example of a while loop:

i = 0
while i < 5:
    print(i)
    i += 1
  1. Flow control statements (break, continue, pass, return): These are used to influence the flow of execution inside loops and functions.

Example with break and continue:

for i in range(5):
    if i == 2:
        continue  # this skips the rest of the loop for this iteration
    if i == 4:
        break  # this stops the loop entirely
    print(i)
for number in range(1, 6):
    if number % 2 == 0:
        print(f"{number} is even.")
    else:
        print(f"{number} is odd.")
1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.

Practices and Solution Code#

  1. Write a Python program that iterates through the numbers from 1 to 10 and prints whether each number is a multiple of 3 or not.

Instructions:

  1. Use a for loop to iterate through the numbers from 1 to 10.

  2. Inside the loop, use an if statement to check if the current number is a multiple of 3.

  3. f the number is a multiple of 3, print a message stating that the number is a multiple of 3.

  4. If the number is not a multiple of 3, print a message stating that the number is not a multiple of 3.

Example output:

1 is not a multiple of 3.
2 is not a multiple of 3.
3 is a multiple of 3.
4 is not a multiple of 3.
5 is not a multiple of 3.
6 is a multiple of 3.
7 is not a multiple of 3.
8 is not a multiple of 3.
9 is a multiple of 3.
10 is not a multiple of 3.

Tip

  • Use the range() function to generate a sequence of numbers from 1 to 10.

  • Use the modulo operator % to check if a number is a multiple of another number. If the remainder of the division is 0, the number is a multiple of the other number.

  • Use f-strings or string concatenation to format the output message.

Practices and Solution Code#

  1. Write a Python program that iterates through the numbers from 1 to 15 and prints whether each number is divisible by 4 or not.

Instructions:#

  1. Use a for loop to iterate through the numbers from 1 to 15.

  2. Inside the loop, use an if statement to check if the current number is divisible by 4.

  3. If the number is divisible by 4, print a message stating that the number is divisible by 4.

  4. If the number is not divisible by 4, print a message stating that the number is not divisible by 4.

Example output:#

1 is not divisible by 4.
2 is not divisible by 4.
3 is not divisible by 4.
4 is divisible by 4.
5 is not divisible by 4.
6 is not divisible by 4.
7 is not divisible by 4.
8 is divisible by 4.
9 is not divisible by 4.
10 is not divisible by 4.
11 is not divisible by 4.
12 is divisible by 4.
13 is not divisible by 4.
14 is not divisible by 4.
15 is not divisible by 4.
  • Use the range() function to generate a sequence of numbers from 1 to 15.

  • Use the modulo operator % to check if a number is divisible by another number. If the remainder of the division is 0, the number is divisible by the other number.

  • Use f-strings or string concatenation to format the output message.

# Start your code here...

in statement#

In Python, the in keyword is part of the control flow tools, especially when combined with if statements or loops. It’s commonly used for checking if an item exists in a collection like a list or a dictionary, or if a substring exists in a string.

Here’s how it works:

  1. Checking for membership in a collection:

In this case, it can be used with the if keyword to check if a specific value exists in a collection (like a list, tuple, or dictionary).

Example:

numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
    print("3 is in the list!")

If you run this code with the same list as before, it will print each number on a separate line.

  1. Iterating over a collection with a for loop:

The in keyword can also be used in a for loop to iterate over each item in a collection.

Example:

for number in numbers:
    print(number)
  1. Checking for a substring within a string:

The in keyword can be used to check if a certain sequence of characters (substring) is part of a larger string.

Example:

sentence = "Hello, world!"
if "world" in sentence:
    print("The word 'world' is in the sentence.")

If you run this code, it will print “The word ‘world’ is in the sentence.” because “world” is indeed a substring of “Hello, world!”.

Overall, the in keyword is a very useful tool for controlling the flow of your Python programs, especially when you need to work with collections of items or strings.

fruits = ["apple", "banana", "orange", "grape", "kiwi"]

# Check if "banana" exists in the list
if "banana" in fruits:
    print("Banana is in the list of fruits.")

# Check if "mango" exists in the list
if "mango" not in fruits:
    print("Mango is not in the list of fruits.")
Banana is in the list of fruits.
Mango is not in the list of fruits.

Practices and Solution Code#

  1. Write a Python program that iterates through a list of animals and prints whether each animal is a mammal or not.

Instructions:#

  1. Create a list of animals including mammals and non-mammals.

  2. Use a for loop to iterate through the list of animals.

  3. Inside the loop, use an if statement to check if the current animal is a mammal.

  4. If the animal is a mammal, print a message stating that the animal is a mammal.

  5. If the animal is not a mammal, print a message stating that the animal is not a mammal.

Example list of animals:#

animals = ["dog", "cat", "crocodile", "parrot", "elephant"]

Example output:#

dog is a mammal.
cat is a mammal.
crocodile is not a mammal.
parrot is not a mammal.
elephant is a mammal.

Tip

  • Create a list of mammals that you can use to check if an animal is a mammal or not.

  • Use the in keyword to check if an item exists in a list.

  • Use f-strings or string concatenation to format the output message.

# Start you code here ....

Practices and Solution Code#

  1. Write a Python program that iterates through a list of cities and prints whether each city is a capital city or not.

Instructions:#

  1. Create a list of cities including capital and non-capital cities. Use a for loop to iterate through the list of cities.

  2. Inside the loop, use an if statement to check if the current city is a capital city.

  3. If the city is a capital city, print a message stating that the city is a capital city.

  4. If the city is not a capital city, print a message stating that the city is not a capital city.

Example list of cities:#

cities = ["Paris", "Tokyo", "New York", "Berlin", "Madrid", "London", "Sydney"]

Example output:#

Paris is a capital city.
Tokyo is a capital city.
New York is not a capital city.
Berlin is a capital city.
Madrid is a capital city.
London is a capital city.
Sydney is not a capital city.
# start you code here ...

Practices and Solution Code#

  1. Write a Python program that iterates through a list of cars and prints whether each car is a electric or not

Tesla Model 3 is an electric vehicle.
Nissan Leaf is an electric vehicle.
Toyota Corolla is not an electric vehicle.
Ford Mustang is not an electric vehicle.
Chevrolet Bolt is an electric vehicle.
BMW i3 is an electric vehicle.

Concept of len() and enumerate()#

# Create a list of fruits
fruits = ["apple", "banana", "orange", "grape", "kiwi"]

# Print the length of the list using len()b
print(f"Total number of fruits: {len(fruits)}")
Total number of fruits: 5
# Use enumerate() to iterate through the list along with the index
for index, fruit in enumerate(fruits):
    # The index starts at 0, so we add 1 to get the correct position
    print(f"{index + 1}. {fruit}")
1. apple
2. banana
3. orange
4. grape
5. kiwi
# Access an item from the list using its index
print("The first fruit in the list is:", fruits[0])
print("The last fruit in the list is:", fruits[-1])
The first fruit in the list is: apple
The last fruit in the list is: kiwi

Practices and Solution Code#

  1. Write a Python program that iterates through a list of programming languages and prints whether each language is a compiled or interpreted language, along with its position in the list.

Instructions:#

  1. Create a list of programming languages including both compiled and interpreted languages.

  2. Use a for loop with the enumerate() function to iterate through the list of programming languages along with their index.

  3. Inside the loop, use an if statement to check if the current language is a compiled language.

  4. If the language is a compiled language, print a message stating that the language is a compiled language and its position in the list.

  5. If the language is not a compiled language, print a message stating that the language is an interpreted language and its position in the list.

  6. Use the len() function to print the total number of programming languages in the list.

Example list of programming languages:#

languages = ["C", "Java", "Python", "Ruby", "C#", "JavaScript", "Swift"]

Example output:#

1. C is a compiled language.
2. Java is a compiled language.
3. Python is an interpreted language.
4. Ruby is an interpreted language.
5. C# is a compiled language.
6. JavaScript is an interpreted language.
7. Swift is a compiled language.
Total number of programming languages: 7
# Start you code here