Examples on Loops in Python

In this section, we will explore some solved exercises that demonstrate the use of loops in Python. These examples will help you understand how to implement counting, skip counting, and other simple loop-based tasks.

Exercise 1: Counting from 1 to 10

In this exercise, we will use a for loop to count from 1 to 10 and print each number.

# Counting from 1 to 10 using a for loop
print("Counting from 1 to 10:")
for i in range(1, 11):
    print(i)

        

Explanation: The for loop iterates over a range of numbers from 1 to 10, and the print(i) statement outputs each number to the console.

Sample Output:

c:\demo>python count_from_1_to_10.py
Counting from 1 to 10:
1
2
3
4
5
6
7
8
9
10
c:\demo>

    

Exercise 2: Skip Counting by 2

In this exercise, we will use a for loop to count from 1 to 20, skipping every second number (i.e., counting by 2).

# Skip counting by 2 using a for loop
print("Skip counting by 2 from 1 to 20:")
for i in range(1, 21, 2):
    print(i)

        

Explanation: The range(1, 21, 2) function generates a sequence of numbers from 1 to 20 with a step of 2. The for loop iterates over this sequence, and the print(i) statement outputs each number to the console.

Sample Output:

c:\demo>python skip_count_by_2.py
Skip counting by 2 from 1 to 20:
1
3
5
7
9
11
13
15
17
19
c:\demo>

    

Exercise 3: Sum of First 10 Natural Numbers

In this exercise, we will use a while loop to calculate the sum of the first 10 natural numbers.

# Sum of the first 10 natural numbers using a while loop
sum = 0
i = 1
while i <= 10:
    sum += i
    i += 1
print("Sum of the first 10 natural numbers is:", sum)

        

Explanation: The while loop iterates as long as i is less than or equal to 10. In each iteration, it adds the value of i to sum and increments i by 1. Finally, the print statement outputs the sum.

Sample Output:

c:\demo>python sum_first_10_numbers.py
Sum of the first 10 natural numbers is: 55
c:\demo>

    

Exercise 4: Printing Multiplication Table of a Number

In this exercise, we will use a for loop to print the multiplication table of a number provided by the user.

# Printing multiplication table of a number using a for loop
number = int(input("Enter a number to print its multiplication table: "))
print(f"Multiplication table for {number}:")
for i in range(1, 11):
    print(f"{number} x {i} = {number * i}")

        

Explanation: The for loop iterates over a range of numbers from 1 to 10. In each iteration, it multiplies the user-provided number by the current value of i and prints the result.

Sample Output:

c:\demo>python multiplication_table.py
Enter a number to print its multiplication table: 5
Multiplication table for 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
c:\demo>

    

Exercise 5: Counting Down from 10 to 1

In this exercise, we will use a while loop to count down from 10 to 1 and print each number.

# Counting down from 10 to 1 using a while loop
i = 10
print("Counting down from 10 to 1:")
while i > 0:
    print(i)
    i -= 1

        

Explanation: The while loop iterates as long as i is greater than 0. In each iteration, it prints the value of i and decrements i by 1.

Sample Output:

c:\demo>python countdown.py
Counting down from 10 to 1:
10
9
8
7
6
5
4
3
2
1
c:\demo>

    

Exercise 6: Reverse a Given String

In this exercise, we will reverse a string provided by the user using a loop.

# Exercise 6: Reverse a given string
string = input("Enter a string: ")
reversed_string = ""
for char in string:
    reversed_string = char + reversed_string
print(f"Reversed string is {reversed_string}")

        

Explanation: This program reverses a string provided by the user. It iterates over each character in the string and prepends it to the reversed_string variable.

Sample Output:

c:\demo>python reverse_string.py
Enter a string: Python
Reversed string is nohtyP
c:\demo>

    

Exercise 7: Print a Pattern of Stars

In this exercise, we will print a right-angled triangle pattern of stars using nested loops.

# Exercise 7: Print a pattern of stars
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
    for j in range(i):
        print("*", end="")
    print()

        

Explanation: This program prints a right-angled triangle pattern of stars. It uses nested for loops to print the stars.

Sample Output:

c:\demo>python star_pattern.py
Enter the number of rows: 5
*
**
***
****
*****
c:\demo>

    

Exercise 8: Check if a String is a Palindrome

In this exercise, we will check if a string provided by the user is a palindrome.

# Exercise 8: Check if a string is a palindrome
string = input("Enter a string: ")
reversed_string = string[::-1]
if string == reversed_string:
    print(f"{string} is a palindrome")
else:
    print(f"{string} is not a palindrome")

        

Explanation: This program checks if a string provided by the user is a palindrome. It compares the original string with its reversed version.

Sample Output:

c:\demo>python palindrome_check.py
Enter a string: radar
radar is a palindrome
c:\demo>

    

Exercise 9: Count the Number of Words in a String

In this exercise, we will count the number of words in a string provided by the user.

# Exercise 9: Count the number of words in a string
string = input("Enter a string: ")
words = string.split()
print(f"Number of words in the string is {len(words)}")

        

Explanation: This program counts the number of words in a string provided by the user. It splits the string into words using the split method and counts the number of words.

Sample Output:

c:\demo>python word_count.py
Enter a string: Python is amazing
Number of words in the string is 3
c:\demo>

    

Understanding String Handling in Python

In Python, strings are a sequence of characters, and they can be treated as arrays of characters. This means you can access individual characters using indexing, slice strings to create substrings, and even loop through each character. This ability to handle strings as arrays of characters provides a powerful tool for manipulating text and performing various operations on it.

For example, reversing a string involves iterating through it and appending each character to a new string in reverse order. Similarly, checking for palindromes or counting the number of words in a string leverages the array-like properties of strings in Python.

By understanding and utilizing these properties, you can perform complex text manipulations with ease and write more efficient and readable code.

Key Takeaway

These exercises demonstrate how to use loops and string handling techniques to perform repetitive tasks and manipulate text efficiently in Python. By understanding the different types of loops and practising with simple examples like counting, skip counting, and string operations, you can build a strong foundation for more complex programming tasks.