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.

Problem 7 you can use the simple solution
rows = 5
for i in range(rows,0,-1):
for j in range(i,0,-1):
print(j,end=” “)
print()
Exercise 22:
num = -6754102
num_set = set(str(abs(num)))
print(‘Largest digit in’, num, ‘is’, max(num_set))
print(‘Smallest digit in’, num, ‘is’, min(num_set))
For exercise 8. I have another simple solution:
list1 = [10, 20, 30, 40, 50]
for i in list1[::-1]:
print(i)
in EXERCISE 20 you told us to print this pattern
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
and gave us solution :
“def print_alternate_pattern(rows):
num = 1
for i in range(1, rows + 1):
if i % 2 != 0: # Odd row: increasing order
for x in range(num, num + i):
print(x, end=’ ‘)
print() # to diaply next row of number on new line
else: # Even row: decreasing order
for y in range(num + i – 1, num – 1, -1):
print(y, end=’ ‘)
print() # # to diaply next row of number on new line
num += i
# Call the function to print the pattern with a specified number of rows
print_alternate_pattern(5)”
which is printing this :
“1
3 2
4 5 6
10 9 8 7
11 12 13 14 15 ”
which is wrong so here is the corrected code for printing that pattern
just a change of this
“for y in range(num ,num + i)”
def print_alternate_pattern(rows):
num = 1
for i in range(1, rows + 1):
if i % 2 != 0: # Odd row: increasing order
for x in range(num, num + i):
print(x, end=’ ‘)
print() # to diaply next row of number on new line
else: # Even row: decreasing order
for y in range(num ,num + i):
print(y, end=’ ‘)
print() # # to diaply next row of number on new line
num += i
# Call the function to print the pattern with a specified number of rows
print_alternate_pattern(5)
I have a much simpler and shorter solution to problem #21.
def alternate_pattern(rows):
a = 1
b = 0
count = 0
for i in range(1,rows+1):
b = a + count
a = b
count += 1
for j in range(0,i,1):
print(a+j,””,end=””)
print(“”)
alternate_pattern(5)
Have fun coding!
I am sorry, I meant problem #20 not #21
x=1
for i in range(1,6):
for j in range(1,i+1):
print(x,end=” “)
x+=1
print()
mine is even simpler
num=1
for i in range(1,6):
for j in range(i):
print(num,end=’ ‘)
num=num+1
print(“”)
import math
if __name__ == ‘__main__’ :
cnt = 1
for var in range(1,6) :
if var == 1 :
print(cnt)
cnt += 1
else :
for j in range(1,var + 1) :
print(cnt,end =’ ‘)
cnt += 1
print()
bai 20
row = 5
k = 0
for i in range(row):
l = k
k = k + i + 1
for j in range(l,k):
print(j,end=” “)
print()
Expanding the solution of Ex21 with recursive function
#Exercise 21: Flatten a nested list using loops
def flatten(nested):
flat_list = []
for item in nested:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
nested_list = [1, [2, 3], [4, 5, 6], 7, [8, 9,[10,11,[12,13,[14,15]]]]]
print(flatten(nested_list))
You can also use type(i)==list: in the if statement the start the loop
wow those are really helpful for me. understanding core python.
thank you very much i done the whole ex here…
thank you very much…
count = 0
strdd = ”
cc = 1
for i in range(1,10):
if count =5:
print(strdd.replace(‘*’, ”,cc))
cc +=1
count +=1
i done excersice 18 just 1 loop , it not very clean but it use less resource to solve
Also in a single loop for question 18:
for i in range(-5, 6, 1):
print(‘*’ * (5 – abs(i)))
Exercise-7
for i in range(5,0,-1):
for j in range(i,0,-1):
print(j,” “,end=””)
print()
12345
1234
123
12
1
for i in range(5,0,-1):
a=0
for j in range(i):
a=a+1
print(a,end=””)
print()
Exercise-7
for i in range(5,0,-1):
for j in range(i,0,-1):
print(j,” “,end=””)
print()
Last Exercise, my solution:
for i in range(9):
if i < 5:
for j in range(i+1):
print("*", end=" ")
else:
for l in range(9-i):
print("*", end=" ")
print()
collection = [1, 2, 3, 4, 5, 4, 3, 2, 1]
for i in collection:
print(‘* ‘ * i)
Hello Vishal
I wrote a more simple code than in solution.
***********************************************
”’
Write a program to print the following start pattern using the for loop
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
”’
rows=8
for i in range (1,rows+1,1):
print(‘*’*i)
for i in range (rows-1,1,-1):
print(‘*’*i)
********************************************
it is very elegant 🙂
first = 5
second = 3
for i in range(first+1):
for j in range(i):
print(“*”,end = ‘ ‘)
print()
for i in range(second+1,0,-1):
for j in range(i):
print(“*”,end = ‘ ‘)
print()
I think its an simple basic understanding but your code can’t understood bro
it’s 0 in between instead of 1 in second for loop
Hi !
Don’t be angry foot me. Your exercises are very good. They are my favorites.
But for Me in Hungary multiplication table is looks like:
****************************************
#https://pynative.com/python-if-else-and-for-loop-exercise-with-solutions/#h-exercise-1-
#Exercise 4: Print multiplication table of a given number
num =8
for i in range(1, 10, 1):
print(num ,’X’,i, ‘ =’, num*i)
******************************************
Márton from Budapest
Here is my logic for problem 15 without using list slicing:
x = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
#to get the size of list
size=len(x)
#loop to print elements with odd index number
for i in range(0,size):
if i%2!=0:
print(x[i],end=” “)
These were really helpful , thankyou so much
n=5
a=2
i=1
sum=0
while(i<=n):
if i<5:
print(a,end="+")
else:
print(a,end="=")
sum=sum+a
a=a*10+2
i+=1
print(sum)
lol nice job author really good resourses
This is my code:
numbers = [12, 75, 150, 180, 145, 525, 50]
lst = []
for i in numbers:
if i > 150:
continue
elif i > 500:
break
elif i%5 ==0:
print(i)
But the result show:
75
150
145
50
Why does 50 appear?
elif i > 500:
break
shoud be above the first if statement
Break will stop the execution so it wont read the 50 in the list
U have to put a limit value for the if statement i > 150 and i <500
Ex 7 could be as simple as
for x in range(5,0,-1):
for y in range(x):
print(x-y,end=” “)
print(“”)
Found a shorter answer to Example 18:
rows = 5
for x in range(0, rows + 1):
print(x * ‘*’)
for x in range(rows – 1, 0, -1):
print(x * ‘*’)
rows = 5
for x in range(0, rows + 2):
if x == 6:
for x in range(rows-1, 0, -1):
print(x * ‘*’)
print(x * ‘*’)
Exercise 15, this is an alternative way to solve this question
list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for i in range(len(list1)):
if i > 0:
if i % 2 != 0 :
print(list1[i],end = ” “)
for Q14 i dont feel there would be any need to loop through the given number you can always just convert it into a string the reverse it back in to an int, if there is any benefit of using a loop in this case , maybe the time complexity can be affected please do comment below:
num = 76542
newnum = str(num)
newnum = newnum[::-1]
intnum = int(newnum)
print(intnum)
Exercize 9
fun little use of lists
for i in range(10,0,-1):
print(i*-1)
#or
list1 = []
for i in range(1,11):
i = i*-1
list1.append(i)
for i in reversed(list1):
print(i)
question 8
list1 = [10,20,30,40,50]
for i in reversed(list1):
print(i)
print(” “)
#or
for i in list1[::-1]:
print(i)
exercise 2
would recommend using the variables for readability but this is an alternative way to use the outer loop
for i in range(6,1,-1):
for j in range(i-1,0,-1):
print(j, end = “”)
print()
Q5
i feel like the output should include 50 , because all the conditions agree to that
user = int(input(“enter the number you want to calculate the sum for: “))
for i in range(1,11):
print(user*i)
exercize 2
for i in range(1,7):
for j in range(1,i):
print(j , end = ” “)
print()
Another solution for exercise 18
rows = 5
middle_row = rows // 2 + 1
decrement = 0
for i in range(1, rows + 1):
if i > middle_row:
decrement += 2
print(“* ” * (i – decrement))
In my personal opinion, I’m not really a huge fan of nested for loops unless absolutely necessary. In my experience working on independent projects, nested for loops tend to hurt the overall performance of the program, because scaling the operation gets overwhelming for the program to handle. In a small example like this, it doesn’t really matter.
I remember one time I was building a game in pygame, and I had a nested for loop to iterate over all the enemy objects on screen. I started running into issues when the program couldn’t iterate over every enemy fast enough, and it was causing a lot of weird bugs.
My solution has the same benefits of scalability as the provided solution but is able to execute more efficiently being in a single for loop, rather than having to use 2 nested for loops to achieve the same thing.
Exercise 17:
n = 5
x = str(2)
total = 0
for i in range(1, n+1) :
z = x * i
total = int(z) + total
print(total)
exercise 10
for i in range(1, 5+1):
if i == 5:
print(“done!”)
break
print(i)
Exercise 6
x = 75869
print(len(str(x)))
while(Num!=0)
Exercise 6:
for i in range(5, 0, -1):
for j in range(i, 0, -1):
print(j, end = ” “)
print()
excelent very good
my solution to exercize 17
n = 5
sum = 0
num = 0
for i in range(n):
for j in range(i+1):
sum += 2*10**j
num += sum
sum = 0
print(num)
n = 5
sum = 0
num = 0
for i in range(n):
for j in range(i+1):
sum += 2*10**j
num += sum
sum = 0
print(num)
PLISSS in SPANISHH. PLISSS. I NO SABER ENGLISH, TEN KIU
nuh uh
question 4
print(“table”)
for i in range(2,22,2):
print(i)
#1
num =1
while num > 0:
print(num)
num += 1
if num == 11:
break
Exercise 18
for i in range(1,10):
z=0
if i<=5:
while z<i:
print('*',end=" ")
z+=1
print("\n")
else:
while z<10-i:
print('*',end=" ")
z+=1
print("\n")
Thank you so so so much for these exercises. i learned a lot! godbless you
for Exercise 18:
max=int(input(“Enter max number of * in one line: “))
for i in range(-max,max):
n=max-abs(i)
[print(“*”,end=” “) for x in range(n)]
print(“”)
Exercise 6:
x = input(“Enter number : “)
z = str(x)
count = 0
while count < len(z):
count += 1
print(f"total digits are {count}")
Thank you, this is very helpful
hello,I hope you are good.
exersices were so great and useful!
really thank you so much and i wish the best things in world for you
good luck
# mlist = [0,1]
# for i in range(0,8):
# sum = mlist[i]+mlist[i+1]
# mlist.append(sum)
# print(f’the mlist is {mlist}’)
# mlist = [0,1]
# for i in range(0,8):
# sum = mlist[i]+mlist[i+1]
# mlist.append(sum)
# print(mlist)
problem16:
num=int(input("please give the number to find the cubes"))for i in range(num+1):
cube=i**3
print(f"the cube of {i} is:",cube)
q4:
nu=int(input("enter the number tp print the table "))for i in range(1,11):
print(f"{nu} * {i}={i*nu}")
# Exercise 3: Calculate the sum of all numbers from 1 to a given number
Correction
sum =0for i in range(5):
x = int(input("Enter a Number: "))
sum += x
print("\n")
print(sum)
I would just like to thank you for the great job you’ve done here. Very helpful.
for ques 6, i solved like the below prog. I want to know is that correct
def count_n(n):a=list(enumerate(str(n)))
print(len(a))
Exercise 5: Display numbers from a list using loop
Why the solution exclude 50?
I wrote this and the result was: 75 150 145 50
for it in numbers:if it % 5 != 0:
continue
if it > 150:
continue
if it > 500:
break
print(it)
because 525 continued the loop instead of ending it.
# 18
rng = list(range(1, n)) + list(range(n, 0, -1))for i in rng:
print('* ' * i)
Qn# 17:
n=int(input("enter number: "))sum=0
for i in range(1,n+1):
sum=int(start*i)+sum
if i==n:
print(start*i,"=",sum)
else:
print(start*i,"+",end=" ")
Qn 18:
str="*"for i in range(1,5):
print(str*i)
for j in range(5,-1,-1):
print(str*j)
Ex. 8:
list1 = [10, 20, 30, 40, 50]for i in list1[::-1]:
print(i)
USING RECURSION
def fact(num):if num > 1:
return (num*fact(num-1))
return num
num=int(input("Enter the number"))
ans=fact(num)
print(ans)
# pattern 18end = 6
for i in range (0,end+1):
if i=(end/2):
for z in range (end-i,0,-1):
print("*",end=" ")
print()
Print the list in reverse order using a loop
l = [10, 20, 30, 40, 50]n = l[::-1]
for i in n:
print(i)
l = [10, 20, 30, 40, 50]New list=reversed(I)
print( New list)
ex: 5
n = [12, 75, 150, 180, 145, 525, 50]for i in n:
if i % 5 == 0 and i 500:
break
#18 Pattern:(my code)
for i in range(0,6):for j in range(1,i+1):
print("*",end=" ")
print("")
for i in range(0,6):
for j in range(1,5-i):
print("*",end=" ")
print("")
That’s the wrong code it does nothing other than breaking loop
Exercise 14:
Reverse an integer number
The solution not entirely correct if your number ends with 0
Most integer types in virtually every programming language do not show leading zeroes. If you want to reverse it with zeroes, convert to a string first. If you want leading zeroes you need to specify how many places you want to show.
Internally 11120 is stored as 00000000000000000010101101110000, it’s just shown as 11120 for readability.
Question no.15 : Use a loop to display elements from a given list present at odd index positions.
nums = [24,18,6,13,16,7,69]i = 1
while i < len(nums):
print(nums[i])
i = i + 2
Exercise 7:
number = int(input('Number: '))for i in range(number):
for j in range(number - i):
print(number - i - j, end = ' ')
print()
Exercise 18, with user input:
maxnum = int(input("enter the maximum number of stars: "))start_range = maxnum * -1 + 1
for i in range(start_range,maxnum,1):
print ("\n")
num_of_stars = maxnum - abs(i)
for x in range(num_of_stars):
print ("* ", end="")
for the number 2 problem, u really don’t need any nested loop
For i in range(0,6,1):Print(i*"*")
For j in range(6,0,-1):
Print(j*"*")
Exe 18 (my idea)
why my pre tag doesn’t work
******** Q13*********
It can be dome without an else statement
factorial = 1n = int(input("number: "))
for i in range(1 , n+1):
factorial = factorial * i
print(factorial)
Question Number 18:
EXERCISE 15
Exercise 14
I converted the num to str to apply a list reversed function. I think I understood this better
Did 14 like this
I DID LIKE THIS :
num = 76542
string = str(num)
txt = string[::-1]
rnum = int(txt)
print(rnum)
for exercise 18, scalable answer:
Exercise 18
For Exercise 8, Solution 3
For exercise 4 :
Exercis2 my solution:
Exercise 5:
It seems your solution is a mistake.
The break should be a nested loop so that the loop will continue to all the list:
The exercise specifically says to end the loop if the number is greater than 500. Not continue evaluating the remaining numbers. His “expected output” shows this. > 500 ends the loop/script. >150 skips and continues
How come 180 is missing the out of this program?
numbers = [12, 75, 150, 180, 145, 525, 50]# iterate each item of a list
for item in numbers:
if item > 500:
break
elif item > 150:
continue
# check if number is divisible by 5
elif item % 5 == 0:
print(item)
As it says in the instructions, elements greater than 150 should not be printed.
thank you
It’s 👍😊
<3
question number 17. an alternative using nested loops
didn’t know we could do it at the beginning and at the end just once
so did it for every line
here is the “better to look” version
I did it like this
n = 5
sum = 0
num = 0
for i in range(n):
for j in range(i+1):
sum += 2*10**j
num += sum
sum = 0
print(num)
solution for exercise number 15
lol dude i too did in the same way
a more simplified silution for exercise 8
Exercise 2
For Exercise 17
question 14
The range of i must be
star+1Remaining code is good
Excellent job there
to reverse a string
for 18th problem
in q6 why not display 50?
SAME QUE BRO ANY ONE CAN EXPLAIN
you mean Question 5 with the List,
program will break when it iterates over the list and find a number greater than 500 …525 precedes 50. program will terminate at 525.
#for 8th problem
Q18 Alternate and Easy Solution
There are N people in a party numbered 1 to N.
Sruthi has K card with her. Starting with person A,
she gives the cards one by one to the people in the
party in the numbering order. A, A+1,A+2 ….N. 1,2…..A-1.
your task is to output the number of the person who will get the last card.
INPUT 1
3 3 2
OUTPUT 1
1
INPUT2
1 100 1
OUTPUT
1
kindly explain this question with a solution
Exercise 12
Exercise 18
For exercise 17
Exercise 6
Exercise 7 – An alternative using only 2 variables inside the for loops:
Exercise 8:
Exercise 4 for any number
Exercise 2
Q. 18
Q7. Print the following pattern.
# Exercise 18: Print the following pattern
I don’t think this is very efficient but that’s what I came up with haha
Using if is unnecessary here my friend
Q 18 in very simple way:
simpler :
simpler:)
Exercise-9 Answer
Exercise-5-Answer
Exercise 6: – Answer –
Exercise 18: I believe this is easy.
Also works, and I believe it’s faster (
O(n)) because it only loops once, not twice.For clarification: I use a user input here for the number of columns for testing purposes, but you can easily set num to 5 to get exactly the pattern that was asked.
Exercise 15: one more solution
Exercise 14: Reverse a given integer number
Exercise 10: this also works
Exercise 4: Print multiplication table of a given number
But it works only for number 2, but we need a code that works for every number that the user input .
try this code
Another method for Exercise 8
#another solution
ANOTHER METHOD OF SOLVING PYTHON EXERCISE 8
Explanation is very poor!! Need to change it.
Exercise 8:
Exercise 4: Print multiplication table of a given number:
will be perfect.
Exercise 12 Solution:
For exercise 11, you actually only need to check for divisors up to the
sqrt(num). This is because any composite number has a factor less than the square root of itself. Minor improvement in the runtime, but thought I would mention it.Thank you, I didn’t know about that! This will probably be useful at some point. What I did was only check from 2 to the number – 1 (ommiting 1 and the number itself), which compared to the provided solution makes hardly any difference.
for exercise 07:
Another solution for Exercise 8:
For exercise 3, I found that I had to add float, e.g.
or I would get this error message with some ranges “ValueError: invalid literal for int() with base 10: “
FOR EX 7
Another solution for Exercise 18
Another solution for Question no -11
This is beautiful!
Exercise 14
thanks for sharing this solution
We can also achieve the result using this code:
For Exercise 18:
We can also achieve the result using this code:
Output:
How many blocks do you want to add to your vertical pyramid?: 5
#EXercise 18 less steps
This prints the pattern based on the distance (absolute value) from 5. Thus a simple algorithm.
Exercise 17
#modified exercise 17 so that user can enter the no of rows and the starting value of the series
rows = int(input('enter no of rows : ')) original_series = int(input('enter starting value of series : '))#to store the starting value of the series series = 0 total = 0 for i in range(0,rows): series = (series*10)+original_series print(series) total = total + series txt = 'Sum of the first {} rows of the above series is {}' print(txt.format(rows,total))SMOOTH! THANK YOU!
#EXercise 16
for ex 7 cant we use
# question 1
Are you also there on youtube
for example. 6
Can’t you just use
Hello. I am a beginner programmer and your laconic exercises help me a lot. I appreciate your work and thank you .(Georgia.Tbilisi)
Solution to 6:
The answer to the exercise 15
I think it’s much more convenient to answer question NUMBER 5 with a function.
MY SOLUTION:
The solution to exercise 16
Aolution to 8
Question 18. print the following pattern
Question 16
Question 15
Question 15
Question 14: Reverse a given integer numbers
Question 10
Question 10:
Question 6. Given a no, count the total no of digits in the no.
don’t even need to convert to a string. just use
len(num)TypeError: object of type ‘int’ has no len()
Question 5
Question 4. Print multiplication table of a given number
very nice
an easy way of 14th exercise
Output
[76543]
Do you guys even test your code before posting solutions?
question number 8 in loop exercise
Here are my worked solutions. Some are different from the answers given. Please ask if you have any questions.
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
#11
#12
#13
#14
#15
#16
#17
#18
I want solution for this question
write a python program to read the numbers until -1 is encountered.find the average of positive numbers and negative numbers entered by the user
After I read your comment I went straight to the code editor to try and solve it……little did I know that your comment was 2 yrs ago…LOL…But still, I’m posting it so that you or others who tried to solve this problem but failed can refer. Most probably you won’t even see it. Ok bye, thanks!
Hope you understood my solution
thanks!
Question 3
TypeError: ‘int’ object is not callable
question 16
question 15
question 12 using for loop
question 10
question 9
question 8
question 5
question 3
Alternative answer for question 14
Question asked to use a loop.
Alternative solution for question 18:
solution 16:
solution 14:
solution 13 :
Exercise Question 10: Display a message “Done” after successful execution of for loop
print(“Done”)
Q3:
n= int(input(“enter a number”)
result = n*(n+1)//2
print(result)
Do you have class/oop exercises?
Can I just use
print("Done")without the else? What does the else do in the code?In Q10, I forgot to mention it.
So basically the else runs if there is a break in the loop otherwise the else dose not come in to picture
think so,
item+=1is unwanted in the above codeNo,, you can’t every time when it’s count,, it also prints “done”,,
I didn’t use a loop for Question 6, but this works for 0 and negative numbers:
Edited so it will also work with decimals:
Scratch that last one! Needs work!
How’s this for Question 6:
should we have an easier alternative
# the outcome is still 5, btw
without a loop, it’s so easy, but with the loop is kind of difficult
hey! I have done here have a look for
–optimized code–
Q6
Ya it worked and it is very simple compare to loop
In a question 4:
Question 7:
Question 2:
solution for exercise 5
for question no. 4
Question8
You are the best bro.
Question5
Question4
Q8:
# Exercise Question 6: Given a number count the total number of digits in a number
I got a question if someone can help, why do they use triple coordinates, like in exercise 3
for i in range(1, n + 1, 1)I tried it without the extra,1 and the result is the same, I just want to know the purpose of it being there or were I cand find out more about this 🙂
Hey Jakes, Please refer this detailed article on Python range()
The last argument of
range()function is the step. The step is a difference between each number in the result. The default value of the step is 1 if not specified.If you change it to 2 the difference between each number is 2
For example:
This will produce the following output.
I hope it helps you. Let me know if you have any doubts.
got it, thank you :))
the third co ordinate represents the difference of numbers in the range in the given case it is 1 which means that num are 1,2,3…n if it is 2 then 1,3,5…
It is basically used to determine how you want to increment the base value. for example –
The output will be 1 4 7.
Q6 without a loop
Exercise Question 4: Accept n number from user and print its multiplication table
n = int(input('Enter Your num : ')) for i in range(1,11): sum = n*i print(n,'x',i,'=',sum)Exercise Question 2: Print the following pattern
The for in Q10 Dose NOT go with else:
for i in range(5): print(i) else: print("Done!")Here is a Better Solution:
for i in range(5): print(i) print("Done!")list1 = [10, 20, 30, 40, 50] n = len(list1) for i in range(1,n+1): print(list1[n-i])How about
50
40
30
20
10
Question 7:
n = input('Enter any no :') count = 0 for i in n: count += 1 print('Total digits are: ',count)Question5:
list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200] for x in range(len(list1)): if (list1[x] % 5 == 0) and (list1[x] <= 150): print(list1[x]) else: continue# # Exercise Question 1:
# for i in range(6): # for j in range(i): # print(i,end=" ") # print("")# Exercise Question 3:
# n= int(input("enter the number: ")) # total=0 # for i in range(1,n): # total=total+i # total = n+total # print("including n total number is :",total)# # Exercise Question 4:
# # 2*1=2 # # 2*2=4 # # 2*3=6 # # n*i=n*i # n= int(input("enter value :")) # for i in range(1,11): # print(n,"*",i ,"=",n*i)# Exercise Question 5:
# # Exercise Question 6:
# num= int(input("enter number : ")) # count=0 # while(num!=0): # num = num//10 # count+=1 # print(count)# Exercise Question 7:
# number=int(input("enter number: ")) # for i in range(0,number+1): # for j in range(number-i,0,-1): # print(j,end=" ") # print("")# number=5 # for i in range(1,number+1): # i=number-i # for j in range(0,i+1): # j=number-j # print(j,end=" ") # print("")# Exercise Question 8:
# Exercise Question 9:
# Exercise Question 10:
for i in range(5): print(i) print("done")for Question 4:
num = int(input("Enter Number= ")) table = 0 for i in range(1,11): table = (i*num) print(table)Solution for Exercise 4:
num = int(input(“Enter Number= “))
table = 0
for i in range(1,11):
table = (i*num)
print(table)
For Q8
list1 = [10,20,30,40,50] for i in list1[::-1] print(I)Question 6 doesn’t work with 0 and negative numbers. I don’t understand what is
and how does it help to count, if I delete that line, I get an endless loop which is to be expected.
for Q.7
for i in range(5,0,-1): for j in range(i,0,-1): print(j, end=" ") print()for Q.8
list1 = [10, 20, 30, 40, 50] for i in list1[::-1]: print(i)alternative for answer of question 8
list1 = [10, 20, 30, 40, 50] for i in list1[::-1]: print(i)sir, i want to ask that are these python exercises sufficient for project works?
These exercises will help you to improve your understanding and coding ability.
Hey team, so I arrived at this “alternative answer” for question 4:
x = 1 n = int(input("enter the number for multiplication table : ")) while x < 11: print(x*n) x += 1However, I’m having difficulty wrapping my head around “i” within the for statements. When using it for the solutions, is it merely a dynamic variable in between the stated ranges?
Yes, i is an iterator variable, changes its value in each iteration.
Hi Everyone, I’m new to Python and confused of the line
print(i, end=' ')I acknowledge that it’d print the number generated from the same loop in one line but what exactly does it mean?
Hey Trung Nguyen,
The default value of the
endis\nmeaning that after the print statement, it will print a new line. Theendis you want to be printed after the print statement has been executed.For example,
print(i, end=' ')will print all the values ofion the same line. If we replace this withprint(i, end="\n\n")it will write two newlines after each value ofiThanks sir
Thanks Sir!
this is one of the best website and here i got to learn many things. And the practice part including quiz that’s the great work and it’s very helpful for me.
Thanks for making this lovely website i really appreciate your work.
Thank you, Ashish. I really appreciate your kind words and encouragement.
For exercise question 2, here is a short answer:
num = [] for i in range(1,6): num.append(i) print(*num)Hey, Thank you for an alternative solution
Hi
In solution of question 8, “-1” is equivalent with 10? Then why we reduce with -1 in
another way for Exercise Question 8: Reverse the following list using for loop
list1 = [10, 20, 30, 40, 50] for i in list1.__reversed__(): print(i)Thank you, Agus
list1 = [10, 20, 30, 40, 50][::-1]
for i in list1:
print(i)
In question number 2 when input given is beyond 50 it does not generate desired pattern . Can you please explain it
Hey Avinash, It is generating Pattern correctly after giving input bigger than 50. Can you please share your code.
we can use the
reverse()and it much easier!Hi! Your exercises are very helpful. I was wondering if you could add some comments in your codes as they are very helpful for beginners like me. ?
Thanking you.?
Thank you, elite_coder. Sure we will add comments
do the solution of question 10 and the following code make any difference?
for i in range(5): print(i) print("Done!")Thank you in advance.
Hi Ashna, The question was created to demonstrate the use of else clause in for loop. The
elseblock executes only when loop terminates naturallywhat does num//=10 means in exercise 6?
Hi Nifdi, Its Floor division operator and returns the “floor” of the result.
the numbers are divided by 7 without a remainder per 1,000,000
how is the solution of the question
Create a variable List and fill it with the number and number of free lists. Make it use IF ELSE and Looping statements (FOR, While, etc) that call from a List. Print output “number including number x” (x consists of even, odd, and prime).
??
It fetches the quotient.
num //= 10for example
1234//=10, will fetch 123 alone.It is opposite to
num%10which fetches the remainder.VERY COOL