Data Types and Operators in Python

Python Looping Exercises

Exercise 1: Print numbers from 1 to 10

# Exercise 1: Print numbers from 1 to 10
for i in range(1, 11):
    print(i)

Explanation: This program uses a for loop to print numbers from 1 to 10. The range function generates numbers from 1 to 10, and the loop iterates over each number, printing it.

Exercise 2: Print even numbers from 1 to 20

# Exercise 2: Print even numbers from 1 to 20
for i in range(2, 21, 2):
    print(i)

Explanation: This program prints even numbers from 1 to 20 using a for loop. The range function is used with a step of 2 to generate even numbers.

Exercise 3: Print odd numbers from 1 to 20

# Exercise 3: Print odd numbers from 1 to 20
for i in range(1, 21, 2):
    print(i)

Explanation: This program prints odd numbers from 1 to 20 using a for loop. The range function is used with a step of 2 to generate odd numbers.

Exercise 4: Print multiplication table for a given number

# Exercise 4: Print multiplication table for a given number
number = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{number} x {i} = {number * i}")

Explanation: This program prints the multiplication table for a number provided by the user. It uses a for loop to multiply the number by values from 1 to 10 and prints the results.

Exercise 5: Sum of first 10 natural numbers

# Exercise 5: Sum of first 10 natural numbers
total = 0
for i in range(1, 11):
    total += i
print(f"Sum of first 10 natural numbers is {total}")

Explanation: This program calculates the sum of the first 10 natural numbers using a for loop. It accumulates the sum in the variable total and prints the result.

Exercise 6: Factorial of a given number

# Exercise 6: Factorial of a given number
number = int(input("Enter a number: "))
factorial = 1
for i in range(1, number + 1):
    factorial *= i
print(f"Factorial of {number} is {factorial}")

Explanation: This program calculates the factorial of a number provided by the user. It uses a for loop to multiply the numbers from 1 to the given number, accumulating the result in factorial.

Exercise 7: Count the number of vowels in a string

# Exercise 7: Count the number of vowels in a string
string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0
for char in string:
    if char in vowels:
        count += 1
print(f"Number of vowels in the string is {count}")

Explanation: This program counts the number of vowels in a string provided by the user. It iterates over each character in the string and checks if it is a vowel, incrementing the count if true.

Exercise 8: Reverse a given string

# Exercise 8: 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.

Exercise 9: Check if a number is prime

# Exercise 9: Check if a number is prime
number = int(input("Enter a number: "))
is_prime = True
if number > 1:
    for i in range(2, number):
        if number % i == 0:
            is_prime = False
            break
if is_prime:
    print(f"{number} is a prime number")
else:
    print(f"{number} is not a prime number")

Explanation: This program checks if a number provided by the user is a prime number. It iterates from 2 to the given number and checks if the number is divisible by any of these values.

Exercise 10: Print Fibonacci sequence up to n terms

# Exercise 10: Print Fibonacci sequence up to n terms
n_terms = int(input("Enter the number of terms: "))
n1, n2 = 0, 1
count = 0
if n_terms <= 0:
    print("Please enter a positive integer")
elif n_terms == 1:
    print(f"Fibonacci sequence up to {n_terms}: {n1}")
else:
    print("Fibonacci sequence:")
    while count < n_terms:
        print(n1)
        nth = n1 + n2
        n1 = n2
        n2 = nth
        count += 1

Explanation: This program prints the Fibonacci sequence up to a specified number of terms provided by the user. It uses a while loop to generate the sequence.

Exercise 11: Sum of digits of a number

# Exercise 11: Sum of digits of a number
number = int(input("Enter a number: "))
sum_of_digits = 0
while number > 0:
    digit = number % 10
    sum_of_digits += digit
    number //= 10
print(f"Sum of digits is {sum_of_digits}")

Explanation: This program calculates the sum of the digits of a number provided by the user. It uses a while loop to extract each digit and accumulate the sum.

Exercise 12: Calculate the power of a number

# Exercise 12: Calculate the power of a number
base = int(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
result = 1
for _ in range(exponent):
    result *= base
print(f"{base} raised to the power of {exponent} is {result}")

Explanation: This program calculates the power of a base number raised to an exponent. It uses a for loop to multiply the base by itself the specified number of times.

Exercise 13: Print a pattern of stars

# Exercise 13: 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.

Exercise 14: Check if a string is a palindrome

# Exercise 14: 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.

Exercise 15: Count the number of words in a string

# Exercise 15: 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.

Key Takeaways

Loops are essential for performing repetitive tasks efficiently. Python offers both for and while loops to handle different looping scenarios. Nested loops are useful for generating patterns and working with multi-dimensional data. Understanding loops and their control structures is fundamental for solving complex problems. Practice with varied examples helps in mastering the concepts of loops and their applications.