PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Loops Exercises: 40+ Coding Problems with Solutions

Python Loops Exercises: 40+ Coding Problems with Solutions

Updated on: March 24, 2026 | 327 Comments

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-else statements for conditional decision-making.
  • for loop: Understand how to iterate over sequences like lists, tuples, or strings.
  • range() function: Use range() within a for loop 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.

Also Read:

  • Python Loops Quiz
  • Python Loops Interview Questions

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 while loop with the condition i <= 10.
  • Don’t forget to increment i inside the loop.
Solution
# Initialize the counter
i = 1

# Iterate until i is greater than 10
while i <= 10:
    print(i)
    # Increment the counter to move to the next number
    i += 1Code language: Python (python)

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, i would 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
# Start at -10, stop before 0
for i in range(-10, 0):
    print(i)Code language: Python (python)

Explanation to Solution:

  • range(-10, 0): In Python, range(start, stop) always goes up to, but does not include, the stop value. 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
for i in range(5):
    print(i)
else:
    # This block executes only after the loop finishes naturally
    print("Done!")Code language: Python (python)

Explanation to Solution:

  • Indentation: Notice the else is aligned with for, not print. This tells Python it belongs to the loop structure.
  • The “No Break” Rule: If we had added an if i == 3: break inside the loop, the word “Done!” would never appear. Because the loop finishes its full range (0-4), the else block 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:

  • Accept input from user in Python
  • Calculate sum and average in Python
Hint
  • Create a variable s = 0 before the loop.
  • Inside the loop, add the current iteration value to s using the += operator.
Solution
# Take input from user and convert to integer
n = int(input("Enter number: "))

# Variable to store the sum
s = 0

# Loop from 1 to n (n+1 is used because range is exclusive)
for i in range(1, n + 1):
    s += i

print("Sum is:", s)Code language: Python (python)

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 number i and adds it to our total. If n=3, it does 0+1, then 1+2, then 3+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 for loop with range(1, 11).
  • Multiply the user’s number by the current loop index in each iteration.
Solution
num = 2

# Iterate 10 times
for i in range(1, 11):
    # Calculate product
    product = num * i
    print(product)Code language: Python (python)

Explanation to Solution:

  • range(1, 11): This ensures the loop runs exactly 10 times, starting from 1 and ending at 10.
  • num * i: Since num is 2, the loop calculates 2*1, then 2*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 for loop with range(1, input_number + 1).
  • To calculate a cube, use i * i * i or i ** 3
Solution
input_number = 6

for i in range(1, input_number + 1):
    # Calculate cube and print with formatting
    print(f"Current Number is : {i}  and the cube is {i ** 3}")Code language: Python (python)

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 writing i * i * i for 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:

  1. The number must be divisible by five.
  2. If the number is greater than 150, skip it and move to the next.
  3. 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 if statement for the “stop” condition (break)
  • Then the “skip” condition (continue), and
  • Finally, the “divisible by 5” condition.
Solution
numbers = [12, 75, 150, 180, 145, 525, 50]

for item in numbers:
    # Condition 3: Stop the loop if number > 500
    if item > 500:
        break
    
    # Condition 2: Skip the number if > 150
    if item > 150:
        continue
    
    # Condition 1: Print if divisible by 5
    if item % 5 == 0:
        print(item)Code language: Python (python)

Explanation to Solution:

  • break: When the loop hits 525, the break command kills the loop instantly. The final 50 in the list is never even checked.
  • continue: When the loop hits 180, it triggers continue. 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 = 0 variable.
  • Loop through each item in the list and check if item == target.
Solution
list1 = [10, 20, 10, 30, 10, 40, 50]
target = 10
count = 0

for num in list1:
    if num == target:
        count += 1

print(f"{target} appears {count} times")Code language: Python (python)

Explanation to Solution:

  • Direct Iteration: for num in list1 looks at each value directly, which is more “Pythonic” than using indices.
  • Conditional Increment: The count += 1 line only fires when the if condition 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
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# range(start, stop, step)
for i in range(1, len(my_list), 2):
    print(my_list[i], end=" ")Code language: Python (python)

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 a for loop
  • Or use a range that starts at the last index and moves to 0 with a step of -1.
Solution
list1 = [10, 20, 30, 40, 50]

# Use the reversed() function for clean iteration
for item in reversed(list1):
    print(item)Code language: Python (python)

Solution 2: Using for loop and the len() function

list1 = [10, 20, 30, 40, 50]
size = len(list1) - 1
for i in range(size, -1, -1):
    print(list1[i])Code language: Python (python)

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
original_str = "Python"
reversed_str = ""

for char in original_str:
    # Prepending: Put the new character before the existing ones
    reversed_str = char + reversed_str

print(f"Original: {original_str}")
print(f"Reversed: {reversed_str}")Code language: Python (python)

Explanation to Solution:

  • char + reversed_str: This is the “flip” mechanism. If reversed_str is already “yP” and the next character is “t”, the operation t + yP results 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
sentence = "Loops are Fun!"
vowels = "aeiou"
v_count = 0
c_count = 0

for char in sentence.lower():
    if char.isalpha():  # Only process letters
        if char in vowels:
            v_count += 1
        else:
            c_count += 1

print(f"Vowels: {v_count}")
print(f"Consonants: {c_count}")Code language: Python (python)

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 if filters out noise (spaces), while the inner if-else categorizes 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
num = 75869
count = 0

# Keep dividing by 10 until the number reaches 0
while num != 0:
    # Floor division to remove the last digit
    num = num // 10
    # Increment the counter
    count = count + 1

print("Total digits are:", count)Code language: Python (python)

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 % 10 to grab the last digit of the number.
  • Use // 10 to remove the last digit.
  • Build the reversed number by multiplying the current reverse by 10 and adding the new digit.
Solution
num = 76542
reverse_number = 0

while num > 0:
    # Get the last digit
    digit = num % 10
    # Add it to the reverse (shifting existing digits left)
    reverse_number = (reverse_number * 10) + digit
    # Remove the last digit from the original number
    num = num // 10

print(reverse_number)Code language: Python (python)

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 = 0 and smallest = 9.
  • Use a while loop with % 10 to get each digit.
  • Compare each digit to your current largest and smallest, updating them if a new extreme is found.
Solution
num = 75869
# Initialize with opposite extremes
largest = 0
smallest = 9

while num > 0:
    digit = num % 10
    
    # Check for new largest
    if digit > largest:
        largest = digit
    # Check for new smallest
    if digit < smallest:
        smallest = digit
        
    num = num // 10

print("Largest digit:", largest)
print("Smallest digit:", smallest)Code language: Python (python)

Explanation to Solution:

  • Initialization: We start largest at the lowest possible digit (0) and smallest at 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-else statement to compare the reversed number with the original input.
Solution
number = 121
# Store original to compare later
temp = number
reverse_num = 0

while number > 0:
    digit = number % 10
    reverse_num = (reverse_num * 10) + digit
    number = number // 10

if temp == reverse_num:
    print("Yes. Given number is palindrome number")
else:
    print("No. Given number is not palindrome")Code language: Python (python)

Explanation to Solution:

  • temp = number: Since our loop reduces number to 0, we must save the original value in temp to verify if the reversal matches.
  • Comparison Logic: The if temp == reverse_num check 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 factorial variable 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
num = 5
factorial = 1

if num < 0:
    print("Factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1, num + 1):
        factorial = factorial * i
    print(f"The factorial of {num} is {factorial}")Code language: Python (python)

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-else block to apply the n/2 or 3n+1 rules, updating n each time.
Solution
n = 6
print(n, end="")

while n != 1:
    if n % 2 == 0:
        n = n // 2
    else:
        n = (3 * n) + 1
    print(f", {n}", end="")Code language: Python (python)

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., 3 instead of 3.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
num = 153
num_str = str(num)
power = len(num_str)
total = 0

for digit in num_str:
    total += int(digit) ** power

if total == num:
    print(f"{num} is an Armstrong number")
else:
    print(f"{num} is not an Armstrong number")Code language: Python (python)

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 if statement 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:

  • Print Patterns In Python
  • Nested loops in Python
Hint
  • Use an outer for loop to iterate from 1 to 5.
  • Inside it, use another for loop 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 j in each iteration of the inner loop (j is the inner loop iterator variable).
Solution
print("Number Pattern:")

# Outer loop for the number of rows
for i in range(1, 6):
    # Inner loop to print numbers in each row
    for j in range(1, i + 1):
        print(j, end=' ')
    # Move to the next line after each row is printed
    print("")Code language: Python (python)

Explanation to Solution:

  • range(1, 6): Generates a sequence from 1 to 5. The outer loop i represents the current row number.
  • range(1, i + 1): The inner loop depends on i. 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
n = 5
# Outer loop for number of rows (5 down to 1)
for i in range(n, 0, -1):
    # Inner loop for printing numbers in each row
    for j in range(i, 0, -1):
        print(j, end=' ')
    # New line after each row
    print("")Code language: Python (python)

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, i is 5, so it prints 5 4 3 2 1. In the second row, i is 4, so it prints 4 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, and step.
  • To get every other number, set your step to 2.
Solution
# Start at 1, go up to (but not including) 21, skip by 2
for i in range(1, 21, 2):
    print(i, end=" ")Code language: Python (python)

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 step parameter, 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 it i + 1 times.
Solution
rows = 5
ascii_value = 65 # Starting with 'A'

for i in range(rows):
    # Calculate current letter
    letter = chr(ascii_value + i)
    # Print the letter (i + 1) times
    for j in range(i + 1):
        print(letter, end=" ")
    print()Code language: Python (python)

Explanation to Solution:

  • chr(65 + i): As i goes 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
n = 5
for i in range(n):
    for j in range(n):
        # Check if we are on the border
        if i == 0 or i == n - 1 or j == 0 or j == n - 1:
            print("*", end=" ")
        else:
            print(" ", end=" ")
    print()Code language: Python (python)

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 else block 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
rows = 5

# Upper part of the pattern
for i in range(0, rows):
    for j in range(0, i + 1):
        print("*", end=' ')
    print("\r")

# Lower part of the pattern
for i in range(rows - 1, 0, -1):
    for j in range(0, i):
        print("*", end=' ')
    print("\r")Code language: Python (python)

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 to print(), 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 for loops, 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 empty print() after the inner loop to start a new row.
Solution
# Outer loop for rows
for i in range(1, 11):
    # Inner loop for columns
    for j in range(1, 11):
        # Print product followed by a tab for alignment
        print(i * j, end="\t")
    # Move to the next line after finishing a row
    print()Code language: Python (python)

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_sum and then append that sum to your new list.
Solution
numbers = [1, 2, 3, 4]
cumulative_list = []
current_sum = 0

for num in numbers:
    current_sum += num
    cumulative_list.append(current_sum)

print(f"Cumulative Sum: {cumulative_list}")Code language: Python (python)

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
scores = {"Alice": 85, "Bob": 70, "Charlie": 95, "David": 60}
passing_students = {}
threshold = 75

for name, score in scores.items():
    if score >= threshold:
        passing_students[name] = score

print(f"Passing Students: {passing_students}")Code language: Python (python)

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_a and for each item, check if item in list_b.
Solution
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]
common = []

for item in list_a:
    if item in list_b:
        common.append(item)

print("Common elements:", common)Code language: Python (python)

Explanation to Solution:

  • The in Operator: This is a shorthand for a hidden internal loop that scans list_b for 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
original = [1, 2, 2, 3, 4, 4, 4, 5]
unique_list = []

for num in original:
    if num not in unique_list:
        unique_list.append(num)

print("Unique List:", unique_list)Code language: Python (python)

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, evens and odds.
  • Loop through the main list, sorting numbers into their respective bins, then combine them at the end using evens + odds.
Solution
numbers = [1, 2, 3, 4, 5, 6]
evens = []
odds = []

for n in numbers:
    if n % 2 == 0:
        evens.append(n)
    else:
        odds.append(n)

# Merging lists
result = evens + odds
print("Segregated List:", result)Code language: Python (python)

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
nums = [1, 2, 3, 4, 5]
k = 2

# Perform the rotation k times
for _ in range(k):
    # Remove the first element
    first_element = nums.pop(0)
    # Move it to the end
    nums.append(first_element)

print("Rotated List:", nums)Code language: Python (python)

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-else block to check if the word is already a key in your dictionary.
Solution
text = "apple banana apple orange banana apple"
words = text.split()
frequency = {}

for word in words:
    if word in frequency:
        frequency[word] += 1
    else:
        # First time seeing this word
        frequency[word] = 1

print(frequency)Code language: Python (python)

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 frequency checks 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 = 0 and num2 = 1.
  • In each loop iteration, calculate the res = num1 + num2, then update num1 to be num2 and num2 to be res.
Solution
# First two terms
num1, num2 = 0, 1

print("Fibonacci sequence:")
for i in range(10):
    print(num1, end="  ")
    # Calculate next term
    res = num1 + num2
    # Update values for next iteration
    num1 = num2
    num2 = resCode language: Python (python)

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 num2 into num1, and our new res into num2, 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, add i to the sum.
Solution
num = 28
divisor_sum = 0

# A divisor cannot be greater than half the number
for i in range(1, (num // 2) + 1):
    if num % i == 0:
        divisor_sum += i

if divisor_sum == num:
    print(f"{num} is a Perfect Number")
else:
    print(f"{num} is not a Perfect Number")Code language: Python (python)

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 == num at 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
binary_str = "1101"
decimal_val = 0

# Reverse to handle indices as powers (0, 1, 2...)
reversed_binary = binary_str[::-1]

for i in range(len(reversed_binary)):
    if reversed_binary[i] == '1':
        decimal_val += 2 ** i

print("Decimal value:", decimal_val)Code language: Python (python)

Explanation to Solution:

  • [::-1]: We reverse the string so that the index i matches 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
start = 25
end = 50

print(f"Prime numbers between {start} and {end} are:")

for num in range(start, end + 1):
    # Prime numbers are greater than 1
    if num > 1:
        for i in range(2, num):
            if (num % i) == 0:
                # Found a factor, not prime
                break
        else:
            # Loop finished without finding a factor
            print(num)Code language: Python (python)

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. The else block only runs if the break was 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 = 2 and total_sum = 0.
  • In each step, add start to total_sum, then update start by calculating start * 10 + 2.
Solution
n = 5
start = 2
sum_seq = 0

for i in range(0, n):
    # Add current term to the total sum
    sum_seq += start
    # Generate the next term (e.g., 2 -> 22 -> 222)
    start = start * 10 + 2

print(sum_seq)Code language: Python (python)

Explanation to Solution:

  • start = start * 10 + 2: This is the “growth engine.” If start is 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 n times 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 for loop to iterate through the main list, and an inner for loop to iterate through each sub-list, appending every item to your flattened list.
Solution
nested_list = [[10, 20], [30, 40], [50, 60]]
flattened = []

# Iterate through each sub-list
for sublist in nested_list:
    # Iterate through each item in the current sub-list
    for item in sublist:
        flattened.append(item)

print("Flattened List:", flattened)Code language: Python (python)

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 up 10, then 20.
  • .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, and enumerate() on the inner loop to get the column index.
Solution
matrix = [
    [10, 20],
    [30, 40],
    [50, 60]
]
target = 30

for r_idx, row in enumerate(matrix):
    for c_idx, val in enumerate(row):
        if val == target:
            print(f"Target {target} found at Row: {r_idx}, Column: {c_idx}")
            break # Found it!Code language: Python (python)

Explanation to Solution:

  • enumerate(): This is a cleaner way to get both the index and the item at the same time, avoiding the clunky range(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, break stops the inner loop immediately once the target is found to save time.

Filed Under: Python, Python Basics, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Solairaj S says

    November 25, 2025 at 12:26 pm

    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()

    Reply
  2. Ufok says

    November 1, 2025 at 3:01 am

    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))

    Reply
  3. Luis says

    August 19, 2025 at 10:45 pm

    For exercise 8. I have another simple solution:
    list1 = [10, 20, 30, 40, 50]
    for i in list1[::-1]:
    print(i)

    Reply
  4. Aditya Shrivastav says

    July 17, 2025 at 1:34 pm

    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)

    Reply
    • Ali says

      August 1, 2025 at 7:20 pm

      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!

      Reply
      • Ali says

        August 1, 2025 at 7:28 pm

        I am sorry, I meant problem #20 not #21

        Reply
        • jatin mulani says

          February 5, 2026 at 1:29 am

          x=1
          for i in range(1,6):
          for j in range(1,i+1):
          print(x,end=” “)
          x+=1
          print()

          Reply
      • dawr says

        October 20, 2025 at 6:22 am

        mine is even simpler

        num=1
        for i in range(1,6):
        for j in range(i):
        print(num,end=’ ‘)
        num=num+1
        print(“”)

        Reply
    • hoang says

      January 2, 2026 at 1:12 am

      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

      Reply
    • Mohammed Ahmed ALi says

      April 13, 2026 at 2:47 pm

      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()

      Reply
  5. harry says

    July 10, 2025 at 12:49 pm

    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))

    Reply
    • Naushad says

      August 22, 2025 at 6:52 pm

      You can also use type(i)==list: in the if statement the start the loop

      Reply
  6. Abdul says

    April 10, 2025 at 4:54 pm

    wow those are really helpful for me. understanding core python.
    thank you very much i done the whole ex here…
    thank you very much…

    Reply
  7. Dukduk2311 says

    February 4, 2025 at 10:42 am

    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

    Reply
    • Timi says

      March 15, 2025 at 5:03 am

      Also in a single loop for question 18:

      for i in range(-5, 6, 1):
      print(‘*’ * (5 – abs(i)))

      Reply
  8. Okbazghi says

    January 26, 2025 at 2:35 am

    Exercise-7
    for i in range(5,0,-1):
    for j in range(i,0,-1):
    print(j,” “,end=””)
    print()

    Reply
    • aryan says

      January 30, 2025 at 3:11 pm

      12345
      1234
      123
      12
      1

      Reply
      • pooja says

        June 8, 2025 at 11:51 pm

        for i in range(5,0,-1):
        a=0
        for j in range(i):
        a=a+1
        print(a,end=””)
        print()

        Reply
  9. Okbazghi says

    January 26, 2025 at 2:30 am

    Exercise-7
    for i in range(5,0,-1):
    for j in range(i,0,-1):
    print(j,” “,end=””)
    print()

    Reply
  10. jay says

    December 23, 2024 at 8:48 pm

    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()

    Reply
  11. Devansh says

    December 22, 2024 at 12:33 am

    collection = [1, 2, 3, 4, 5, 4, 3, 2, 1]
    for i in collection:
    print(‘* ‘ * i)

    Reply
  12. Márton says

    November 26, 2024 at 11:13 pm

    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 🙂

    Reply
    • Ananthaprabhu says

      September 18, 2025 at 3:11 am

      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

      Reply
    • Rakesh Raushan says

      October 17, 2025 at 1:55 pm

      it’s 0 in between instead of 1 in second for loop

      Reply
  13. Márton / says

    November 26, 2024 at 1:43 am

    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

    Reply
  14. Aznair Manzoor says

    October 25, 2024 at 2:26 pm

    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=” “)

    Reply
  15. janki says

    September 16, 2024 at 12:11 am

    These were really helpful , thankyou so much

    Reply
  16. Muddasar Sd says

    September 12, 2024 at 8:29 pm

    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)

    Reply
  17. Bobby Wang says

    June 28, 2024 at 4:53 pm

    lol nice job author really good resourses

    Reply
  18. Sky Runner says

    June 22, 2024 at 8:13 pm

    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?

    Reply
    • deeek says

      June 28, 2024 at 4:51 pm

      elif i > 500:
      break

      shoud be above the first if statement

      Reply
      • Gayu says

        August 13, 2024 at 11:45 pm

        Break will stop the execution so it wont read the 50 in the list

        Reply
        • Al says

          September 11, 2024 at 10:47 pm

          U have to put a limit value for the if statement i > 150 and i <500

          Reply
  19. Babar Azam PK says

    June 12, 2024 at 8:17 am

    Ex 7 could be as simple as

    for x in range(5,0,-1):
    for y in range(x):
    print(x-y,end=” “)
    print(“”)

    Reply
  20. Alex says

    March 12, 2024 at 2:37 am

    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 * ‘*’)

    Reply
    • Turab anwar says

      August 28, 2024 at 10:37 am

      rows = 5
      for x in range(0, rows + 2):
      if x == 6:
      for x in range(rows-1, 0, -1):

      print(x * ‘*’)

      print(x * ‘*’)

      Reply
  21. Phindulo Ratshilumela says

    December 22, 2023 at 8:07 pm

    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 = ” “)

    Reply
  22. Phindulo Ratshilumela says

    December 22, 2023 at 6:57 pm

    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)

    Reply
  23. Phindulo Ratshilumela says

    December 16, 2023 at 2:23 pm

    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)

    Reply
  24. Phindulo Ratshilumela says

    December 16, 2023 at 2:17 pm

    question 8

    list1 = [10,20,30,40,50]
    for i in reversed(list1):
    print(i)
    print(” “)
    #or
    for i in list1[::-1]:
    print(i)

    Reply
  25. Phindulo Ratshilumela says

    December 16, 2023 at 1:39 pm

    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()

    Reply
  26. Phindulo Ratshilumela says

    December 16, 2023 at 11:58 am

    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)

    Reply
  27. Phindulo Ratshilumela says

    December 16, 2023 at 11:24 am

    exercize 2

    for i in range(1,7):
    for j in range(1,i):
    print(j , end = ” “)
    print()

    Reply
  28. David says

    December 3, 2023 at 6:52 am

    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.

    Reply
  29. Karol says

    December 2, 2023 at 11:35 pm

    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)

    Reply
  30. panos says

    November 4, 2023 at 12:40 pm

    exercise 10

    for i in range(1, 5+1):
    if i == 5:
    print(“done!”)
    break
    print(i)

    Reply
  31. Danilo says

    October 11, 2023 at 11:22 am

    Exercise 6

    x = 75869
    print(len(str(x)))

    Reply
    • Bashaar Tariq says

      November 14, 2023 at 4:53 am

      while(Num!=0)

      Reply
  32. Danilo says

    October 11, 2023 at 11:19 am

    Exercise 6:

    for i in range(5, 0, -1):
    for j in range(i, 0, -1):
    print(j, end = ” “)
    print()

    Reply
    • andresito says

      October 26, 2023 at 9:30 pm

      excelent very good

      Reply
  33. Francesco says

    October 6, 2023 at 12:38 am

    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)

    Reply
  34. Francesco says

    October 6, 2023 at 12:36 am

    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)

    Reply
    • ANDRESITO OTRA VEZ says

      October 26, 2023 at 9:32 pm

      PLISSS in SPANISHH. PLISSS. I NO SABER ENGLISH, TEN KIU

      Reply
      • God.Theholy says

        January 18, 2024 at 4:13 pm

        nuh uh

        Reply
  35. rishit raghuvanshi says

    October 1, 2023 at 11:40 am

    question 4
    print(“table”)
    for i in range(2,22,2):
    print(i)

    Reply
  36. mohamed Talal says

    September 29, 2023 at 4:47 am

    #1
    num =1
    while num > 0:
    print(num)
    num += 1

    if num == 11:
    break

    Reply
  37. Mohammad says

    September 26, 2023 at 5:08 pm

    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")

    Reply
  38. Van Jovan says

    September 20, 2023 at 10:57 am

    Thank you so so so much for these exercises. i learned a lot! godbless you

    Reply
  39. sabbath says

    September 19, 2023 at 4:45 pm

    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(“”)

    Reply
  40. Hameed says

    September 14, 2023 at 2:28 am

    Exercise 6:

    x = input(“Enter number : “)
    z = str(x)
    count = 0

    while count < len(z):
    count += 1

    print(f"total digits are {count}")

    Reply
  41. Chinmay says

    August 26, 2023 at 10:22 pm

    Thank you, this is very helpful

    Reply
  42. mohammadho3ein says

    August 21, 2023 at 10:31 am

    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

    Reply
  43. ravi lakshakar says

    July 30, 2023 at 1:45 pm

    # mlist = [0,1]
    # for i in range(0,8):
    # sum = mlist[i]+mlist[i+1]
    # mlist.append(sum)
    # print(f’the mlist is {mlist}’)

    Reply
  44. ravi lakshakar says

    July 30, 2023 at 1:43 pm

    # mlist = [0,1]
    # for i in range(0,8):
    # sum = mlist[i]+mlist[i+1]
    # mlist.append(sum)
    # print(mlist)

    Reply
  45. divya says

    July 17, 2023 at 5:01 pm

    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)

    Reply
  46. divya says

    July 12, 2023 at 9:57 pm

    q4:

    nu=int(input("enter the number tp print the table "))
    for i in range(1,11):
    print(f"{nu} * {i}={i*nu}")

    Reply
  47. Dhruv says

    June 11, 2023 at 8:47 pm

    # Exercise 3: Calculate the sum of all numbers from 1 to a given number

    Correction
    sum =0

    for i in range(5):
    x = int(input("Enter a Number: "))
    sum += x
    print("\n")
    print(sum)

    Reply
  48. Dinko says

    May 27, 2023 at 1:28 am

    I would just like to thank you for the great job you’ve done here. Very helpful.

    Reply
  49. Rinkey Pal says

    May 4, 2023 at 10:11 am

    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))

    Reply
  50. Santiago says

    March 19, 2023 at 11:45 pm

    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)

    Reply
    • 123 says

      March 20, 2023 at 9:45 am

      because 525 continued the loop instead of ending it.

      Reply
  51. 0xAH says

    March 2, 2023 at 3:40 pm

    # 18

    rng = list(range(1, n)) + list(range(n, 0, -1))
    for i in rng:
    print('* ' * i)

    Reply
  52. asim says

    January 14, 2023 at 10:56 am

    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=" ")

    Reply
  53. asim says

    January 14, 2023 at 10:55 am

    Qn 18:
    str="*"
    for i in range(1,5):
    print(str*i)
    for j in range(5,-1,-1):
    print(str*j)

    Reply
  54. sam bumanlag says

    January 12, 2023 at 10:31 am

    Ex. 8:

    list1 = [10, 20, 30, 40, 50]
    for i in list1[::-1]:
    print(i)

    Reply
  55. sumit says

    December 31, 2022 at 1:58 pm

    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)

    Reply
  56. lol says

    November 27, 2022 at 11:11 pm

    # pattern 18

    end = 6
    for i in range (0,end+1):
    if i=(end/2):
    for z in range (end-i,0,-1):
    print("*",end=" ")
    print()

    Reply
  57. ragnaritachi says

    November 12, 2022 at 7:41 pm

    Print the list in reverse order using a loop

    l = [10, 20, 30, 40, 50]
    n = l[::-1]
    for i in n:
    print(i)

    Reply
    • Sagar says

      May 27, 2023 at 7:33 pm

      l = [10, 20, 30, 40, 50]
      New list=reversed(I)
      print( New list)

      Reply
  58. ragnaritachi says

    November 12, 2022 at 7:20 pm

    ex: 5

    n = [12, 75, 150, 180, 145, 525, 50]
    for i in n:
    if i % 5 == 0 and i 500:
    break

    Reply
    • pavan c says

      December 20, 2022 at 3:38 pm

      #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("")

      Reply
    • Mayur says

      June 20, 2023 at 8:23 am

      That’s the wrong code it does nothing other than breaking loop

      Reply
  59. Árvai Gábor says

    November 9, 2022 at 7:00 pm

    Exercise 14:

    Reverse an integer number

    The solution not entirely correct if your number ends with 0

    Reply
    • Anatolii says

      June 14, 2023 at 2:04 am

      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.

      Reply
  60. Savi Sharma says

    November 3, 2022 at 1:21 pm

    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

    Reply
  61. Em says

    November 3, 2022 at 5:03 am

    Exercise 7:
    number = int(input('Number: '))

    for i in range(number):
    for j in range(number - i):
    print(number - i - j, end = ' ')
    print()

    Reply
  62. Chrismander says

    October 27, 2022 at 5:30 am

    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="")

    Reply
  63. lily fullery says

    September 25, 2022 at 10:49 pm

    for the number 2 problem, u really don’t need any nested loop

    a = ""
    for i in range(1,6):
        a = a +" "+str(i)
        print(a)
    Reply
    • Vimal maurya says

      October 31, 2022 at 3:14 am

      For i in range(0,6,1):
      Print(i*"*")
      For j in range(6,0,-1):
      Print(j*"*")

      Reply
  64. Bort (again) says

    September 10, 2022 at 6:53 pm

    Exe 18 (my idea)

    num = 5
    for i in range(1, num + 1):
    for j in range(1, i + 1):
    print(“* “, end=””)
    print()
    
    for i in range(num-1, 0, -1):
    print(“* ” * i)
    Reply
    • Bort says

      September 10, 2022 at 6:53 pm

      why my pre tag doesn’t work

      Reply
    • bdawg says

      September 19, 2022 at 6:21 pm

      factorial = 1
      n = int(input("number: "))
      
      for i in range(1 , n+1):
          factorial = factorial * i
      
      else:
          print(factorial)
      Reply
      • bdawg says

        September 19, 2022 at 6:22 pm

        ******** Q13*********

        Reply
      • Madara says

        March 21, 2023 at 2:16 pm

        It can be dome without an else statement

        factorial = 1
        n = int(input("number: "))

        for i in range(1 , n+1):
        factorial = factorial * i
        print(factorial)

        Reply
  65. Saurav Sharma says

    September 4, 2022 at 10:55 pm

    Question Number 18:

    row = int(input("Please Enter the number of max stars in a row : "))
    for i in range(row):
        for j in range(i+1):
            print("*", end="")
        print("\n")
    else:
        for i in range(row-1, 0, -1):
            for j in range(i):
                print("*", end="")
            print("\n")
    Reply
  66. Ayomide Soniyi says

    September 1, 2022 at 6:30 pm

    EXERCISE 15

    my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    index = len(my_list)
    
    for index, num in enumerate(my_list):
        if index % 2 != 0:
            print(f"Index {index} = {num}")
    Reply
  67. Ayomide Soniyi says

    September 1, 2022 at 2:57 pm

    Exercise 14
    I converted the num to str to apply a list reversed function. I think I understood this better

    num = 76542
    new = list(str(num))
    result = reversed(new)
    final = "".join(list(result))
    final = int(final)
    print(final)
    Reply
    • bdawg says

      September 19, 2022 at 6:46 pm

      Did 14 like this

      number = 76542
      
      print(number)
      
      while number > 0:
          digit = number % 10
          number = number // 10
          print (digit, end = "")
      Reply
    • Surya says

      August 27, 2024 at 11:44 am

      I DID LIKE THIS :

      num = 76542
      string = str(num)
      txt = string[::-1]
      rnum = int(txt)
      print(rnum)

      Reply
  68. Igor says

    August 29, 2022 at 11:40 pm

    for exercise 18, scalable answer:

    class Game():
        
        def __init__(self, num_of_times):
            for i in range(num_of_times):
                self.down()
                self.up()
        
        
        def down(self):
            for i in range(1, 6):
                for j in range(i):
                    print("*", end = " ")
                print("")
                
                
        def up(self):
            iter = 5
            for i in range(1, iter):
                for j in range(iter - i):
                    print("*", end = " ")
                print("")
    
    num_of_times = 2
    case = Game(num_of_times)
    Reply
    • vini1955 says

      October 3, 2022 at 3:19 pm

      Exercise 18

      def arrow(integer):
          temp_string = ""
          for n in range(1, integer + 1):
              temp_string = temp_string + "* "
              print(temp_string)
      
          for n in range(1, integer + 1):
              temp_string = temp_string[:-2]
              print(temp_string)
      
      arrow(5)
      Reply
      • vini1955 says

        October 3, 2022 at 3:22 pm

        def arrow(integer):
            temp_string = ""
            for n in range(1, integer + 1):
                temp_string = temp_string + "* "
                print(temp_string)
        
            for n in range(1, integer + 1):
                temp_string = temp_string[:-2]
                print(temp_string)
        
        arrow(5)
        Reply
  69. Amir says

    August 26, 2022 at 11:08 pm

    For Exercise 8, Solution 3

    list1 = [10, 20, 30, 40, 50]
    for item in list1:
        item2 =list1.index(item)
        print(list1[-1:-item2:-1])
        break
    Reply
  70. Amir says

    August 26, 2022 at 8:59 pm

    For exercise 4 :

    multi=int(input("Enter No: "))
    
    for i in range(1,11):
        for j in range(1):
            print(f"{i} * {multi} = {i*multi}")
    Reply
  71. Milosh says

    August 24, 2022 at 11:06 am

    Exercis2 my solution:

    for i in range(2,7):
        j=i+1
        for j in range(1,i):
            print(j,end=' ')
        
        print (" ")
    Reply
  72. Joe says

    August 21, 2022 at 11:50 pm

    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:

    numbers = [525, 75, 150, 180, 145, 12, 50]
    out = []
    for i in numbers:
        if i > 150:
            continue
        elif i%5==0:
            if i > 500:
                break
            out.append(i)
            print(i)
    Reply
    • Mike says

      September 27, 2022 at 8:31 pm

      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

      Reply
      • Sarpudeen says

        February 26, 2023 at 10:01 pm

        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)

        Reply
        • Suchet says

          September 21, 2023 at 9:27 pm

          As it says in the instructions, elements greater than 150 should not be printed.

          Reply
  73. Jad says

    August 20, 2022 at 6:09 pm

    Exercise 2 simple solution: 
    t=1
    x='1'
    while t<=25:
        print(x)
        t+=1
        x+=' '+str(t)
    t=1#restart variable
    x='1'#restart variable
    print('#'*50)#separator 
    #whit for loop
    max =25
    for i in range(max):
        print(x)
        t+=1
        x+=' '+str(t)
    Reply
    • Piter says

      August 20, 2022 at 6:11 pm

      thank you
      It’s 👍😊
      <3

      Reply
  74. Tribhuvan sai says

    August 3, 2022 at 2:52 pm

    question number 17. an alternative using nested loops

    #idea:
    #write a loop that iterates 5 times
    #now, in order to get the no. of 2's to increase every time we
    #iterate let's write an inner for loop 
    #let's add the number then to get the desired result
    
    #given
    n=5
    #initially, the sum is zero
    sum=0
    #writing a for loop to add 5 times
    for i in range(1,n+1):
        #iterating the inner loop only once
        for j in range(1):
            #multiplying with "i" to get the required number
            req_number = "2"*i
            #adding the number to get the sum
            sum = sum + int(req_number)
    #printing the result
    print(sum)

    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

    Reply
    • Francesco says

      October 6, 2023 at 12:29 am

      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)

      Reply
  75. luke says

    August 2, 2022 at 2:33 pm

    solution for exercise number 15

    my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    for item in range(1,len(my_list)-1+1,2):
        print(my_list[item])
    Reply
  76. luke says

    August 1, 2022 at 3:26 pm

    list1 = [10, 20, 30, 40, 50]
    for item in list1[::-1]:
        print(item)
    Reply
    • Tribhuvan sai says

      August 3, 2022 at 2:14 pm

      lol dude i too did in the same way

      Reply
  77. luke says

    August 1, 2022 at 3:25 pm

    a more simplified silution for exercise 8

    Reply
  78. Ali suleymani says

    July 16, 2022 at 4:37 pm

    Exercise 2

    
    rows=6
    for i in range(2, rows+1):
    	for j in range(1, i):
    		while  j0:	
    			print(j, end=' ')
    			j+=1
    			if j!=i:
    				break
    	print('')		
    Reply
  79. Monir Al-Amassi says

    July 1, 2022 at 8:29 pm

    For Exercise 17

    n = int(input("Please, enter an integer: "))
    # Creating an empty list
    series_str = []
    # Appending the numbers as str
    for i in range(1,n+1):
        series_str.append("2"*i)
    
    # Creating an empty list
    series_int = []
    # Converting the type of numbers from str into int and appending them to
    # the new list series_int
    for k in series_str:
        series_int.append(int(k))
       
    # Output:
    print(f"The series is: {series_int}\nSummation: {sum(series_int)}")
    Reply
  80. Abdou says

    June 23, 2022 at 1:34 pm

    question 14

    num=76542
    for i in range(len(str(num))):
        res=num%10
        num//=10
        print(res,end='')
    Reply
  81. Mr. Keyboard says

    June 16, 2022 at 9:52 pm

    
    star = int(input("Enter the number of star: "))
    for i in range(star):
        for j in range(i):
            print("*", end=" ")
        print("*")
    for i in range(star-2,-1,-1):
        for j in range(i):
            print("*", end=" ")
        print("*")
    Reply
    • Chakradhar says

      June 24, 2022 at 7:17 pm

      The range of i must be star+1
      Remaining code is good
      Excellent job there

      Reply
  82. Mr. Keyboard says

    June 16, 2022 at 9:49 pm

    star = int(input("Enter the number of star: "))
    for i in range(star):
        for j in range(i):
            print("*", end=" ")
        print("*")
    for i in range(star-2,-1,-1):
        for j in range(i):
            print("*", end=" ")
        print("*")
    Reply
    • jay says

      August 9, 2022 at 1:27 am

      for i in range(0,10):
          print(i*"*")
      for j in range(10,0,-1):
          print(j*'*')
      Reply
  83. SWAMI PATEL MS says

    June 16, 2022 at 3:22 pm

    #simple code for the 18 th exercise:
    for i in range(5-1):
        for j in range(i+1):
            print("*",end=" ")
        print()
    for i in range(5):
        for j in range(i,5):
            print("*",end=" ")
        print()
    Reply
  84. kalyan says

    June 13, 2022 at 4:39 pm

    s="kalyan"
    for i in s[::-1]:
        print(i,end=" ")

    to reverse a string

    Reply
  85. reef says

    May 18, 2022 at 3:57 pm

    print()
    
    Reply
  86. Afzal Hasan says

    May 8, 2022 at 2:21 am

    ex=15
    my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    for i in range(len(my_list)):
        if i%2!=0:
            print(my_list[i],end=" ")
    Reply
  87. Alvin says

    May 4, 2022 at 2:32 pm

    for 18th problem

    f=5
    for x in range(1,10):
         if x<6:
              f-=1
         else:
              f+=1
         print("* " * (5 - f))
    Reply
  88. Hashim says

    April 20, 2022 at 1:30 pm

    in q6 why not display 50?

    Reply
    • SWAMI PATEL MS says

      June 15, 2022 at 7:22 pm

      SAME QUE BRO ANY ONE CAN EXPLAIN

      Reply
      • Swats says

        June 24, 2022 at 5:58 am

        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.

        Reply
  89. Rohit Chandoriya says

    March 18, 2022 at 3:34 am

    #for 8th problem

    num=[1,2,3,4,5,6,7,8,9,0]
    
    def flo(n):
        for i in range(len(n),0,-1):
            print(num[i-1])
    print(flo(num))
    Reply
    • mouhamed kssourou says

      April 22, 2022 at 7:11 pm

      9
      8
      7
      6
      5
      4
      3
      2
      1
      Reply
  90. Shubham Bansal says

    February 23, 2022 at 1:58 am

    Q18 Alternate and Easy Solution

    num=int(input("Enter a number: "))
    print("")
    for i in range(0,num):
             print("* "*i)
    for j in range(0,num):
             print("* "*(num-j))
    Reply
  91. venkatesh says

    January 30, 2022 at 7:53 pm

    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

    Reply
    • Valluri says

      May 10, 2022 at 1:24 pm

      n,k,starts=input ().split ()
      for i in range (1,n+1):
       S=i%k
       If (s==(starts-1)):
        Print (i,end="")
      Reply
  92. Yunes says

    January 21, 2022 at 2:56 pm

    Exercise 12

    
    num1, num2 = 0, 1
    for i in range(10):
        print(num2, end=' ')
        num1, num2 = num2, num1 + num2
    Reply
  93. Yunes says

    January 21, 2022 at 2:49 pm

    Exercise 18

    
    rows = 5
    for i in range(1,rows+1):
        print('* ' * i)
    for j in range(rows-1,0,-1):
        print('* ' * j)
    Reply
  94. hakizimana frederick says

    January 6, 2022 at 12:27 am

    
    number = 76542
    str_number = str(number)
    reversed = str_number[::-1]
    print(reversed)
    Reply
  95. Vishal says

    December 31, 2021 at 11:47 pm

    For exercise 17

    def calculate_series_sum(num,series):
        if(series == 0 or num == 0):
            return 0
        else:
            return num * (10 ** (series - 1)) + (calculate_series_sum(num, series - 1) )
    
    n = 5
    sum2= 0
    num = 2
    for i in range(0,n):
        sum2 += calculate_series_sum(num, i+1)
        i += 1
        
    print(sum2)
    Reply
  96. Eric says

    December 28, 2021 at 11:11 pm

    Exercise 6

    num = 456767
    lis = []
    
    while num > 0:
        quot = num // 10
        rem = num % 10
        lis.append(rem)
        num = quot
        
    print(len(lis))
    Reply
    • Ram Shekharan says

      April 10, 2022 at 3:24 am

      num = 76548
      str_num = str(num)
      
      digit_count = 0
      
      for val in str_num:
          if val.isdigit():
              digit_count += 1
              
      print(digit_count)
      Reply
  97. Cosmin-Silviu Ghioanca says

    December 6, 2021 at 5:46 pm

    Exercise 7 – An alternative using only 2 variables inside the for loops:

    for i in range(5, 0, -1):
        for j in range(i, 0, -1):
            print(j, end=" ")
        print()
    Reply
  98. Partha says

    December 1, 2021 at 6:16 pm

    # Question no 4
    # this code is according to the formula of arithmetic progression
    a = 1
    x = int(input("Enter the number: "))
    print("sum of number from 1 to", x, "is", (x/2*(2+x-1)))
    Reply
  99. bryan says

    November 12, 2021 at 8:57 pm

    Is this answer acceptable for Q14
    number = [7, 6, 5, 4, 2]
    i = -1
    
    while i >= -5 and i  0:
        print(number[i], end="")
        i -= 1
    Reply
    • bryan says

      November 12, 2021 at 8:59 pm

      number = [7, 6, 5, 4, 2]
      i = -1
      
      while i >= -5 and i  0:
          print(number[i], end="")
          i -= 1
      Reply
  100. Danilo says

    November 5, 2021 at 1:06 pm

    Exercise 8:

    list1 = [10, 20, 30, 40, 50]
    y = len(list1) - 1
    while y >= 0:
        print(list1[y])
        y -= 1
    Reply
  101. Danilo says

    November 4, 2021 at 9:48 pm

    Exercise 4 for any number

    x = int(input('Enter number: '))
    for i in range(1, 11, 1):
        print(x * i)
    Reply
  102. Danilo says

    November 4, 2021 at 8:48 pm

    Exercise 2

    for i in range(1, 7):
        print('\n')
        for j in range(1, i):
            print(j, end = " ")
    Reply
  103. Nwafor Bernard says

    October 21, 2021 at 12:36 am

    Q. 18

    for num in range(5):
        for x in range(num +1):
            print("*", end= " ")
        print()
    else:
        for secNum in range(5, 0, -1):
            for y in range(secNum-1, 0, -1):
                print("*", end=" ")
            print()
    Reply
  104. Praveen Sehra says

    October 16, 2021 at 7:24 pm

    Q7. Print the following pattern.

    a = int(input("Enter a number: "))+1
    for i in range(1, a):
        for j in range(i, a):
            b = a-j
            print(b, end=" ")
        print()
    Reply
  105. Victor says

    October 4, 2021 at 2:05 pm

    # Exercise 18: Print the following pattern

    for i in range(-4,5,1):    
        print(' '.join(['*' for j in range(5 - abs(i))]))
    Reply
    • Develation says

      October 6, 2021 at 6:39 pm

      I don’t think this is very efficient but that’s what I came up with haha

      for i in range(1, 5, 1):
          print("* ", *i)
      if i == 4:
          for i in range(5, 0, -1):
              print("* ", *i)
      Reply
      • Hellington says

        October 6, 2021 at 6:42 pm

        Using if is unnecessary here my friend

        Reply
  106. Houssem says

    September 9, 2021 at 2:58 am

    Q 18 in very simple way:

    
    def pattern(num):
        for i in range(num+1):
            print("* "*i)
        for i in range(num-1, 0, -1):
            print("* "*i)
    
    pattern(5)
    Reply
    • Baraa says

      September 17, 2021 at 2:45 am

      simpler :

      for star in range(0,6):
      
          print(" *"*star)
      
      for star2 in reversed(range(0,5)):
          
          print(" *"*star2)
      Reply
      • Izaaka says

        October 14, 2021 at 10:53 am

        for n in range(num):
            print("* " * n)
        for n in range(num-1):
            print("* " * (num-2-n))

        simpler:)

        Reply
  107. Sonia Sharma says

    August 24, 2021 at 2:23 pm

    Exercise-9 Answer

    for i in range(10,0,-1):
        print(-i)
    Reply
    • Santosh says

      September 9, 2021 at 6:16 am

      9
      8
      7
      6
      5
      4
      3
      2
      1
      0
      Reply
  108. Sonia Sharma says

    August 23, 2021 at 9:39 pm

    Exercise-5-Answer

    list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
    for i in list1:
        if (i%5==0) and (i<151):
            print(i)
    Reply
  109. Sonia Sharma says

    August 23, 2021 at 9:36 pm

    list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
    for i in list1:
        if (i%5==0) and (i<151):
            print(i)
    Reply
  110. Mazhar says

    August 15, 2021 at 6:38 pm

    Exercise 6: – Answer –

    Num = 75869
    print(len(str(Num)))
    Reply
  111. Mazhar says

    August 14, 2021 at 9:36 pm

    Exercise 18: I believe this is easy.

    for i in range(1,6):
        for j in range(i):
            print("*", end= " ")
        print()
    
    for i in range(5,1,-1):
        for j in range(i-1):
            print("*", end= " ")
        print()
    Reply
    • Jan says

      August 19, 2021 at 2:39 pm

      num = int(input())
      
      for i in range(1, num+1):
          print("* " * i, end="")
          print()
      
      for j in range(num-1, 0, -1):
          print("* " * j, end="")
          print()

      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.

      Reply
  112. Mazhar says

    August 8, 2021 at 3:05 pm

    Exercise 15: one more solution

    my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    
    start = 1
    end = len(my_list)
    step = 2
    
    for i in range(start,end,step):
        print(my_list[i])
    Reply
  113. mazhar says

    August 8, 2021 at 2:57 pm

    Exercise 14: Reverse a given integer number

    num = 76542
    
    while num > 0:
        digit = num % 10
        num //= 10
        print(digit,end="") 
    Reply
  114. Mazhar says

    August 8, 2021 at 1:29 pm

    Exercise 10: this also works

    for i in range(5):
        print(i)
    print("Done!")
    Reply
  115. Mazhar says

    August 8, 2021 at 12:32 pm

    Exercise 4: Print multiplication table of a given number

    for i in range(2,21,2):
        print(i)
    Reply
    • badr says

      September 18, 2021 at 5:31 pm

      But it works only for number 2, but we need a code that works for every number that the user input .
      try this code

      num = int(input("Your number :"))
      for i in range(1,11):
          multiplication = num * i 
          print(multiplication)
      Reply
  116. Subin Jerin says

    July 17, 2021 at 3:06 pm

    Another method for Exercise 8

    list1 = [10, 20, 30, 40, 50]
    list1.reverse()
    #print(list1)
    def rev (list1):
        for i in (list1):
            print(i)
    rev(list1)
    Reply
    • Narmin says

      August 6, 2021 at 4:19 pm

      list1=[10,20,30,40,50]
      list2=list1[::-1]
      print(list2)

      #another solution

      Reply
  117. SUBIN JERIN says

    July 17, 2021 at 3:05 pm

    ANOTHER METHOD OF SOLVING PYTHON EXERCISE 8

    list1 = [10, 20, 30, 40, 50]
    list1.reverse()
    #print(list1)
    def rev (list1):
        for i in (list1):
            print(i)
    rev(list1)
    Reply
  118. Mukul says

    July 15, 2021 at 11:07 pm

    Explanation is very poor!! Need to change it.

    Reply
  119. Tamir says

    July 14, 2021 at 6:41 pm

    Exercise 8:

    list1 = [10, 20, 30, 40, 50]
    for i in reversed(list1):
        print(i)
    Reply
  120. Mazhar says

    July 6, 2021 at 6:36 pm

    Exercise 4: Print multiplication table of a given number:

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

    will be perfect.

    Reply
  121. komeil mansouri says

    June 25, 2021 at 9:31 pm

    Exercise 12 Solution:

    print("Fibonacci sequence:")
    b=[0,1]
    for i in range(8):
        b.append(b[i]+b[i+1])
    print(b)
    Reply
  122. Omer says

    June 23, 2021 at 4:29 am

    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.

    Reply
    • Jan says

      August 19, 2021 at 2:44 pm

      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.

      Reply
  123. nipuni cabral says

    June 22, 2021 at 4:06 pm

    for exercise 07:

    for x in range(6,1,-1):
        for y in range(x-1,0,-1):
            print(y,end=" ")
    
        print()
    Reply
    • Mona says

      July 31, 2021 at 1:34 am

      for i in reversed(range(1,6,1)):
          for j in range(i,0,-1):
              print(j,end=' ')
          print()
      Reply
  124. AndyLee says

    June 14, 2021 at 1:01 pm

    Another solution for Exercise 8:

    for num in range(50, 0, -10):
        print(num)
    Reply
  125. AndyLee says

    June 13, 2021 at 5:50 am

    For exercise 3, I found that I had to add float, e.g.

    n = int(float(input('Please enter a range of numbers.')))

    or I would get this error message with some ranges “ValueError: invalid literal for int() with base 10: “

    Reply
  126. Ritvik says

    June 12, 2021 at 1:48 pm

    FOR EX 7

    num = int(input())
    for i in range(num, 0, -1):
        for j in range(i, 0, -1):
            print(j, end=' ')
        print(' ')
    Reply
  127. Shoeb Agha says

    May 25, 2021 at 11:58 am

    Another solution for Exercise 18

    max_num=int(input('Enter the number:'))
    for i in range(1,max_num+1):
        print('* '*i)
    for i in range(max_num-1,0,-1):
        print("* "*i)
    Reply
    • Aditya says

      June 11, 2021 at 5:06 pm

      Another solution for Question no -11

       
      k = int(input())
      n = int(input()) 
      while(k<=n):
          flag=False
          i = 2
          while(i<k):
              if(k%i==0):
                  flag=True 
              i=i+1 
          if(not(flag)):
              print(k)
          k=k+1 
      Reply
    • AndyLee says

      June 20, 2021 at 8:22 am

      This is beautiful!

      Reply
  128. Shoeb Agha says

    May 25, 2021 at 11:38 am

    Exercise 14

    num=str(input('Enter the number:'))
    length=len(num)
    for i in range(length,0,-1):
        print(int(num[i-1]),end='')
    Reply
    • Amir says

      June 26, 2021 at 7:26 pm

      thanks for sharing this solution

      Reply
  129. Jignesh Ramani says

    May 2, 2021 at 11:57 am

    We can also achieve the result using this code:

    for i in range(5):
        print("* " * (i+1))
    
    for i in range(5,0,-1):
        print("* " * (i-1))
    Reply
  130. Siddhartha Roy says

    April 7, 2021 at 3:42 am

    For Exercise 18:

    We can also achieve the result using this code:

    user_input=int(input("How many blocks do you want to add to your vertical pyramid?: "))
        
        for n in range(1, user_input):
            print(i*n)
            
        for n in range(user_input, 0, -1):
            print(i*n)

    Output:
    How many blocks do you want to add to your vertical pyramid?: 5

    *
    **
    ***
    ****
    *****
    ****
    ***
    **
    *
    Reply
  131. Rashin says

    March 15, 2021 at 9:37 pm

    #EXercise 18 less steps

    
    rows = 5
    for r in range(1,rows+1):#variable 'r' value increases from 1 to 5{range(1,6)}
        print('* '*r)#strings displayed several times by multiplying
        print("\r")
    for c in range(rows-1,0,-1):#variable 'c' value decreases from 4 to 1{range(4,0,-1)}
        print('* '*c)
        print('\r')
    Reply
    • Thomas says

      June 26, 2021 at 2:13 am

      This prints the pattern based on the distance (absolute value) from 5. Thus a simple algorithm.

      for i in range(1, 10):
          dist = abs(5 - i)
          temp = "* "
          for i in range(5 - dist):
              print('* ', end="")
          print()
      Reply
  132. Rashin says

    March 15, 2021 at 9:20 pm

    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))
    Reply
    • Mona says

      July 31, 2021 at 11:08 am

      SMOOTH! THANK YOU!

      Reply
  133. Rashin says

    March 15, 2021 at 8:49 pm

    #EXercise 16

    
    input_num = 6
    for i in range(1, input_num+1) :
        print('Current no is : ', i ,' and the cube is ', i**3) #for cube ' i **3 ' exponent in python is **
    Reply
  134. Rashin says

    March 15, 2021 at 11:28 am

    for ex 7 cant we use

    
    for r in range( 5, 0, -1) :
        for c in range( r, 0, -1) :
            print(c , end='  ')
        print( '\n' )
    Reply
  135. Amber says

    March 9, 2021 at 10:31 am

    # question 1

    for i in range(0,11,1):
        print(i)
    Reply
  136. Saurabh says

    March 9, 2021 at 1:06 am

    Are you also there on youtube

    Reply
  137. Python_noob says

    March 8, 2021 at 12:00 am

    for example. 6
    Can’t you just use

    
    n = 75869
    print(len(str(n)))
    
    Reply
  138. kakhaber says

    February 13, 2021 at 2:39 am

    Hello. I am a beginner programmer and your laconic exercises help me a lot. I appreciate your work and thank you .(Georgia.Tbilisi)

    Reply
  139. Suman kumar Shrestha says

    February 5, 2021 at 11:56 am

    Solution to 6:

    given_num = 75869
    num_string = str(given_num)
    print(len(num_string))
    Reply
  140. Tarun Venkat says

    January 31, 2021 at 6:31 pm

    The answer to the exercise 15

    my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    for items in my_list:
        if(items%20==0):
            print(items)
    Reply
  141. Moshe Mizrachi says

    January 20, 2021 at 9:00 pm

    I think it’s much more convenient to answer question NUMBER 5 with a function.
    MY SOLUTION:

    def divi5(lst):
        for x in range(len(lst)):
            if lst[x] <= 150 and lst[x] % 5 == 0:
                print(lst[x])
    Reply
  142. pavle says

    January 12, 2021 at 8:49 pm

    The solution to exercise 16

    num = 8
    
    for i in range(0, num, 1):
        if(i == num-1):
            print("* "*i)
            for a in range(num, 0, -1):
                print("* "*a)
        else:
            print("* "*i)
    Reply
  143. Pavle says

    January 12, 2021 at 4:05 pm

    Aolution to 8

    for l in range(len(list1)):
        print(list1[-(l+1)])
    Reply
  144. Rajkumar says

    December 21, 2020 at 12:01 pm

    Question 18. print the following pattern

    for i in range(5):
        for j in range(i):
            print('*', end=' ')
        print()
    for k in range(5,0,-1):
        for l in range(k,0,-1):
            print('*', end=' ')
        print()
    Reply
    • Haider Ali says

      January 11, 2021 at 12:08 pm

      * 
      * * 
      * * * 
      * * * * 
      * * * * * 
      * * * * 
      * * * 
      * * 
      * 
      
      Reply
  145. Rajkumar says

    December 20, 2020 at 11:34 pm

    Question 16

    num = int(input("Enter a no: "))
    
    for i in range(1, num+1):
        print (f"Current No. is {i} and cube is {i*i*i}")
    Reply
  146. Rajkumar says

    December 20, 2020 at 11:25 pm

    Question 15

    my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    
    newlist = my_list[1::2]
    #print(newlist)
    for i in newlist:       # list converted into int
        print(i, end=' ')
    Reply
  147. Rajkumar says

    December 20, 2020 at 11:12 pm

    Question 15

    my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    for i in range(1,len(my_list), 2):
        print(my_list[i])
    Reply
  148. Rajkumar says

    December 20, 2020 at 10:51 pm

    Question 14: Reverse a given integer numbers

    num = 76542
    
    while num > 0:
        digit = num % 10
        num = num // 10
        print(digit, end='')
    Reply
  149. Rajkumar says

    December 20, 2020 at 6:08 pm

    Question 10

    try:
        for i in range(5):
            print(i)
    finally:
        print('Done!')
    Reply
  150. Rajkumar says

    December 20, 2020 at 6:05 pm

    Question 10:

    for i in range(5):
        print(i)
    print('Done!')
    Reply
    • Rajkumar says

      December 20, 2020 at 6:29 pm

      print("Prime numbers between 25 and 50 are:")
      for i in range(25, 50):
          if i%2!=0 and i%3!=0 and i%5!=0 and i%7!=0:
              print(i, end=' ')
      Reply
  151. Rajkumar says

    December 18, 2020 at 8:07 pm

    Question 6. Given a no, count the total no of digits in the no.

    # Which not involves any loop
    num = 75869
    
    string = str(num)
    print(len(string))
    Reply
    • Mike says

      July 21, 2021 at 9:14 pm

      don’t even need to convert to a string. just use len(num)

      Reply
      • Suchet says

        September 21, 2023 at 9:48 pm

        TypeError: object of type ‘int’ has no len()

        Reply
  152. Rajkumar says

    December 18, 2020 at 7:32 pm

    Question 5

    list1= [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
    
    for i in list1:
        if i == 180:
            break
        elif i%5==0:
            print(i, end=' ')
    Reply
  153. Rajkumar says

    December 18, 2020 at 4:03 pm

    Question 4. Print multiplication table of a given number

    num=int(input("Enter a number: "))
    mul=1
    
    for i in range(1,11):
        mul=i*num
        print(mul, end=' ')
    Reply
  154. tom warren rees says

    December 7, 2020 at 3:03 pm

    very nice

    Reply
  155. aboobakker says

    November 29, 2020 at 10:35 pm

    an easy way of 14th exercise

    num  = [76543]
    num1 = num[::-1]
    print(num1)
    Reply
    • Suchet says

      September 21, 2023 at 9:51 pm

      Output
      [76543]

      Do you guys even test your code before posting solutions?

      Reply
  156. nikhil says

    November 29, 2020 at 9:30 pm

    question number 8 in loop exercise

    list1 = [10, 20, 30, 40, 50]
    for i in range(len(list1)):
        print(list1[-1-i])
    Reply
  157. Sarah A says

    November 2, 2020 at 7:00 am

    Here are my worked solutions. Some are different from the answers given. Please ask if you have any questions.

    #1

    for i in range(0,11):
        print(i)
    #these both print the same
    i = 0
    while i <= 10:
        print(i)
        i += 1

    #2

    num = 1
    string = ''
    while num <= 5:
        string = string+str(num)+' '
        print(string)
        num += 1

    #3

    num1 = 10
    summ = 0
    for n in range(num1+1): #+1 because range iterates up to but not including number specified
        summ = n + summ
    print(summ)

    #4

    def multtable(number):
        i = 1
        while i <= 10:
            print(number*i)
            i += 1
    multtable(67)

    #5

    list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
    for nums in list1:
        if nums % 5 == 0 and nums <= 150:
            print(nums,end=' ')
        else:
            continue
    print('')

    #6

    num = 75869
    count = 0
    while num != 0:
        num //= 10 #dividing by 10 will remove last digit(must use // to pass as integer)
        count += 1
    print('Number specified has %s digits!' % (count))

    #7

    for r in range(5,0,-1): #for each row
        for n in range(r,0,-1): #counting backwards
            print(n,end=' ')
        print('')

    #8

    list1 = [10,20,30,40,50]
    for t in range(len(list1),0,-1): #iterates backwards
        print(list1[t-1])

    #9

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

    #10

    try:
        for i in range(5):
            print(i)
        print('Done!')
    except:
        print('Error Occured.')

    #11

    nums = list(range(25,50)) #create list of nums to edit
    for n in range(25,50): #use range here since indexes will be actively changing
        for a in range(2,n):
            if n % a == 0:
                nums.remove(n)
                break #break out of loop for specific number once removed
            else:
                continue #will keep trying numbers to divide by 
    for i in nums:
        print(i)

    #12

    fib = [0,1]
    for i in range(2,10):
        new = fib[i-2]+fib[i-1]
        fib.append(new)
    for i in fib:
        print(i,end=' ')
    print('')

    #13

    factorial = 5
    for i in range(factorial,1,-1): #set end to 1 to avoid multiplying by 0
        factorial *= i-1
    print(factorial)

    #14

    number = 76542
    number = list(str(number))
    number.reverse()
    for i in number:
        print(i,end='')

    #15

    my_list = [10,20,30,40,50,60,70,80,90,100]
    for e in range(len(my_list)):
        if e % 2 == 0:
            print(my_list[e],end='\n')
        else:
            continue
    #indicies start at 0 so technically 30,50,70,90 are at even indicies

    #16

    including = 6
    for i in range(1,7): #remember range counts up to but not including number specified
        cube = i**3
        print('The square cube of %s is %s.' %(i,cube))

    #17

    num_of_terms = 5
    list1 = ['2'] #multiplying strings repeats string certain number of times
    for i in range(1,6):
        new = list1[0]
        new = new*i
        if new != '2':
            list1.append(new)
    print(list1)
    summ=0
    for i in range(len(list1)):
        summ += int(list1[i])
    print('Total sum is: %s' %(summ))

    #18

    rows = [1,2,3,4,5,4,3,2,1]
    string = '*'
    for i in range(len(rows)):
        print(string*rows[i])
    Reply
  158. A.Ramya says

    November 1, 2020 at 3:06 pm

    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

    Reply
    • Tribhuvan sai says

      August 3, 2022 at 4:17 pm

      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!

      #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
      
      #let the list be: (since you haven't mentioned the list, I have assumed it)
      list_1 =[1,3,5,-6,7,-1,9]
      sum = 0
      
      #reading the elements in the list
      
      for i in list_1:
          #checking if the element is -1
          if i ==-1:
              
              #checking if the index of -1 is 0 or not. if yes, then print the average as 0
              #I have done this since in the next else statement we use index for division
              #and if when we divide by 0, we get an error
              
              if list_1.index(i)==0:
                  print("the average is: ",0)
              
              #here, i have written a loop to find the sum and then used it to find the average
              #another alternative is to use math module and find the average(although I am not
              #sure if it is possible to find average of the elements in a list.).But since this 
              #is an exercise for loops I used loops
              
              else:
                  index = list_1.index(i)
                  for j in range(0,index):
                      sum = sum +list_1[j]
                      
                  #found the average and print it
                  
                  average = sum/index
                  print(average)
          
          else:
              continue

      Hope you understood my solution
      thanks!

      Reply
  159. Tori says

    October 30, 2020 at 9:10 pm

    Question 3

    user=input('Give a number: ')
    print('Sum of all number between 1 and entered number is '+ str(sum(range(1,int(user)+1))))
    Reply
    • Joe says

      August 21, 2022 at 8:16 pm

      TypeError: ‘int’ object is not callable

      Reply
  160. Abdu Ismael says

    October 20, 2020 at 8:30 am

    question 16

    for x in range(1,6+1):
        print("current number is:",x,"and the cube is",x**3)
    Reply
  161. Abdu Ismael says

    October 20, 2020 at 8:24 am

    question 15

     my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    
    for x in range(len(my_list)):
        if x%2!=0:
          print(my_list[x],end=' ')
    Reply
  162. Abdu Ismael says

    October 20, 2020 at 8:00 am

    question 12 using for loop

    n1 = 0
    n2= 1
    temp = 0
    for x in range(1,10+1):
        print(n1, end=" ")
        temp = n1+n2
        n1=n2
        n2=temp
    
    Reply
  163. Abdu Ismael says

    October 20, 2020 at 6:27 am

    question 10

    for x in range(1,10+1):
        print(x*x)
    print("Done!")
    Reply
  164. Abdu Ismael says

    October 20, 2020 at 6:23 am

    question 9

    for x in range(10):
        print(x-10)
    Reply
  165. Abdu Ismael says

    October 20, 2020 at 6:18 am

    question 8

    list1 = [10, 20, 30, 40, 50]
    num = 0
    for x in list1:
        list1.reverse()
        for y in list1:
            print(y)
        break;
    Reply
  166. Abdu says

    October 17, 2020 at 12:21 am

    question 5

    list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
    
    for x in list1:
        if x <= 150 and x%5==0:
            print(x)
    Reply
  167. Abdu says

    October 16, 2020 at 11:44 pm

    question 3

    num = int(input("Enter a number: "))
    sum1 = 0
    for x in range(1,num+1):
        sum1 +=x
    
    print("sum of all the numbers between 1 and",num,"is: ",sum1)
    Reply
  168. Mel-Tech says

    September 29, 2020 at 6:13 pm

    Alternative answer for question 14

    num=76542 
    snum=str(num) 
    print (snum[: : -1])
    Reply
    • Rajeesh says

      October 14, 2020 at 1:27 am

      Question asked to use a loop.

      Reply
  169. Marek says

    September 28, 2020 at 6:03 pm

    Alternative solution for question 18:

    
    n=5
    no_rows=2*n-1
    
    for i in range(1,no_rows+1):
        if i>n:
            j=(no_rows+1-i)
        else:
            j=i
        print(j* " *")
    Reply
  170. Asma_Bouf says

    September 23, 2020 at 3:07 pm

    solution 16:

    input_number = 6
    for i in range(1,input_number+1):
     print("Current Number is : ",i, "and the cube is ",i**3)
    Reply
  171. Asma_Bouf says

    September 23, 2020 at 2:26 pm

    solution 14:

    number = 76542
    reverse = 0
    while number > 0:
        reverse = number % 10  # to save the last digit of the number as a first number of the reversed one
        number //= 10  #to remove the saved digit from the original number
        print(reverse,end="")
    Reply
  172. Asma_Bouf says

    September 23, 2020 at 5:03 am

    solution 13 :

    num=5
    for i in range(num-1,1,-1):
        while i<0:
            break
        else:
         num *= i
         factorial = num
    print(factorial)
    Reply
  173. Ajinkya says

    September 8, 2020 at 4:15 pm

    Exercise Question 10: Display a message “Done” after successful execution of for loop

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

    print(“Done”)

    Reply
  174. Nalini says

    September 2, 2020 at 9:47 am

    Q3:
    n= int(input(“enter a number”)
    result = n*(n+1)//2
    print(result)

    Reply
    • Keerthik Shetty says

      September 6, 2020 at 3:01 pm

      a=int(input('enter the number to cal'))
      sum=0
      for i in range(a):
       sum=sum+i
      print(sum)
      Reply
  175. qwertytrg says

    August 13, 2020 at 3:23 pm

    Do you have class/oop exercises?

    Reply
  176. Mark says

    August 8, 2020 at 12:52 am

    Can I just use print("Done") without the else? What does the else do in the code?

    Reply
    • Mark says

      August 8, 2020 at 12:52 am

      In Q10, I forgot to mention it.

      Reply
    • Robert says

      August 14, 2020 at 3:14 pm

      So basically the else runs if there is a break in the loop otherwise the else dose not come in to picture

      Reply
  177. vijay kant verma says

    August 3, 2020 at 5:40 am

    list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
    for item in list1:
        if item%5 == 0 and item <= 150:
            print(item)
        item += 1
    Reply
    • THAMIZHSELVAN says

      August 10, 2020 at 7:10 pm

      think so,
      item+=1 is unwanted in the above code

      Reply
    • Megh says

      August 27, 2020 at 7:47 pm

      No,, you can’t every time when it’s count,, it also prints “done”,,

      Reply
    • Keerthik Shetty says

      September 6, 2020 at 3:14 pm

      list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
      for i in list1:
       if i>150:
          break
       if i%5==0:
          print(i)
       else:
          pass
      Reply
  178. Rachel F. says

    August 3, 2020 at 3:11 am

    I didn’t use a loop for Question 6, but this works for 0 and negative numbers:

    number = abs(int(input("Enter a number: ")))
    number = str(number)
    length = len(number)
    print("Total digits are: ", length)
    Reply
    • Rachel F. says

      August 3, 2020 at 3:22 am

      Edited so it will also work with decimals:

      number = abs(float(input("Enter a number: ")))
      number = str(number)
      number = number.replace(".", "")
      length = len(number)
      print("Total digits are: ", length)
      Reply
      • Rachel F. says

        August 3, 2020 at 3:28 am

        Scratch that last one! Needs work!

        Reply
        • Rachel F. says

          August 3, 2020 at 3:59 am

          How’s this for Question 6:

          number = (input("Enter a number: "))
          if "." in number or "-" in number:
              number = number.replace(".", "")
              number = number.replace("-", "")
          length = len(number)
          print("Total digits are: ", length)
          Reply
    • theo says

      October 8, 2020 at 10:05 am

      should we have an easier alternative

      num = str(75869)
      lst = len(num)
      print(lst)

      # the outcome is still 5, btw

      Reply
    • lily fullery says

      September 26, 2022 at 1:28 am

      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–

      a = 673294702380
      string = str(a)
      b = 0
      while len(string[0:b]) != len(string):
          b = b +1
      print(len(string))
      Reply
  179. sheena says

    July 28, 2020 at 7:33 am

    Q6

     
    c1=234567
    c=len(str(c1))
    print(c)
    
    		
    Reply
    • Prashant says

      October 6, 2020 at 12:47 pm

      Ya it worked and it is very simple compare to loop

      Reply
  180. ujair says

    July 25, 2020 at 11:11 pm

    In a question 4:

    
    num_input = input ("enter your number")
    For num in range(1,11):
     While True:
       Multiplication =  int(num_input)*int(num)
        Print (Multiplication)
        break
    Reply
  181. SANKAR says

    July 16, 2020 at 7:39 pm

    Question 7:

    
    last_number =6
    
    for i in range(1,last_number):
        for j in range(last_number-i, 0,-1):
            print( j, end=" ")
        print ("\n")
    Reply
  182. SANKAR says

    July 16, 2020 at 7:31 pm

    Question 2:

    last_number =6
    
    for row in range(1, last_number):
        for j in range(1, row+1):
            print( j, end=" ")
        print ("\n")
    Reply
  183. shiva says

    July 15, 2020 at 10:50 am

    solution for exercise 5

    
    list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
    
    for element in list1:
        if (element>150):
            break
        elif (element%5==0):
            print(element)
        else:
            continue
    
    Reply
  184. shiva says

    July 15, 2020 at 10:45 am

    
    num = 2
    times=1
    
    while times<=10:
        print(num*times)
        times+=1
    
    Reply
  185. shiva says

    July 15, 2020 at 10:40 am

    num =10
    add=0
    while num>=1: #go to loop code until num is greater than 1
        add+=num  #adding current num to variable add 
        num-=1    #decresing num value by till it reaches 1 
    print(add)    #print add valuse,after while loop is False
    
    Reply
  186. Saurabh Jadhav says

    July 12, 2020 at 4:00 pm

    for question no. 4

    
    n = int(input("Desired number : "))
    i = 1
    while i <11 :
    	print(n*i)
    	i+=1
    
    Reply
  187. Khalid says

    July 9, 2020 at 3:38 pm

    Question8

    
    list1 = [10, 20, 30, 40, 50]
    
    for num in list1[::-1]:
        print(num)
    Reply
    • Abdimajid says

      August 11, 2020 at 2:01 pm

      You are the best bro.

      Reply
  188. Khalid says

    July 9, 2020 at 3:31 pm

    Question5

    
    list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
    
    for num in list1:
        if num <= 150 and num % 5 == 0:
            print(num)
    
    Reply
  189. Khalid says

    July 9, 2020 at 3:23 pm

    Question4

    
    provided_num = int(input("Give a number: "))
    
    multiplication_table = list(range(provided_num, 11 * provided_num, provided_num))
    
    for num in multiplication_table:
        print(num)
    
    Reply
  190. Robert Ndebele says

    June 29, 2020 at 10:37 pm

    Q8:

    
    List1 = [10, 20, 30, 40, 50]
    List1.reverse()
    for nums in List1:
        print(nums)
    Reply
  191. Son_Volam says

    June 29, 2020 at 8:42 am

    # Exercise Question 6: Given a number count the total number of digits in a number

    number = input("Given number: ")
    print(len(number))
    Reply
  192. Jakes says

    June 20, 2020 at 7:44 am

    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 🙂

    Reply
    • Vishal says

      June 20, 2020 at 7:31 pm

      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:

      for i in range(1, 10, 2):
          print(i)

      This will produce the following output.

      1
      3
      5
      7
      9

      I hope it helps you. Let me know if you have any doubts.

      Reply
      • Jakes says

        June 21, 2020 at 10:55 pm

        got it, thank you :))

        Reply
    • lalith says

      June 23, 2020 at 1:40 pm

      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…

      Reply
    • Basu says

      July 18, 2020 at 8:33 pm

      It is basically used to determine how you want to increment the base value. for example –

      for i in range (1, 10, 3):
          print (i)

      The output will be 1 4 7.

      Reply
  193. Alec Nigh says

    June 17, 2020 at 9:57 pm

    Q6 without a loop

    
    number = 696969
    x = len(str(number))
    print(x)
    
    Reply
  194. Ash says

    June 15, 2020 at 6:44 pm

    
    list1 = [10, 20, 30, 40, 50]
    list1.reverse()
    for rev in list1:
        print(rev)
    
    Reply
  195. Narendra says

    June 8, 2020 at 2:52 pm

    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)
    
    Reply
  196. Narendra says

    June 8, 2020 at 2:21 pm

    Exercise Question 2: Print the following pattern

    
    for i in range(6):
        for j in range (i):
            print(i,end='')
        print('\n')
    
    Reply
  197. Bangava says

    June 7, 2020 at 10:44 pm

    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!")
    
    Reply
  198. parag k says

    May 26, 2020 at 10:24 am

    list1 = [10, 20, 30, 40, 50]
    n = len(list1)
    for i in range(1,n+1):
        print(list1[n-i])
    
    
    		
    Reply
    • DHAiRYA says

      July 4, 2020 at 9:32 am

      How about

      
      list = [10, 20, 30, 40, 50]
      for i in list[::-1]:
          print(i)
      
      Reply
    • pratik panchal says

      September 5, 2020 at 10:07 pm

      50
      40
      30
      20
      10

      Reply
  199. Parag K says

    May 26, 2020 at 9:55 am

    Question 7:

    n = input('Enter any no :')
    count = 0
    for i in n:
        count += 1
    print('Total digits are: ',count)
    
    
    
    		
    Reply
  200. Parag Khedikar says

    May 26, 2020 at 9:21 am

    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
    
    
    
    		
    Reply
  201. jyotirmoy ghose says

    May 23, 2020 at 12:06 am

    # # Exercise Question 1:

    # for i in range(11):
    #     print(I)
    
    # # Exercise Question 2: Print the following pattern
    # # 1 
    # # 1 2 
    # # 1 2 3 
    # # 1 2 3 4 
    # # 1 2 3 4 5
    
    # 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:

    # list = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
    
    # for i in list:
    #     if(i>150):
    #         break  
    #     if(i%5==0):
    #         print(i)
    

    # # Exercise Question 6:

    # num= int(input("enter number : "))
    # count=0
    # while(num!=0):
    #     num = num//10
    #     count+=1
    # print(count)  
    

    # Exercise Question 7:

    # 5 4 3 2 1 
    # 4 3 2 1 
    # 3 2 1 
    # 2 1 
    # 1
    
    # 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:

    # list1 = [10, 20, 30, 40, 50]
    
    # lent= len(list1)
    # for i in range(lent-1,-1,-1):
    #     print(list1[i],end=" ")
    

    # Exercise Question 9:

    # for i in range(10,0,-1):
    #     print(-i)
    

    # Exercise Question 10:

    for i in range(5):
        print(i)
    print("done")
    
    Reply
  202. Divyanshu Sharma says

    May 19, 2020 at 2:13 pm

    for Question 4:

    num = int(input("Enter Number= "))
    table = 0
    for i in range(1,11):
        table = (i*num)
        print(table)
    
    Reply
  203. Divyanshu Sharma says

    May 19, 2020 at 2:12 pm

    Solution for Exercise 4:

    num = int(input(“Enter Number= “))
    table = 0
    for i in range(1,11):
    table = (i*num)
    print(table)

    Reply
  204. Boris says

    May 17, 2020 at 10:23 pm

    For Q8

    list1 = [10, 20, 30, 40, 50]
    for i in range(len(list1)+1):
     if i!=0:
      print(list1[-i])
    
    Reply
    • vishal says

      May 22, 2020 at 10:46 pm

      list1 = [10,20,30,40,50]
      
      for i in list1[::-1]
          print(I)
      
      Reply
  205. Boris says

    May 17, 2020 at 9:59 pm

    Question 6 doesn’t work with 0 and negative numbers. I don’t understand what is

     n//=10

    and how does it help to count, if I delete that line, I get an endless loop which is to be expected.

    Reply
  206. nikkhil k says

    May 11, 2020 at 1:52 am

    for Q.7

    for i in range(5,0,-1):
        for j in range(i,0,-1):
            print(j, end=" ")
        print()
    
    Reply
  207. nikkhil k says

    May 11, 2020 at 1:50 am

    for Q.8

    list1 = [10, 20, 30, 40, 50]
    for i in list1[::-1]:
        print(i)
    
    Reply
  208. suraj says

    May 8, 2020 at 4:50 pm

    alternative for answer of question 8

    list1 = [10, 20, 30, 40, 50]
    for i in list1[::-1]:
        print(i)
    
    Reply
  209. dhananjay says

    May 5, 2020 at 4:34 pm

    sir, i want to ask that are these python exercises sufficient for project works?

    Reply
    • Vishal says

      May 7, 2020 at 8:36 pm

      These exercises will help you to improve your understanding and coding ability.

      Reply
  210. Alec Nigh says

    April 25, 2020 at 1:11 am

    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 += 1
    

    However, 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?

    Reply
    • Vishal says

      April 26, 2020 at 5:02 pm

      Yes, i is an iterator variable, changes its value in each iteration.

      Reply
  211. Trung Nguyen says

    April 23, 2020 at 2:54 am

    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?

    Reply
    • Vishal says

      April 23, 2020 at 7:45 pm

      Hey Trung Nguyen,

      The default value of the end is \n meaning that after the print statement, it will print a new line. The end is you want to be printed after the print statement has been executed.
      For example, print(i, end=' ') will print all the values of i on the same line. If we replace this with print(i, end="\n\n") it will write two newlines after each value of i

      Reply
      • omkesh says

        August 5, 2022 at 1:36 pm

        Thanks sir

        Reply
  212. Ashish Ruchal says

    April 17, 2020 at 10:12 pm

    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.

    Reply
    • Vishal says

      April 18, 2020 at 12:48 am

      Thank you, Ashish. I really appreciate your kind words and encouragement.

      Reply
  213. fkoth says

    April 16, 2020 at 8:35 pm

    For exercise question 2, here is a short answer:

    num = []
    for i in range(1,6):
        num.append(i)
        print(*num)
    
    Reply
    • Vishal says

      April 17, 2020 at 5:07 pm

      Hey, Thank you for an alternative solution

      Reply
  214. Anais says

    April 13, 2020 at 12:11 pm

    Hi
    In solution of question 8, “-1” is equivalent with 10? Then why we reduce with -1 in

    start = len(list1) - 1
    stop = -1
    step = -1
    
    Reply
  215. agus says

    April 13, 2020 at 4:13 am

    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)
    
    Reply
    • Vishal says

      April 13, 2020 at 7:57 pm

      Thank you, Agus

      Reply
    • JJ says

      August 8, 2023 at 3:29 am

      list1 = [10, 20, 30, 40, 50][::-1]
      for i in list1:
      print(i)

      Reply
  216. Avinash Trivedi says

    April 9, 2020 at 1:27 pm

    In question number 2 when input given is beyond 50 it does not generate desired pattern . Can you please explain it

    Reply
    • Vishal says

      April 10, 2020 at 3:55 pm

      Hey Avinash, It is generating Pattern correctly after giving input bigger than 50. Can you please share your code.

      Reply
  217. arsalanrad says

    March 24, 2020 at 9:00 pm

    we can use the reverse() and it much easier!

    Reply
  218. elite_coder says

    March 19, 2020 at 11:56 am

    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.?

    Reply
    • Vishal says

      March 19, 2020 at 9:09 pm

      Thank you, elite_coder. Sure we will add comments

      Reply
  219. Aahna says

    March 15, 2020 at 9:17 am

    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.

    Reply
    • Vishal says

      March 16, 2020 at 5:03 pm

      Hi Ashna, The question was created to demonstrate the use of else clause in for loop. The else block executes only when loop terminates naturally

      Reply
  220. Nifdi says

    March 5, 2020 at 8:12 am

    what does num//=10 means in exercise 6?

    Reply
    • Vishal says

      March 5, 2020 at 10:33 am

      Hi Nifdi, Its Floor division operator and returns the “floor” of the result.

      Reply
      • SAIDAZIM says

        July 5, 2020 at 9:55 pm

        the numbers are divided by 7 without a remainder per 1,000,000

        Reply
      • Peny says

        October 11, 2020 at 4:01 pm

        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).
        ??

        Reply
    • Radhika.G. says

      July 24, 2020 at 11:10 pm

      It fetches the quotient.
      num //= 10
      for example 1234//=10, will fetch 123 alone.
      It is opposite to num%10 which fetches the remainder.

      Reply
      • THUNDER says

        November 9, 2020 at 4:50 pm

        VERY COOL

        Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com