Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“š Python Loops: All-in-One Practice Assignments

Python Loops All-in-One Practice Assignments

Comprehensive practice covering for, while, nested loops, break, continue, else, and more.

Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers to make programming easy through practical examples and clear explanations.
šŸ“‘ On this page:
  • About
  • For Loop
  • While Loop
  • Nested Loops
  • Break & Continue
  • Loop Else
  • Advanced
  • Try It
Share:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link

About These Assignments

This page contains 30+ unique practice assignments that cover all loop concepts in Python. Unlike the topic-specific pages, these problems are designed to test your ability to choose the right loop for each situation and combine loop techniques effectively.

🟢 Beginner 🟠 Intermediate šŸ”“ Advanced
šŸŽÆ Unique Challenge: Each problem is designed to be different from the topic-specific assignments. You'll need to decide which loop type (for, while, or nested) is most appropriate for each scenario.

šŸ’” Tip: Try each problem yourself first. Click "Show Solution" only after attempting.

1. For Loop Challenges 5 Questions

šŸŽÆ Focus: Iterate over sequences with for loop.
Beginner Q1: Sum of Squares
Calculate the sum of squares of numbers from 1 to n using a for loop.
šŸ’” Solution:
n = int(input("Enter n: "))
sum_sq = 0
for i in range(1, n+1):
sum_sq += i ** 2
print(f"Sum of squares: {sum_sq}")
šŸ“– Explanation: Uses range() to iterate from 1 to n and accumulates squares.
Beginner Q2: Factorial Using For Loop
Calculate the factorial of a number using a for loop.
šŸ’” Solution:
n = int(input("Enter n: "))
fact = 1
for i in range(1, n+1):
fact *= i
print(f"{n}! = {fact}")
šŸ“– Explanation: Iterative factorial calculation using for loop.
Intermediate Q3: List of Prime Numbers
Generate a list of prime numbers up to n using a for loop.
šŸ’” Solution:
n = int(input("Enter n: "))
primes = []
for num in range(2, n+1):
is_prime = True
for i in range(2, int(num**0.5)+1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
print(primes)
šŸ“– Explanation: Uses nested for loop (one for range, one for primality test).
Intermediate Q4: Reverse a String
Reverse a string using a for loop (without slicing).
šŸ’” Solution:
text = input("Enter a string: ")
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
print(f"Reversed: {reversed_text}")
šŸ“– Explanation: Builds reversed string by prepending each character.
Advanced Q5: Custom Range Generator
Create a custom range function that generates numbers from start to end with a step, but only even numbers.
šŸ’” Solution:
def even_range(start, end, step=2):
result = []
for i in range(start, end+1, step):
if i % 2 == 0:
result.append(i)
return result
print(even_range(1, 20, 3))
šŸ“– Explanation: Custom iteration with filtering inside for loop.

2. While Loop Challenges 5 Questions

šŸŽÆ Focus: Condition-based iteration with while loop.
Beginner Q6: Countdown Timer
Print a countdown from n to 1 using a while loop.
šŸ’” Solution:
n = int(input("Enter n: "))
while n > 0:
print(n)
n -= 1
print("Blast off!")
šŸ“– Explanation: Decrements n until it reaches 0.
Beginner Q7: Sum Until Zero
Keep asking the user for numbers until they enter 0, then print the sum.
šŸ’” Solution:
total = 0
num = None
while num != 0:
num = int(input("Enter a number (0 to stop): "))
total += num
print(f"Total: {total}")
šŸ“– Explanation: Sentinel-controlled while loop.
Intermediate Q8: Digit Sum
Calculate the sum of digits of a number using a while loop.
šŸ’” Solution:
num = int(input("Enter a number: "))
temp = abs(num)
digit_sum = 0
while temp > 0:
digit_sum += temp % 10
temp //= 10
print(f"Sum of digits: {digit_sum}")
šŸ“– Explanation: Extracts digits using modulo and integer division.
Intermediate Q9: Palindrome Check
Check if a number is a palindrome using a while loop.
šŸ’” Solution:
num = int(input("Enter a number: "))
temp = num
reversed_num = 0
while temp > 0:
reversed_num = reversed_num * 10 + temp % 10
temp //= 10
if num == reversed_num:
print("Palindrome")
else:
print("Not a palindrome")
šŸ“– Explanation: Reverses number digit by digit using while loop.
Advanced Q10: Collatz Sequence
Generate the Collatz sequence for a given number using a while loop until it reaches 1.
šŸ’” Solution:
n = int(input("Enter a number: "))
seq = [n]
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
seq.append(n)
print(seq)
šŸ“– Explanation: Classic while loop with conditional updates.

3. Nested Loops Challenges 5 Questions

šŸŽÆ Focus: Loops within loops for multi-dimensional problems.
Beginner Q11: Multiplication Table Grid
Print a 5x5 multiplication table grid using nested loops.
šŸ’” Solution:
for i in range(1, 6):
for j in range(1, 6):
print(f"{i*j:4}", end='')
print()
šŸ“– Explanation: Outer loop for rows, inner loop for columns.
Intermediate Q12: Number Pyramid
Print a number pyramid with 5 rows using nested loops.
šŸ’” Solution:
n = 5
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=' ')
print()
šŸ“– Explanation: Inner loop prints increasing numbers per row.
Intermediate Q13: Matrix Diagonal Sum
Calculate the sum of the main diagonal of a 3x3 matrix.
šŸ’” Solution:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
diag_sum = 0
for i in range(3):
for j in range(3):
if i == j:
diag_sum += matrix[i][j]
print(f"Diagonal sum: {diag_sum}")
šŸ“– Explanation: Nested loops with conditional for diagonal elements.
Advanced Q14: Multiplication Table with Different Ranges
Print multiplication tables for numbers 1-5, but only even products (skip odd).
šŸ’” Solution:
for i in range(1, 6):
print(f"Table of {i}:", end=' ')
for j in range(1, 11):
product = i * j
if product % 2 == 0:
print(product, end=' ')
print()
šŸ“– Explanation: Nested loops with conditional filtering inside inner loop.
Advanced Q15: Flatten a List
Flatten a nested list (list of lists) into a single list using nested loops.
šŸ’” Solution:
nested = [[1,2,3], [4,5,6], [7,8,9,10]]
flat = []
for sublist in nested:
for item in sublist:
flat.append(item)
print(flat)
šŸ“– Explanation: Nested loops to traverse all levels of nesting.

4. Break & Continue Challenges 5 Questions

šŸŽÆ Focus: Loop control statements.
Beginner Q16: Find First Multiple
Find the first number between 1 and 100 that is divisible by 7 and 3.
šŸ’” Solution:
for i in range(1, 101):
if i % 7 == 0 and i % 3 == 0:
print(f"First: {i}")
break
šŸ“– Explanation: Break exits loop when condition is met.
Beginner Q17: Skip Multiples of 3
Print numbers from 1 to 20, but skip multiples of 3.
šŸ’” Solution:
for i in range(1, 21):
if i % 3 == 0:
continue
print(i)
šŸ“– Explanation: Continue skips the rest of the iteration.
Intermediate Q18: Break on Negative
Keep accepting numbers until a negative number is entered, then break.
šŸ’” Solution:
while True:
num = int(input("Enter a number (negative to stop): "))
if num < 0:
break
print(f"You entered: {num}")
šŸ“– Explanation: Infinite while loop with break condition.
Intermediate Q19: Skip Vowels
Print a string without vowels using continue.
šŸ’” Solution:
text = "Hello World"
vowels = "aeiouAEIOU"
result = ""
for char in text:
if char in vowels:
continue
result += char
print(result)
šŸ“– Explanation: Continue skips vowels, builds result without them.
Advanced Q20: Nested Break
Find the first pair of numbers (i, j) where i*j > 50, using nested loops with break.
šŸ’” Solution:
found = False
for i in range(1, 11):
for j in range(1, 11):
if i * j > 50:
print(f"First pair: {i} * {j} = {i*j}")
found = True
break
if found:
break
šŸ“– Explanation: Nested break using a flag variable.

5. Loop Else Challenges 3 Questions

šŸŽÆ Focus: Using else with loops.
Intermediate Q21: Check Prime with Else
Check if a number is prime using for-else.
šŸ’” Solution:
n = int(input("Enter a number: "))
for i in range(2, int(n**0.5)+1):
if n % i == 0:
print(f"{n} is not prime")
break
else:
print(f"{n} is prime")
šŸ“– Explanation: Else executes if loop completes without break.
Intermediate Q22: Search with Else
Search for a number in a list. If not found, print "Not found" using else.
šŸ’” Solution:
numbers = [5, 12, 7, 23, 9, 18]
target = int(input("Search for: "))
for num in numbers:
if num == target:
print(f"Found: {target}")
break
else:
print(f"{target} not found")
šŸ“– Explanation: Else executes when the loop completes without break.
Advanced Q23: While-Else with Validation
Validate user input (positive number) using while-else.
šŸ’” Solution:
attempts = 3
while attempts > 0:
num = int(input("Enter a positive number: "))
if num > 0:
print(f"Valid input: {num}")
break
attempts -= 1
print(f"Invalid. {attempts} attempts left.")
else:
print("Max attempts reached. Input validation failed.")
šŸ“– Explanation: While-else executes when condition becomes false naturally.

6. Advanced Loop Challenges 4 Questions

šŸŽÆ Focus: Combining all loop concepts.
Advanced Q24: Number Guessing Game
Create a number guessing game where the user has 5 attempts to guess a random number (1-50).
šŸ’” Solution:
import random
secret = random.randint(1, 50)
attempts = 5
while attempts > 0:
guess = int(input(f"Guess (1-50), {attempts} left: "))
if guess == secret:
print("Correct! You won!")
break
elif guess < secret:
print("Too low")
else:
print("Too high")
attempts -= 1
else:
print(f"Game over! The number was {secret}")
šŸ“– Explanation: Combines while loop, if-else, break, and while-else.
Advanced Q25: Pattern with Conditions
Print a pattern where each row has numbers, but skip rows where the row number is even.
šŸ’” Solution:
n = 7
for i in range(1, n+1):
if i % 2 == 0:
continue
for j in range(1, i+1):
print(j, end=' ')
print()
šŸ“– Explanation: Uses continue in outer loop to skip even rows.
Advanced Q26: While-For Mix
Use a while loop to iterate over a list, and a for loop inside to process each element.
šŸ’” Solution:
data = ["apple", "banana", "cherry", "date", "elderberry"]
i = 0
while i < len(data):
word = data[i]
for char in word:
print(char, end='-')
print()
i += 1
šŸ“– Explanation: Demonstrates mixing while and for loops.
Advanced Q27: Loop with Multiple Conditions
Find numbers between 1 and 100 that are divisible by 3, not divisible by 5, and stop when you find 10 such numbers.
šŸ’” Solution:
found = []
num = 1
while len(found) < 10 and num <= 100:
if num % 3 == 0 and num % 5 != 0:
found.append(num)
num += 1
print(f"Found: {found}")
šŸ“– Explanation: Combines multiple conditions and loop control.

Try It Yourself!

Use the interactive editor below to test your solutions or write your own loop code.

Loading Pyodide... 0%
Python Code Editor
========================================
ALL LOOPS PRACTICE
========================================
Sum of squares (1-5): 55
Countdown:
5 4 3 2 1 Blast off!
Number Pyramid:
1
1 2
1 2 3
1 2 3 4

āœ… Write your loop solutions here!

šŸ“š Related Tutorials

šŸ”„ Introduction to Loops

Learn about loops in Python

āš–ļø For vs While

Understand when to use each loop

ā¹ļø Break, Continue, Else

Learn loop control statements

šŸ“– Related Tutorials
  • For Loop
  • While Loop
  • Nested For Loop
  • For Each Loop
  • Infinite Loops
Previous: For Each Assignments Next: List in Python →