Branching and looping techniques are essential for making decisions and controlling program flow in Python. A strong grasp of loops and conditional statements is fundamental for writing efficient, high-performance code.
This article provides 40+ Python loop practice questions that focus entirely on loops (for, while, and nested loops) and control flow statements.
Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.
- All solutions have been fully tested on Python 3.
- Interactive Learning: Use our Online Code Editor to solve these exercises in real time.
Refer to the following tutorials to solve these exercises:
- Control flow statements: Learn how to use
if-elsestatements for conditional decision-making. - for loop: Understand how to iterate over sequences like lists, tuples, or strings.
- range() function: Use
range()within aforloop to repeat actions a specific number of times. - while loop: Learn to execute code blocks repeatedly as long as a specific condition remains
True. - Break and Continue: Master these statements to dynamically alter loop execution.
- Nested loop: Learn how to implement a loop inside another loop for complex data processing.
Let us know if you have any alternative solutions. It will help other developers.
+ Table of Contents (40 Exercises)
Table of contents
- Exercise 1. Print first 10 natural numbers using while loop
- Exercise 2. Display numbers from -10 to -1 using for loop
- Exercise 3. Display a message “Done” after successful execution of for loop
- Exercise 4. Calculate the sum of all numbers from 1 to N
- Exercise 4. Print multiplication table of a given number
- Exercise 6. Calculate the cube of all numbers from 1 to a given number
- Exercise 7. Display numbers from a list using a loop
- Exercise 8. Count occurrences of a specific element in a list
- Exercise 9. Print elements from a list present at odd index positions
- Exercise 10. Print list in reverse order using a loop
- Exercise 11. Reverse a string using a for loop (no slicing)
- Exercise 12. Count vowels and consonants in a sentence
- Exercise 13. Count total number of digits in a number
- Exercise 14. Reverse an integer number
- Exercise 15. Find largest and smallest digit in a number
- Exercise 16. Check if a number is a palindrome
- Exercise 17. Find factorial of a number
- Exercise 18. Collatz Conjecture: Generate a sequence until it reaches 1
- Exercise 19. Armstrong Number Check
- Exercise 20. Print right-angled triangle Number Pattern using a Loop
- Exercise 21. Print the decreasing pattern
- Exercise 22. Print the alternate numbers pattern
- Exercise 23. Print Alphabet pyramid (A, BB, CCC) pattern
- Exercise 24. Hollow square pattern
- Exercise 25. Print pyramid pattern of stars
- Exercise 26. Print full multiplication table (1 to 10)
- Exercise 27. List Cumulative Sum: Each element is the sum of all previous
- Exercise 28. Dictionary Filter: Extract pairs where value exceeds a threshold.
- Exercise 29. Find common elements (Intersection) using loop
- Exercise 30. Remove duplicates without set
- Exercise 31. Even/Odd Segregation: Move evens to front, odds to back
- Exercise 32. List Rotation: Rotate elements left by k positions
- Exercise 33. Word frequency counter
- Exercise 34. Display fibonacci series up to 10 terms
- Exercise 35. Perfect number check
- Exercise 36. Binary to decimal conversion using loop
- Exercise 37. Display all prime numbers within a range
- Exercise 38. Find the sum of the series up to n terms
- Exercise 39. flatten a nested list using loops
- Exercise 40. Nested list search (2D matrix coordinates)
Exercise 1. Print first 10 natural numbers using while loop
Practice Problem: Write a program to print the first 10 natural numbers using a while loop. Each number should be printed on a new line.
Exercise Purpose: This is the fundamental introduction to iteration. It teaches how to set up a loop condition to execute a block of code repeatedly, and manually manage a counter variable to prevent infinite loops.
Help: while loop in Python
Given Input: None (The range is fixed from 1 to 10).
Expected Output:
1
2
3
...
10
Hint
- Initialize a variable
i = 1. - Use a
whileloop with the conditioni <= 10. - Don’t forget to increment
iinside the loop.
Solution
Explanation to Solution:
i = 1: We set the starting point of our sequence.while i <= 10: This creates a boundary. The code inside will keep running as long as this statement remains true.i += 1: This is the “step.” Without this,iwould always be 1, and the loop would never end (an infinite loop).
Exercise 2. Display numbers from -10 to -1 using for loop
Practice Problem: Write a program to display numbers from -10 to -1 using a for loop.
Exercise Purpose: This exercise focuses on Negative Indexing and Ranges. Understanding how Python handles negative numbers in the range() function is crucial for algorithms involving coordinate systems or countdowns.
Given Input: None
Expected Output:
-10
-9
...
-1
Hint
Start the range at -10 and end at 0 (since the stop value is exclusive).
Solution
Explanation to Solution:
range(-10, 0): In Python,range(start, stop)always goes up to, but does not include, thestopvalue. To include -1, we must set the stop value to 0.- Default Step: Even with negative numbers, the default step is
+1. Adding 1 to -10 gives -9, which moves us closer to 0 as intended.
Exercise 3. Display a message “Done” after successful execution of for loop
Practice Problem: Write a program to display a message “Done” after the successful execution of a for loop that iterates from 0 to 4.
Exercise Purpose: This introduces a unique Python feature: the Loop-Else Clause. Unlike if-else, a loop else block only executes if the loop completes all its iterations without being interrupted by a break statement. This is useful for search loops to signal that a target was not found.
Given Input: None
Expected Output:
0
1
2
3
4
Done!
Hint
Place the else: block at the same indentation level as the for keyword itself.
Solution
Explanation to Solution:
- Indentation: Notice the
elseis aligned withfor, notprint. This tells Python it belongs to the loop structure. - The “No Break” Rule: If we had added an
if i == 3: breakinside the loop, the word “Done!” would never appear. Because the loop finishes its full range (0-4), theelseblock is triggered. - Practical Use: You often use this to say “I searched the whole list and didn’t find the item.”
Exercise 4. Calculate the sum of all numbers from 1 to N
Practice Problem: Write a program that accepts a number from the user and calculates the sum of all numbers from 1 up to that number.
Exercise Purpose: This exercise teaches Value Accumulation. It shows how to use a loop to process data and store a running total in a variable, a common task in data processing.
Given Input: Enter number: 10
Expected Output: Sum is: 55
Refer:
Hint
- Create a variable
s = 0before the loop. - Inside the loop, add the current iteration value to
susing the+=operator.
Solution
Explanation to Solution:
int(input(...)): We must convert the user’s string input into an integer to perform math.s = 0: This is our “accumulator.” It starts empty.s += i: In every step, the loop takes the current numberiand adds it to our total. Ifn=3, it does0+1, then1+2, then3+3.
Exercise 4. Print multiplication table of a given number
Practice Problem: Create a program that takes an integer and prints its multiplication table from 1 to 10.
Exercise Purpose: This reinforces the use of loops for generating Mathematical Sequences. It shows how to use the loop index (i) as a multiplier against a fixed constant.
Given Input: 2
Expected Output:
2
4
6
...
20
See: Create Multiplication Table in Python
Hint
- Use a
forloop withrange(1, 11). - Multiply the user’s number by the current loop index in each iteration.
Solution
Explanation to Solution:
range(1, 11): This ensures the loop runs exactly 10 times, starting from 1 and ending at 10.num * i: Sincenumis 2, the loop calculates2*1, then2*2, etc. This demonstrates how a static variable and a dynamic loop index interact.
Exercise 6. Calculate the cube of all numbers from 1 to a given number
Practice Problem: Write a program that takes an integer n and prints the cube of every number from 1 to n in the format Current Number is : 1 and the cube is 1.
Exercise Purpose: This exercise teaches Result Formatting and Power Operations. It shows how to combine text with calculated variables using f-strings or commas and perform exponentiation with the ** operator or pow() function.
Given Input: input_number = 6
Expected Output:
Current Number is : 1 and the cube is 1
Current Number is : 2 and the cube is 8
...
Current Number is : 6 and the cube is 216
Hint
- Use a
forloop withrange(1, input_number + 1). - To calculate a cube, use
i * i * iori ** 3
Solution
Explanation to Solution:
range(1, input_number + 1): This ensures the loop reaches the user’s number exactly.i ** 3: The**operator is Python’s way of saying “to the power of.” It is more readable than writingi * i * ifor larger powers.- f-string (
f"..."): This allows you to embed variables directly inside a string using curly braces{ }, making the output code much cleaner.
Exercise 7. Display numbers from a list using a loop
Practice Problem: Given a list of numbers, iterate through it and print numbers that satisfy these conditions:
- The number must be divisible by five.
- If the number is greater than 150, skip it and move to the next.
- If the number is greater than 500, stop the loop entirely.
Exercise Purpose: This vital Flow Control exercise introduces continue (to skip) and break (to exit), essential for writing efficient code that avoids processing unnecessary data.
Given Input: numbers = [12, 75, 150, 180, 145, 525, 50]
Expected Output:
75
150
145
Refer: break and continue in Python
Hint
- First, use an
ifstatement for the “stop” condition (break) - Then the “skip” condition (continue), and
- Finally, the “divisible by 5” condition.
Solution
Explanation to Solution:
break: When the loop hits525, thebreakcommand kills the loop instantly. The final50in the list is never even checked.continue: When the loop hits180, it triggerscontinue. This tells Python: “Stop what you are doing for this specific number and jump back to the top of the loop for the next one.”item % 5 == 0: The Modulo operator checks the remainder. If the remainder of division by 5 is 0, the number is a multiple of 5.
Exercise 8. Count occurrences of a specific element in a list
Practice Problem: Given a list of numbers, use a loop to count how many times a specific number (e.g., 10) appears.
Exercise Purpose: This introduces Frequency Counting, a staple of data analysis. It shows how to iterate through a collection and use a conditional filter to increment a tally only when a match is found.
Given Input:
list1 = [10, 20, 10, 30, 10, 40, 50]
target = 10Code language: Python (python)
Expected Output: 10 appears 3 times
Hint
- Initialize a
count = 0variable. - Loop through each item in the list and check
if item == target.
Solution
Explanation to Solution:
- Direct Iteration:
for num in list1looks at each value directly, which is more “Pythonic” than using indices. - Conditional Increment: The
count += 1line only fires when theifcondition is met. - Output: We use an f-string to provide a clear summary of our findings.
Exercise 9. Print elements from a list present at odd index positions
Practice Problem: Given a Python list, use a loop to print only the elements that are located at odd index positions (index 1, 3, 5, etc.).
Exercise Purpose: This exercise teaches Index-Based Iteration. It helps you distinguish between an item’s value in a list and its position (index), which is fundamental for data filtering.
Given Input: my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Expected Output: [20 40 60 80 100]
Hint
Use a for loop with range() that starts at 1 and uses a “step” of 2.
Solution
Explanation to Solution:
range(1, len(my_list), 2):
- Start at the second element (odd index).
len(my_list): Go until the end.- Skip one index each time (1 -> 3 -> 5…).
my_list[i]: We use the index i generated by the range to “look up” the specific value in the list.
Exercise 10. Print list in reverse order using a loop
Practice Problem: Given a list, iterate it in reverse order and print each element.
Exercise Purpose: Learning to Traverse Data Backwards is essential for many data structures. This exercise shows how to use the reversed() function or custom range slicing to iterate over a list from the end to the beginning.
Given Input: list1 = [10, 20, 30, 40, 50]
Expected Output: [50, 40, 30, 20, 10]
Hint
- Use the
reversed()function on the list inside aforloop - Or use a
rangethat starts at the last index and moves to 0 with a step of -1.
Solution
Solution 2: Using for loop and the len() function
Explanation to Solution:
reversed(list1): This creates an “iterator” that yields items from the list starting from the right-most side. It is memory-efficient because it doesn’t create a new copy of the list.- Alternative approach: You could also use
range(len(list1) - 1, -1, -1)to access the list via indices.
Exercise 11. Reverse a string using a for loop (no slicing)
Practice Problem: Write a program that takes a string and reverses it using a for loop. While Python’s [::-1] shortcut is famous, reversing a string manually is a classic way to understand how sequences are constructed.
Exercise Purpose: Learn how accumulation logic works. In Python, strings are “immutable,” which means you cannot change them directly. Here, you will practice building a new string by adding characters to the front. This is a key idea for algorithms that build results step by step.
Given Input: "Python"
Expected Output:
Original: Python
Reversed: nohtyP
Hint
- Create an empty string
reversed_str = "". - When you loop through the original string, add the current character to the front of your new string (
char + reversed_str) instead of the back.
Solution
Explanation to Solution:
char + reversed_str: This is the “flip” mechanism. Ifreversed_stris already “yP” and the next character is “t”, the operationt + yPresults in “tyP”.- Immutability: Every time you perform this addition, Python creates a brand-new string in memory. This exercise highlights the cost of string operations in loops compared to lists.
Exercise 12. Count vowels and consonants in a sentence
Practice Problem: Write a program that counts the total number of vowels and consonants in a given sentence, ignoring spaces and special characters.
Exercise Purpose: In this exercise, you will practice membership testing and data filtering. You will use the in operator to check if a value is in a collection, and try string methods like .isalpha() to quickly clean your data.
Given Input: "Loops are Fun!"
Expected Output:
Vowels: 5
Consonants: 7
Hint
- Define a string containing all vowels (
"aeiou"). - Convert the input to lowercase so you don’t have to check for capital letters separately.
- Use
if char.isalpha():to ensure you don’t count the exclamation mark or spaces as consonants.
Solution
Explanation to Solution:
char.lower(): Normalizing the input simplifies your logic. One check handles both ‘A’ and ‘a’.if char in vowels: This is a highly efficient Pythonic way to perform multiple “OR” checks (e.g.,char == 'a' or char == 'e'...).- Nested Conditionals: The outer
iffilters out noise (spaces), while the innerif-elsecategorizes the remaining useful data.
Exercise 13. Count total number of digits in a number
Practice Problem: Write a program to count the total number of digits in a given integer using a while loop.
Exercise Purpose: This exercise introduces Arithmetic Reduction. Instead of treating the number as a string, you learn to peel off digits mathematically using floor division (//). This logic is common in algorithms involving digit manipulation, such as reversing numbers or checking for palindromes.
Given Input: 75869
Expected Output: Total digits are: 5
Hint
- Use a while loop that continues as long as the number is not zero.
- In each iteration, divide the number by 10 (to remove the last digit) and increment a counter.
Solution
Explanation to Solution:
- num // 10: This is floor division. It divides the number by 10 and discards the remainder. For example, 75869 // 10 becomes 7586.
- while num != 0: The loop stops once there are no more digits left to “peel off.”
- Counter Logic: Every time the loop runs, it represents one digit processed, so we increment the count.
Exercise 14. Reverse an integer number
Practice Problem: Write a program to reverse a given integer number (e.g., 76542 should become 24567).
Exercise Purpose: While you could convert the number to a string and slice it, doing it mathematically is more efficient and teaches you to use Modulo (%) and Floor Division (//) together to manipulate digits.
Given Input: 76542
Expected Output: 24567
See: Python Programs to Reverse an Integer Number
Hint
- Use
% 10to grab the last digit of the number. - Use
// 10to remove the last digit. - Build the reversed number by multiplying the current reverse by 10 and adding the new digit.
Solution
Explanation to Solution:
num % 10: Grabs the “remainder” of dividing by 10, which is always the last digit (e.g., 76542 -> 2).reverse_number * 10: This “makes room” for the new digit by shifting the existing digits one decimal place to the left.num // 10: Shaves the number down (76542 -> 7654) so the loop can process the next digit.
Exercise 15. Find largest and smallest digit in a number
Practice Problem: Write a program to find the largest and smallest digit within a given integer (e.g., in 75869, the largest is 9 and the smallest is 5).
Exercise Purpose: This combines Digit Extraction (from Exercise 14) with Min/Max Comparison. It’s a foundational logic for finding “extremes” in a dataset. You learn how to initialize comparison variables and update them dynamically as you scan through data.
Given Input: num = 75869
Expected Output:
Largest digit: 9
Smallest digit: 5
Hint
- Initialize
largest = 0andsmallest = 9. - Use a
whileloop with% 10to get each digit. - Compare each digit to your current
largestandsmallest, updating them if a new extreme is found.
Solution
Explanation to Solution:
- Initialization: We start
largestat the lowest possible digit (0) andsmallestat the highest (9). This ensures that the very first digit we check updates both variables. if digit > largest: This is a “king of the hill” logic. If the new digit is higher than the current king, it takes the throne.num // 10: We discard the last digit and move to the next until the number is exhausted.
Exercise 16. Check if a number is a palindrome
Practice Problem: Write a program to check if a given number is a palindrome. A palindrome number is a number that remains the same when its digits are reversed (e.g., 121, 343).
Exercise Purpose: This exercise combines Mathematical Reversal with Conditional Comparison. It teaches storing an original value before modifying it in a loop so you can perform a final validation.
Given Input: number = 121
Expected Output: Yes
Hint
- Reverse the number (as shown in Exercise 14).
- Then, use a
if-elsestatement to compare the reversed number with the original input.
Solution
Explanation to Solution:
temp = number: Since our loop reducesnumberto 0, we must save the original value intempto verify if the reversal matches.- Comparison Logic: The
if temp == reverse_numcheck is the “decision point” that classifies the data.
Exercise 17. Find factorial of a number
Practice Problem: Write a program to use a loop to find the factorial of a given number (e.g., 5!). The factorial of N is the product of all integers from 1 to N.
Exercise Purpose: Factorials grow fast. This exercise demonstrates Iterative Multiplication, a core concept used in probability, statistics, and combinatorics.
Given Input: num = 5
Expected Output: 120
Hint
- Initialize a
factorialvariable to 1 (not 0, or your result will always be 0!). - Multiply it by every number in the range from 1 to your target.
Solution
Explanation to Solution:
factorial = 1: This is our starting product.range(1, num + 1): We iterate through 1, 2, 3, 4, 5.factorial * i: The math looks like this:1*2*3*4*5 = 120
Exercise 18. Collatz Conjecture: Generate a sequence until it reaches 1
Practice Problem: The Collatz conjecture states that if you start with any positive integer n, and if n is even, divide it by 2; if n is odd, multiply it by 3 and add 1. Repeat the process. The sequence will always eventually reach 1. Write a program to print this sequence for a given number.
Exercise Purpose: This exercise demonstrates Indeterminate Iteration. Unlike a for loop with a known range, a while loop runs until a specific mathematical condition, reaching 1, is met.
Given Input: n = 6
Expected Output: 6, 3, 10, 5, 16, 8, 4, 2, 1
Hint
- Use
while n != 1:. - Inside, use an
if-elseblock to apply then/2or3n+1rules, updatingneach time.
Solution
Explanation to Solution:
while n != 1: The loop’s duration is unpredictable. For some numbers, this sequence is short; for others, it can be very long.- Floor Division (
//): Essential here because dividing an even number by 2 should keep it as an integer, not a float (e.g.,3instead of3.0).
Exercise 19. Armstrong Number Check
Practice Problem: Write a program to check if a number is an Armstrong number. An Armstrong number (for a 3-digit number) is an integer such that the sum of the cubes of its digits is equal to the number itself (e.g., 153 = 1^3 + 5^3 + 3^3).
Exercise Purpose: This logic-heavy exercise combines Type Conversion, Mathematical Iteration, and Power Operations. It tests your ability to break a complex problem into steps: isolate digits, raise them to a power, and compare the sum.
Given Input: num = 153
Expected Output: Yes
Hint
- Convert the number to a string to easily iterate over each digit.
- Use the length of that string as the power to which you raise each digit.
Solution
Explanation to Solution:
str(num): Turning the number into a string is a clever “cheat” to avoid using modulo math to extract digits.int(digit) ** power: We have to convert the character back into an integer to perform math. The**operator raises it to the required power (3 for 153).- Validation: The final
ifstatement compares the mathematical result against the original input to provide the verdict.
Exercise 20. Print right-angled triangle Number Pattern using a Loop
Practice Problem: Write a program to print a right-angled triangle pattern where each row contains increasing numbers up to the row number.
Exercise Purpose: This exercise introduces Nested Loops. It demonstrates how an “outer” loop can control the rows of a structure, while an “inner” loop handles the specific data printed within each row.
Given Input: None (Pattern height is 5).
Expected Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Refer:
Hint
- Use an outer
forloop to iterate from 1 to 5. - Inside it, use another
forloop that iterates from 1 to the current value of the outer loop index + 1. - In the first iteration of the outer loop, the inner loop will execute one time.
- In the second iteration of the outer loop, the inner loop will execute two times, and so on, until row 5.
- Print the value of
jin each iteration of the inner loop (jis the inner loop iterator variable).
Solution
Explanation to Solution:
range(1, 6): Generates a sequence from 1 to 5. The outer loopirepresents the current row number.range(1, i + 1): The inner loop depends oni. In row 3, it prints 1, 2, and 3.end=' ': By default,print()adds a newline. We change it to a space so the numbers stay on the same horizontal line.print(""): This empty print statement acts as a “Return” key, moving the cursor to a new line for the next row.
Exercise 21. Print the decreasing pattern
Practice Problem: Write a program to use for loop to print the following reverse number pattern:
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
Exercise Purpose: This exercise builds on nested loops and introduces Dynamic Range Boundaries. It shows how to make the inner loop’s starting point depend on the outer loop’s current value to create decreasing structures.
Given Input: n = 5
Expected Output: (As shown in the problem description)
Refer: Print patterns in Python
Hint
- Use an outer loop that counts down from 5 to 1.
- The inner loop should then count down from the current outer loop value down to 1.
- The outer loop controls the number of iterations of the inner loop. For each outer loop iteration, the number of inner loop iterations is reduced by
i, the outer loop’s current number. - In each iteration of the inner loop, print the iterator variable of the inner loop (
j).
Solution
Explanation to Solution:
range(5, 0, -1): The third parameter (-1) is the step. It tells Python to count backwards.range(i, 0, -1): In the first row,iis 5, so it prints5 4 3 2 1. In the second row,iis 4, so it prints4 3 2 1.- Inner vs. Outer Relationship: The outer loop sets the “ceiling” for the inner loop, effectively shortening the row every time it iterates.
Exercise 22. Print the alternate numbers pattern
Practice Problem: Write a program to print a pattern of alternate numbers from 1 to 20 (e.g., 1, 3, 5…).
Exercise Purpose: This exercise emphasises Step Logic in ranges. Being able to skip values efficiently without using unnecessary if statements inside your loop makes your code more “Pythonic” and faster to execute.
Given Input: Range: 1 to 20
Expected Output: 1 3 5 7 9 11 13 15 17 19
Hint
- The
range()function takes three arguments:start,stop, andstep. - To get every other number, set your
stepto 2.
Solution
Explanation to Solution:
step = 2: This tells the loop to add 2 to the current value instead of the default 1.- Efficiency: By using the
stepparameter, the loop only runs 10 times instead of 20, because it never even visits the even numbers. This is a great habit for processing large datasets where you only need a sample.
Exercise 23. Print Alphabet pyramid (A, BB, CCC) pattern
Practice Problem: Write a program to print a triangle pattern where each row consists of the same letter, and the letter changes (increments) with each new row.
Exercise Purpose: This exercise introduces ASCII Value Manipulation. You’ll learn to use the chr() function to convert numbers into characters, so you can generate the alphabet dynamically without hardcoding each letter.
Given Input: rows = 5
Expected Output:
A
B B
C C C
D D D D
E E E E E
Hint
- The ASCII value for ‘A’ is 65.
- Use an outer loop to iterate from 0 to
rows. - In each row, calculate the character using
chr(65 + i)and print iti + 1times.
Solution
Explanation to Solution:
chr(65 + i): Asigoes from 0 to 4, this function produces ‘A’, ‘B’, ‘C’, ‘D’, and ‘E’.- String Multiplication (Alternative): You could also write
print((letter + " ") * (i + 1)), but using a nested loop helps practice the underlying structure of grid patterns
Exercise 24. Hollow square pattern
Practice Problem: Print a 5*5 square of stars where the middle is empty, leaving only the border.
Exercise Purpose: This exercise teaches Boundary Condition Logic. Instead of printing every item in a nested loop, you use if statements to identify edges, such as the first or last rows and columns, which is essential for UI layouts and 2D array processing.
Given Input: size = 5
Expected Output:
* * * * *
* *
* *
* *
* * * * *
Hint
Inside your nested loop, only print a star if the row index is 0 or size-1, OR if the column index is 0 or size-1. Otherwise, print a space.
Solution
Explanation to Solution:
- Logical OR (
orThis allows us to combine four boundary checks into a single decision point. - The “Else” Space: The space in the
elseblock is just as important as the star -it maintains the square’s shape by pushing the right-side border to the correct position.
Exercise 25. Print pyramid pattern of stars
Practice Problem: Write a program to print the following pattern using nested loops:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
Exercise Purpose: Introduce Symmetrical Logic. It combines an increasing and a decreasing pattern. You learn to use two separate loop structures sequentially to create a complex visual shape.
Given Input: rows = 5
Expected Output: (As shown in the problem description)
Refer: Print Patterns In Python
Hint
- Use one loop to print the top half (1 to 5 stars) and
- A second, separate loop to print the bottom half (4 down to 1 stars).
Solution
Explanation to Solution:
- First Loop: Standard right-angled triangle logic, printing 1 to 5 stars.
- Second Loop: The reverse. It starts at
rows - 1(4) and counts down to 0 using the step-1. print("\r"): Similar toprint(), it moves the cursor to the start of a new line for the next row.
Exercise 26. Print full multiplication table (1 to 10)
Practice Problem: Write a program to print the full multiplication table from 1 to 10 in a grid format.
Exercise Purpose: This is the ultimate test for Tabular Data Representation. It forces you to think about how nested loops interact. The outer loop represents the rows (multiplicands), and the inner loop represents the columns (multipliers). It also introduces the use of escape characters like \t (tab) to align text columns perfectly.
Given Input: None (Range 1-10)
Expected Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
...
10 20 30 40 50 60 70 80 90 100
See: Create Multiplication Table in Python
Hint
- Use two
forloops, both ranging from 1 to 11. - Inside the inner loop, print the product of the two loop variables, followed by a tab (
\t). Use an emptyprint()after the inner loop to start a new row.
Solution
Explanation to Solution:
range(1, 11): Both loops iterate 10 times.end="\t": This is the secret to the grid layout. Instead of a newline, it inserts a tab space, keeping the cursor on the same line but neatly spaced.print(): This “resets” the line. Without it, all 100 numbers would be printed in one single, massive row.
Exercise 27. List Cumulative Sum: Each element is the sum of all previous
Practice Problem: Given a list of numbers, create a new list where each element is the sum of all elements from the original list up to that position.
Exercise Purpose: This introduces the Running Total pattern. It is essentially “memory” within a loop, carrying the result of previous iterations into the current one. This logic is used in financial ledgers to calculate a balance after each transaction.
Given Input: [1, 2, 3, 4]
Expected Output:
Cumulative Sum: [1, 3, 6, 10]
Hint
- Initialize an empty list and a variable
current_sum = 0. - In each iteration of the loop, add the current number to
current_sumand thenappendthat sum to your new list.
Solution
Explanation to Solution:
current_sum += num: This variable acts as the “accumulator.” It grows with every step of the loop.list.append(): By appending inside the loop, we capture a “snapshot” of the total at every single stage of the process.
Exercise 28. Dictionary Filter: Extract pairs where value exceeds a threshold.
Practice Problem: Given a dictionary of student scores, create a new dictionary that only includes students who scored above a certain threshold (e.g., 75).
Exercise Purpose: This exercise teaches Dictionary Iteration. Unlike lists, dictionaries have keys and values. You learn to use .items() to unpack both at once and how to conditionally build a new mapping.
Given Input:
scores = {"Alice": 85, "Bob": 70, "Charlie": 95, "David": 60} threshold = 75Code language: Python (python)
Expected Output:
Passing Students: {'Alice': 85, 'Charlie': 95}
Hint
- Use
for name, score in scores.items():. - Inside the loop, check if the score meets the threshold before adding it to your result dictionary.
Solution
Explanation to Solution:
.items(): This turns the dictionary into a list of pairs (tuples), allowing the loop to handle the “Who” (key) and the “How Much” (value) simultaneously.- Filtering: This is a classic “Search and Select” pattern used in data science to prune datasets.
Exercise 29. Find common elements (Intersection) using loop
Practice Problem: Given two lists, find the elements that appear in both. Do not use Python’s built-in set().intersection() method.
Exercise Purpose: This exercise focuses on Cross-Reference Iteration. It demonstrates how to use one collection as a master list and check its members against a secondary “filter” list to find commonalities.
Given Input:
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]Code language: Python (python)
Expected Output: Common elements: [4, 5]
Hint
- Create an empty list
common. - Loop through
list_aand for each item, checkif item in list_b.
Solution
Explanation to Solution:
- The
inOperator: This is a shorthand for a hidden internal loop that scanslist_bfor a match. - Filtering: This pattern is used in everything from “Suggested Friends” on social media to inventory systems checking for overlapping stock.
Exercise 30. Remove duplicates without set
Practice Problem: Write a program to remove all duplicate values from a list using a loop, maintaining the original order of elements.
Exercise Purpose: Although set(list) quickly removes duplicates, it destroys order. This exercise teaches Uniqueness Validation, ensuring each piece of data is processed once while preserving sequence.
Given Input: [1, 2, 2, 3, 4, 4, 4, 5]
Expected Output:
Unique List: [1, 2, 3, 4, 5]
Hint
- Create a new list called
unique_list. - As you iterate through the original list, check if the item is already in
unique_list. If not, add it.
Solution
Explanation to Solution:
not in: This is the inverse logic of the intersection exercise. It acts as a gatekeeper, only allowing new, unseen data to pass through.- Order Preservation: Because we append elements as we encounter them for the first time, the original relative order is perfectly preserved.
Exercise 31. Even/Odd Segregation: Move evens to front, odds to back
Practice Problem: Given a list of integers, move all even numbers to the beginning of the list and all odd numbers to the end.
Exercise Purpose: This introduces List Reorganization, a simplified version of the partitioning logic used in QuickSort algorithms. You learn to categorize data and reassemble it into a specific structural order.
Given Input: [1, 2, 3, 4, 5, 6]
Expected Output:
Segregated List: [2, 4, 6, 1, 3, 5]
Hint
- Create two empty lists,
evensandodds. - Loop through the main list, sorting numbers into their respective bins, then combine them at the end using
evens + odds.
Solution
Explanation to Solution:
- Modulo Operator (
% 2): The standard way to distinguish even from odd. - List Concatenation (
+): This creates a new list by joining the two sub-lists, ensuring all evens appear before the first odd.
Exercise 32. List Rotation: Rotate elements left by k positions
Practice Problem: Given a list and an integer k, rotate the list to the left by k positions. For example, if k=2, the first two elements move to the end of the list.
Exercise Purpose: This exercise teaches Positional Manipulation. While slicing is common, using a loop helps you understand how data shifts in memory. This is a core concept for circular buffers and scheduling algorithms.
Given Input:
nums = [1, 2, 3, 4, 5]
k = 2Code language: Python (python)
Expected Output: Rotated List: [3, 4, 5, 1, 2]
Hint
- You can perform a single rotation k times.
- In every single rotation, remove the first element (
pop(0)) and add it to the end (append()).
Solution
Explanation to Solution:
pop(0): This method removes the item at the very beginning of the list and “shifts” all other items one spot to the left.append(): This places that “lost” element at the very back, completing the circular movement.for _ in range(k): We use an underscore_as the variable name because we don’t actually need the index; we just need the loop to run exactly k times.
Exercise 33. Word frequency counter
Practice Problem: Write a program to count the frequency of each word in a given string.
Exercise Purpose: This introduces Mapping Logic. You learn to transform a “flat” string into a structured dictionary. This is the starting point for almost all Natural Language Processing (NLP) tasks, such as building a search engine or a tag cloud.
Given Input: text = "apple banana apple orange banana apple"
Expected Output:
{'apple': 3, 'banana': 2, 'orange': 1}
Hint
- Use
.split()to turn the string into a list of words. - Iterate through the list and use an
if-elseblock to check if the word is already a key in your dictionary.
Solution
Explanation to Solution:
text.split(): By default, this splits the string at every space, yielding a list of individual strings.- Dictionary Check:
if word in frequencychecks keys, not values. If the key exists, we increment the count; if not, we create it with an initial value of 1. - Efficiency: This is an
O(n)operation, meaning it scales linearly with the number of words.
Exercise 34. Display fibonacci series up to 10 terms
Practice Problem: Write a program to display the Fibonacci sequence up to 10 terms. The sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones.
Exercise Purpose: This exercise teaches State Management. You keep track of two changing variables (n1 and n2) and update them in sync to crawl forward through the sequence.
Given Input: n_terms = 10
Expected Output: 0 1 1 2 3 5 8 13 21 34
Refer: Generate Fibonacci Series in Python
Hint
- Start with
num1 = 0andnum2 = 1. - In each loop iteration, calculate the
res = num1 + num2, then updatenum1to benum2andnum2to beres.
Solution
Explanation to Solution:
num1, num2 = 0, 1: We initialize the “seed” of the sequence.res = num1 + num2: This creates the new number.- Variable Swapping: This is the engine of the loop. By moving the value of
num2intonum1, and our newresintonum2, we shift our focus one step to the right for the next calculation.
Exercise 35. Perfect number check
Practice Problem: Write a program to check if a number is a “Perfect Number.” A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding the number itself). For example, 6 is perfect because 1 + 2 + 3 = 6.
Exercise Purpose: Emphasizes efficiency in search. While you could check every number up to n, you only need to check up to n/2 to find all divisors, showing how to optimize loop ranges.
Given Input: num = 28
Expected Output:
28 is a Perfect Number (1 + 2 + 4 + 7 + 14 = 28)
Hint
- Initialize
divisor_sum = 0. - Loop from 1 to
(num // 2) + 1. - If
num % i == 0, addito the sum.
Solution
Explanation to Solution:
num // 2: This optimization cuts the number of loop iterations in half. No number greater than 14 can evenly divide 28 (other than 28 itself).num % i == 0: The modulo operator identifies “factors” or divisors.- Final Verdict: The comparison
divisor_sum == numat the end is the logical “anchor” of the entire algorithm.
Exercise 36. Binary to decimal conversion using loop
Practice Problem: Manually convert a binary string (e.g., "1101") into its decimal integer equivalent using a loop. Do not use int(binary, 2).
Exercise Purpose: This exercise teaches Positional Notation and Powers. It helps you visualize how computers store numbers and process strings from right to left or vice versa to apply mathematical weights.
Given Input: binary_str = "1101"
Expected Output: Decimal value: 13
Hint
- Reverse the string first.
- Next, for each character, if it is ‘1’, add 2index to your total.
Solution
Explanation to Solution:
[::-1]: We reverse the string so that the indeximatches the power of 2 (the rightmost digit is 20).2 ** i: This calculates the “weight” of the current position.
Calculation for “1101”:
- ( 1.20 ) + ( 0.21 ) + ( 1.22 ) + ( 1.23 )
- 1 + 0 + 4 + 8 = 13.
Exercise 37. Display all prime numbers within a range
Practice Problem: Write a program to display all prime numbers within a range (e.g., 25 to 50). A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.
Exercise Purpose: This is a classic test of Nested Loop Logic. You iterate through a range of numbers (outer loop) and, for each, run another loop (inner loop) to check if any smaller number divides it evenly. It’s excellent for practicing flag variables or the loop-else construct
Given Input: start = 25, end = 50
Expected Output:
Prime numbers between 25 and 50 are:
29
31
37
41
43
47
See: Python Programs to Find Prime Numbers within a Range
Hint
- For every number in the range, try dividing it by all numbers from 2 up to the square root of that number (or just half of it).
- If any division results in a remainder of 0, it’s not prime.
Solution
Explanation to Solution:
if num > 1: Basic rule of primes; we ignore 0, 1, and negative numbers.range(2, num): The inner loop checks every possible divisor.break: As soon as we find one factor (e.g., 25 \ 5), we stop checking that number-it’s already disqualified.else: Using the “loop-else” here is very clever. Theelseblock only runs if thebreakwas never triggered, meaning the number is prime.
Exercise 38. Find the sum of the series up to n terms
Practice Problem: Write a program to calculate the sum of the series 2 + 22 + 222 + 2222 + …. up to N terms. For example, if n=5, the series is 2 + 22 + 222 + 2222 + 22222.
Exercise Purpose: This advanced Pattern Accumulation exercise requires generating a new number at each step by multiplying the previous number by 10, adding 2, and then adding that result to a running total.
Given Input:
number_of_terms = 5
Expected Output: 24690
Hint
- Start with
start = 2andtotal_sum = 0. - In each step, add
starttototal_sum, then updatestartby calculatingstart * 10 + 2.
Solution
Explanation to Solution:
start = start * 10 + 2: This is the “growth engine.” Ifstartis 22, multiplying by 10 makes it 220, and adding 2 makes it 222.sum_seq += start: We keep a running tally of these growing numbers.- Iteration Logic: The loop runs
ntimes to ensure we process exactly the requested number of terms.
Exercise 39. flatten a nested list using loops
Practice Problem: Given a nested list (a list containing other lists), write a program to “flatten” it into a single list containing all the individual elements.
Exercise Purpose: In data science and web development, data often arrives in “nested” formats (like JSON). This exercise teaches you Dimensionality Reduction. You learn how to “reach inside” one container to pull items out and place them into a new, simpler container.
Given Input: nested_list = [[10, 20], [30, 40], [50, 60]]
Expected Output: [10, 20, 30, 40, 50, 60]
Hint
- Create an empty list called
flattened. - Use an outer
forloop to iterate through the main list, and an innerforloop to iterate through each sub-list, appending every item to yourflattenedlist.
Solution
Explanation to Solution:
for sublist in nested_list: The first loop picks up[10, 20].for item in sublist: The second loop looks inside that sub-list and picks up10, then20..append(item): This adds the individual numbers to our new flat list one by one. By the time the outer loop finishes, all nested items have been “promoted” to the main list.
Exercise 40. Nested list search (2D matrix coordinates)
Practice Problem: Given a 2D list (matrix), find the row and column index of a target value.
Exercise Purpose: This is the foundation of Coordinate Systems. You learn to use nested loops, where the outer loop iterates over rows, and the inner loop iterates over columns. This logic is essential for game development, image processing, and spreadsheet automation.
Given Input:
matrix = [[10, 20], [30, 40], [50, 60]]
target = 30Code language: Python (python)
Expected Output:
Target 30 found at Row: 1, Column: 0
Hint
- Use
enumerate()on the outer loop to get the row index, andenumerate()on the inner loop to get the column index.
Solution
Explanation to Solution:
enumerate(): This is a cleaner way to get both the index and the item at the same time, avoiding the clunkyrange(len())syntax.- Nested Loops: The outer loop picks a row; the inner loop “scans” across that row.
- The
break: Since we only need one occurrence,breakstops the inner loop immediately once the target is found to save time.
