Skip to main content

For Loops

Revisiting While Loops

A while loop is used when we want to repeat a block of code as long as a condition is true.

  • It works well when:
  • We don’t know in advance how many iterations are needed.
  • We waiting for a condition to be satisfied dynamically during runtime.

Example:

count = 0
while count < 5:
print(count)
count += 1

But while loops can become clunky or error-prone in specific scenarios.

Use Cases Where While Loops Are Less Effective

  • Iterating Through a Range of Numbers

    • Suppose we want to print numbers from 1 to 5.
    • Using a while loop requires initializing, updating, and checking a counter manually.
    • If we forget to update the counter, it can cause an infinite loop.

Example:

count = 1
while count <= 5:
print(count)
count += 1
  • Iterating Over a List

    • Say we have a list of student names, and we want to print each name.
    • Using a while loop would require manually managing the index.

    Please complete the following exercise using while loop:

#Print list of numbers
students = ["Alice", "Bob", "Charlie"]

Simplyfing iterations with for loop

Using while loop to iterate over a list of items like characters of a string or items of list needs 3 steps:

    1. Initializing a condition, like a counter. e.g
    count = 1
    1. Checking for the condition and if true execute the code inside the loop. e.g:
while count < 5:
    1. Updating the condition
count += 1

Introducing for loop

The above problems can be solved with for loop much easily.

  • Iterating Through a Range of Numbers

    numbers = [1, 2, 3, 4, 5]
    for num in numbers:
    print(num)
  • Iterating Over a List

    students = ["Alice", "Bob", "Charlie"]
    for student in students:
    print(student)

Core Concepts of a For Loop

Iteration

What is Iteration?

Iteration is the process of performing a task repeatedly for each item in a sequence. In a for loop, this means:

  • Each item in the sequence is fetched one at a time.
  • The loop variable is assigned the value of the current item.
  • The code block inside the loop executes for that item.

Illustration with the printing numbers

numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(f"Current value of i: {num}")
  • Step-by-step Iteration:

    • The numbers = [1, 2, 3, 4, 5] initializes a list of numbers [1, 2, 3, 4, 5] and assigns it to variable numbers.
    • During the first iteration, i = 1 → print(f"Current value of i: {i}") prints Current value of i: 1
    • During the second iteration, i = 2 → prints Current value of i: 2
    • This continues until i takes on the value 5.

Please think about the following questions before moving on to the next section

  1. Why does the first print statement prints Current value of i: 1 ? Where does the 1 come from?
  2. Why does the loop stops when we have not specified a exit condition?

Illustration with the Student List Example

students = ["Alice", "Bob", "Charlie"]
for student in students:
print(f"Current student: {student}")
  • Step-by-step Iteration:

    • The students list contains ["Alice", "Bob", "Charlie"].
    • During the first iteration, student = "Alice" → print(f"Current student: {student}") prints Current student: Alice.
    • During the second iteration, student = "Bob" → prints Current student: Bob.
    • During the third iteration, student = "Charlie" → prints Current student: Charlie.

Sequence / Iterable

The sequence can be anything iterable, such as a list, tuple, string, dictionary, or a range object.

A for loop can only iterate over a set of data that is iterable.

An iterable is any object in Python that can be iterated (looped) over. This means the object can provide one item at a time to the loop.

  • Think of an iterable as a collection of items (like a list of numbers or a string of characters) that we can go through one by one.

  • Examples of iterables include:

    • Lists: ["apple", "banana", "cherry"]
    • Strings: "hello"
    • Tuples: (1, 2, 3)
    • Dictionaries: {"name": "Alice", "age": 25}
    • Range Objects: range(1, 6)

How Does an Iterable Work?

  • Iterables provide an iterator when we try to loop over them. An iterator is an object that produces the items of an iterable one by one.
  • Python automatically handles this process when we use a for loop.

Example:

my_list = [1, 2, 3]  # A list is iterable
for item in my_list:
print(item)
  • Behind the scenes:
    • Python asks: "Is my_list iterable?" Yes, it is.
    • Python creates an iterator for my_list.
    • The for loop fetches one item at a time from the iterator and assigns it to item.
    • When the iterator is exhausted (no more items), the loop stops.

Automatic Termination

What is Automatic Termination?

  • A for loop stops automatically once all elements in the sequence are processed. There’s no need for manual counters or stopping conditions (unlike a while loop).

Example

for i in range(1, 6):
print(i)
  • How Does it Terminate?

    • The range(1, 6) sequence generates 5 numbers: [1, 2, 3, 4, 5].
    • The loop stops automatically when there are no more numbers left in the sequence.
    • we don’t need to check or update any counter variables; Python handles it internally.

Exploring String, Tuple, and Range as Iterables

Let’s introduce strings, tuples, and range objects in the context of sequences and iterables. These are all iterable objects in Python.

String as a Sequence

A string is a sequence of characters. we can think of it as an "list" of characters where each character can be accessed one by one.

Example:

word = "hello"
for char in word:
print(char)

Output:

h
e
l
l
o

Explanation:

  • The string "hello" is iterable because it’s a sequence of characters.
  • The loop processes each character ('h', 'e', 'l', 'l', 'o') one at a time.
  • we can also access individual characters directly using their index, e.g., word[0] gives 'h'.

Lets practice iterating over a string.

Exercise 1: Write a program to count the number of vowels and consonants in a given string.

Instructions:

  • Take a string as input from the user.
  • Use a for loop to iterate over each character.
  • Check if the character is a vowel or a consonant using if-else.
  • Ignore spaces
# Enter a string: Python Programming
# Vowels: 4
# Consonants: 13
user_string=input("enter a string:").split()
words="".join(user_string)
vowels=['a','e','e','i','o','u']
# vowels=['aeiou']

vowels_count=0
consonants_count=0
for char in words:
if char in vowels:
vowels_count+=1
else:
consonants_count+=1
print(vowels_count)
print(consonants_count)

Exercise 2: Count Uppercase, Lowercase, Digits, and Special Characters

Instructions:

  • Take a string as input from the user.
  • Use a for loop to iterate through the string.
  • Use if-elif conditions and string methods like .isupper(), .islower(), and .isdigit() to classify characters.
  • Count special characters as any character not covered by the above.
# Enter a string: Hello123!
# Uppercase: 1
# Lowercase: 4
# Digits: 3
# Special Characters: 1

Exercise 3: Remove Vowels from the String

Write a program to remove all vowels from a string and print the result.

Instructions:

  • Take a string as input from the user.
  • Use a for loop to iterate over the string.
  • Skip vowels and construct a new string with the remaining characters.
# Enter a string: Python Programming
# String without vowels: Pythn Prgrmmng

Exercise 4: Toggle Case of Each Character

Write a program to toggle the case of each character in a string (uppercase becomes lowercase and vice versa).

Instructions:

  • Take a string as input from the user.
  • Use a for loop to iterate over the string.
  • Use .islower() and .isupper() to toggle the case for each character.
# Enter a string: Python3
# Toggled string: pYTHON3

Tuple as a Sequence

A tuple is a collection of ordered, immutable elements. Like a list, we can iterate over it, but we cannot modify its elements.

Example:

my_tuple = (1, 2, 3)
for num in my_tuple:
print(num)

Output:

1
2
3

Explanation:

  • The tuple (1, 2, 3) is iterable because it’s a sequence of elements.
  • The loop processes each element (1, 2, 3) one by one.

Why Use Tuples?

  • Tuples are often used for fixed sets of data that don’t need modification, like coordinates (x, y) or RGB color values (255, 0, 0).

We will discuss more about tuples while discussing functions.

Lets practice tupples

Type Check for Tuple

Write a program to check if a given variable is a tuple.

Instructions:

  • Create a variable with any data type (e.g., string, list, tuple, etc.).
  • Use the type() function to check if the variable is a tuple. (hint: The datatype for tupple is: tupple)
  • Print a message based on the result.
my_var = (1, 2, 3)
#if my_var is of datatype tupple output shall be "This is a tuple"
#if my_var is not of datatype tupple output shall be "This is not a tuple."

Exercise 2: Type Check for Tuple elements

Write a program to print the datatype of each element of my_tupple in the exercise below.

Instructions:

  • Create a variable my_tupple = (1, "1", True, 5.6, "hello")
  • Iterate over my_tupple and print the element and datatype of the element
my_tupple = (1, "1", True, 5.6, "hello")

Range

A range is a special sequence used for generating numbers. It is especially useful for creating counters or iterating through a fixed range of numbers.

Example:

for i in range(1, 6):  # Generates numbers from 1 to 5
print(i)

Output:

1
2
3
4
5

Explanation:

  • range(1, 6) generates a sequence of numbers: [1, 2, 3, 4, 5].
  • The for loop processes each number in the range.
  • The range object is iterable but does not actually create the list in memory (it generates numbers on the fly, making it memory-efficient).

Why Use Ranges?

  • Perfect for iterating a fixed number of times or over a sequence of numbers.

The Parameters of range()

The range() function in Python can take 1, 2, or 3 arguments:

1. range(stop)

  • Generates numbers starting from 0 (by default) up to, but not including, the stop value.

Example:

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

Output:

0, 1, 2, 3, 4

2. range(start, stop)

  • Generates numbers starting from the start value up to, but not including, the stop value.

Example:

for i in range(2, 6):
print(i)

Output:

2, 3, 4, 5

3. range(start, stop, step)

  • Generates numbers starting from start, incrementing by step, up to, but not including, the stop value.

Example:

for i in range(0, 100, 10):
print(i)

Output:

0
10
20
30
40
50
60
70
80
90

Meaning of start and stop

  • start (First Argument):

    • The value where the range starts.
    • If omitted, it defaults to 0.
  • stop (Second Argument):

    • The value where the range ends (exclusive).
    • This means the range will include numbers up to, but not including, stop.

Why Are They Called start and stop?

  • These terms are descriptive of their roles in defining the range:
    • start: Tells Python where to begin generating numbers.
    • stop: Tells Python where to stop generating numbers (not included in the result).

Let's practice range as a sequence

Exercise 1: Print Numbers from 1 to 10 and mention whether it is odd or even

Expected output:

1: Odd
2: Even
3: Odd
4: Even
5: Odd
6: Even
7: Odd
8: Even
9: Odd
10: Even

Exercise 2: Sum of Numbers in a Range - Part 1

Write a program to calculate the sum of all numbers from 1 to 50 using range.

Expected output:

Sum of numbers in range 1 to 50: 1275

Exercise 3: Sum of Numbers in a Range - Part 2

Repeat the above exercise, but instead of hardcoding the upper range to 50 prompt user to enter.

range_stop = int(input("Please enter range stop: "))

Exercise 4: Print all odd numbers less than 20 using range.

  • No conditons check allowed

Expected outout:

1
3
5
7
9
11
13
15
17
19

Exercise 5: Print all even numbers less than 20 using range.

  • No conditons check allowed
  • Is 0 an odd number or even number?