Tired of watching endless Python tutorials but still feeling unsure when it’s time to write your own code? That frustration ends here.
This post brings you 100 Python practice problems with clear, step-by-step solutions that turn confusion into real understanding. You’ll start with simple essentials like variables, loops, and conditionals, then confidently move on to functions, lists, dictionaries, file handling, object-oriented programming, and even some algorithmic challenges.
Every problem is written in plain, simple language so you can try the code yourself first, then check the solution and truly grasp the why behind it—no more guessing. Whether you’re a complete beginner falling in love with coding or you’re preparing for a technical interview, these exercises will help you feel genuinely capable and proud of your progress.
Pick a problem, start coding, and experience that amazing “I got this!” feeling. You’re ready.
Also try it: 100 Ruby practice problems with solutions
1. Print “Hello, World!” to the console.
python
print("Hello, World!")
2. Declare a variable name with your name and print it.
python
name = "Alice" print(name)
3. Take a user’s input for their age and print it.
python
age = input("Enter your age: ")
print(f"Your age is {age}")
4. Add two numbers (5 and 7) and print the result.
python
result = 5 + 7 print(result)
5. Calculate the area of a rectangle with length 10 and width 5.
python
length = 10 width = 5 area = length * width print(area)
6. Check if a number (e.g., 9) is even or odd.
python
num = 9
if num % 2 == 0:
print("Even")
else:
print("Odd")
7. Find the largest of three numbers (10, 25, 17).
python
a, b, c = 10, 25, 17 largest = max(a, b, c) print(largest)
8. Print numbers from 1 to 10 using a for loop.
python
for i in range(1, 11):
print(i)
9. Print the sum of all numbers from 1 to 50.
python
total = sum(range(1, 51)) print(total)
10. Print the Fibonacci sequence up to the 10th term.
python
a, b = 0, 1
for _ in range(10):
print(a, end=" ")
a, b = b, a + b
11. Reverse a string “Python”.
python
s = "Python" print(s[::-1])
12. Count how many vowels are in the string “Hello World”.
python
s = "Hello World" vowels = "aeiouAEIOU" count = sum(1 for ch in s if ch in vowels) print(count)
13. Check if the string “racecar” is a palindrome.
python
s = "racecar" print(s == s[::-1])
14. Remove duplicates from the list [1,2,2,3,4,4,5].
python
lst = [1,2,2,3,4,4,5] unique = list(set(lst)) print(unique)
15. Find the factorial of a number (e.g., 5).
python
import math n = 5 print(math.factorial(n))
16. Generate a list of squares for numbers 1 through 10.
python
squares = [x**2 for x in range(1, 11)] print(squares)
17. Convert a list of strings [“apple”, “banana”, “cherry”] to uppercase.
python
fruits = ["apple", "banana", "cherry"] upper_fruits = [fruit.upper() for fruit in fruits] print(upper_fruits)
18. Check if a given number (e.g., 17) is prime.
python
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
print(is_prime(17))
19. Find the common elements between two lists [1,2,3,4] and [3,4,5,6].
python
list1 = [1,2,3,4] list2 = [3,4,5,6] common = list(set(list1) & set(list2)) print(common)
20. Square each number in a list using map.
python
numbers = [1,2,3,4] squared = list(map(lambda x: x**2, numbers)) print(squared)
21. Count the frequency of each character in a string “abracadabra”.
python
from collections import Counter s = "abracadabra" freq = Counter(s) print(freq)
22. Sort a list of tuples by the second element: [(1,2), (3,1), (5,0)].
python
data = [(1,2), (3,1), (5,0)] data.sort(key=lambda x: x[1]) print(data)
23. Write a function that returns the maximum of two numbers.
python
def max_of_two(x, y):
return x if x > y else y
print(max_of_two(8, 3))
24. Use a dictionary to store phone numbers (name -> number) and retrieve one.
python
phonebook = {"Alice": "123-456", "Bob": "789-012"}
print(phonebook["Alice"])
25. Write a simple calculator that adds, subtracts, multiplies, or divides two numbers.
python
def calculator(a, b, op):
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
return a / b
else:
return "Invalid operator"
print(calculator(10, 5, '*'))
26. Read a line from the user and print it in reverse.
python
text = input("Enter something: ")
print(text[::-1])
27. Write a function that returns the length of a string without using len().
python
def string_length(s):
count = 0
for _ in s:
count += 1
return count
print(string_length("Hello"))
28. Write a program that prints numbers from 1 to 100, but for multiples of 3 print “Fizz”, for multiples of 5 print “Buzz”, and for both print “FizzBuzz”.
python
for i in range(1, 101):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
29. Create a list of even numbers from 0 to 20 using list comprehension.
python
evens = [x for x in range(21) if x % 2 == 0] print(evens)
30. Use a while loop to print numbers from 10 down to 1.
python
i = 10
while i >= 1:
print(i)
i -= 1
31. Write a function that checks if a string contains only digits.
python
def is_all_digits(s):
return s.isdigit()
print(is_all_digits("12345"))
32. Merge two dictionaries: {‘a’:1, ‘b’:2} and {‘c’:3, ‘d’:4}.
python
dict1 = {'a':1, 'b':2}
dict2 = {'c':3, 'd':4}
merged = {**dict1, **dict2}
print(merged)
33. Write a program that prints the current directory using os module.
python
import os print(os.getcwd())
34. Write a program that creates a file named “test.txt” and writes “Hello Python” into it.
python
with open("test.txt", "w") as f:
f.write("Hello Python")
35. Read the file created in the previous problem and print its content.
python
with open("test.txt", "r") as f:
content = f.read()
print(content)
36. Write a program that appends ” – new line” to the same file.
python
with open("test.txt", "a") as f:
f.write(" - new line")
37. Use try-except to handle division by zero.
python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
38. Write a lambda function that squares a number.
python
square = lambda x: x**2 print(square(5))
39. Sort a list of strings by their length: [“cat”, “elephant”, “dog”, “giraffe”].
python
words = ["cat", "elephant", "dog", "giraffe"] words.sort(key=len) print(words)
40. Write a generator that yields numbers from 1 to N.
python
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for num in count_up_to(5):
print(num)
41. Convert a list of integers [1,2,3] into a string “1-2-3”.
python
nums = [1,2,3] result = "-".join(map(str, nums)) print(result)
42. Write a function that returns the sum of all elements in a list (without sum).
python
def sum_list(lst):
total = 0
for num in lst:
total += num
return total
print(sum_list([1,2,3,4]))
43. Find the index of an element in a list (e.g., find index of ‘banana’ in [‘apple’,’banana’,’cherry’]).
python
fruits = ['apple','banana','cherry']
index = fruits.index('banana')
print(index)
44. Write a program that checks if a given year is a leap year.
python
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(is_leap_year(2024))
45. Use enumerate to print index and value of each item in a list.
python
colors = ["red", "green", "blue"]
for i, color in enumerate(colors):
print(i, color)
46. Write a function that returns the number of words in a sentence.
python
def word_count(sentence):
return len(sentence.split())
print(word_count("The quick brown fox"))
47. Use zip to combine two lists [“a”,”b”,”c”] and [1,2,3] into a list of tuples.
python
letters = ["a","b","c"] numbers = [1,2,3] combined = list(zip(letters, numbers)) print(combined)
48. Write a program that prints the current time using datetime module.
python
from datetime import datetime
print(datetime.now().strftime("%H:%M:%S"))
49. Write a program that sleeps for 2 seconds and then prints “Done”.
python
import time
time.sleep(2)
print("Done")
50. Write a function that returns the second largest number in a list.
python
def second_largest(lst):
unique = list(set(lst))
if len(unique) < 2:
return None
unique.sort(reverse=True)
return unique[1]
print(second_largest([5,2,8,8,1,6]))
51. Use filter to keep only even numbers from a list [1,2,3,4,5,6].
python
numbers = [1,2,3,4,5,6] even = list(filter(lambda x: x%2==0, numbers)) print(even)
52. Write a program that prints the multiplication table (1 to 10) for a given number.
python
n = 7
for i in range(1, 11):
print(f"{n} x {i} = {n*i}")
53. Write a recursive function to compute the factorial of a number.
python
def factorial_recursive(n):
if n <= 1:
return 1
return n * factorial_recursive(n-1)
print(factorial_recursive(5))
54. Check if two strings are anagrams (e.g., “listen” and “silent”).
python
def are_anagrams(s1, s2):
return sorted(s1.lower()) == sorted(s2.lower())
print(are_anagrams("listen", "silent"))
55. Sort a dictionary by its values (descending).
python
d = {'apple': 5, 'banana': 2, 'cherry': 8}
sorted_by_value = dict(sorted(d.items(), key=lambda item: item[1], reverse=True))
print(sorted_by_value)
56. Write a program that reads a whole file and returns the number of lines.
python
with open("test.txt", "r") as f:
lines = f.readlines()
print(len(lines))
57. Use random module to pick a random element from a list.
python
import random items = ["rock", "paper", "scissors"] print(random.choice(items))
58. Write a function that finds all duplicate elements in a list.
python
def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)
print(find_duplicates([1,2,3,2,1,4]))
59. Write a program that converts Celsius to Fahrenheit (input 25).
python
celsius = 25 fahrenheit = (celsius * 9/5) + 32 print(fahrenheit)
60. Use any to check if any element in a list is greater than 10.
python
nums = [1,5,12,3] print(any(x > 10 for x in nums))
61. Write a function that rotates a list to the left by k positions.
python
def rotate_left(lst, k):
if not lst:
return lst
k = k % len(lst)
return lst[k:] + lst[:k]
print(rotate_left([1,2,3,4,5], 2))
62. Write a program that prints all prime numbers between 1 and 100.
python
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
for num in range(1, 101):
if is_prime(num):
print(num, end=" ")
63. Write a function that returns the greatest common divisor (GCD) of two numbers.
python
import math print(math.gcd(48, 18))
64. Write a function that flattens a nested list like [[1,2],[3,4]] into [1,2,3,4].
python
def flatten(lst):
result = []
for item in lst:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
print(flatten([[1,2],[3,4]]))
65. Write a program that counts how many times a word appears in a string.
python
sentence = "the cat and the dog and the bird" word = "the" print(sentence.split().count(word))
66. Use set to find the symmetric difference between two sets {1,2,3} and {3,4,5}.
python
set1 = {1,2,3}
set2 = {3,4,5}
print(set1 ^ set2)
67. Write a function that returns the power set of a small set (optional, for practice).
python
def power_set(s):
from itertools import combinations
lst = list(s)
ps = []
for r in range(len(lst)+1):
ps.extend(combinations(lst, r))
return [set(x) for x in ps]
print(power_set({1,2,3}))
68. Write a program that simulates rolling a six‑sided die 10 times and prints results.
python
import random
for _ in range(10):
print(random.randint(1, 6))
69. Write a function that checks if a number is a perfect square.
python
import math
def is_perfect_square(n):
if n < 0:
return False
root = math.isqrt(n)
return root * root == n
print(is_perfect_square(16))
70. Write a program that removes all occurrences of a given element from a list.
python
def remove_all(lst, val):
return [x for x in lst if x != val]
print(remove_all([1,2,3,2,4,2], 2))
71. Write a function that returns the number of uppercase letters in a string.
python
def count_uppercase(s):
return sum(1 for ch in s if ch.isupper())
print(count_uppercase("Hello World"))
72. Write a program that prints the current date and time in “YYYY-MM-DD HH:MM:SS”.
python
from datetime import datetime
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
73. Write a program that asks the user to enter numbers until they type “quit” and then prints the sum.
python
total = 0
while True:
user_input = input("Enter a number (or 'quit'): ")
if user_input.lower() == 'quit':
break
total += float(user_input)
print("Sum:", total)
74. Write a function that returns the number of unique elements in a list.
python
def count_unique(lst):
return len(set(lst))
print(count_unique([1,2,2,3,3,3]))
75. Write a program that prints the first 10 numbers of the Fibonacci sequence using recursion.
python
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
for i in range(10):
print(fib(i), end=" ")
76. Write a program that checks if a list is sorted in ascending order.
python
def is_sorted(lst):
return all(lst[i] <= lst[i+1] for i in range(len(lst)-1))
print(is_sorted([1,2,3,4]))
77. Write a function that returns the most frequent element in a list.
python
from collections import Counter
def most_frequent(lst):
if not lst:
return None
return Counter(lst).most_common(1)[0][0]
print(most_frequent([1,2,2,3,3,3]))
78. Write a program that finds the intersection of two lists using list comprehension.
python
a = [1,2,3,4] b = [3,4,5,6] intersection = [x for x in a if x in b] print(intersection)
Also try it: 100 Dart practice problems with solutions
79. Write a function that returns the first non‑repeating character in a string.
python
def first_non_repeating(s):
from collections import Counter
count = Counter(s)
for ch in s:
if count[ch] == 1:
return ch
return None
print(first_non_repeating("swiss"))
80. Write a program that uses sys.argv to accept command line arguments and prints them.
python
import sys
print("Arguments:", sys.argv[1:])
81. Write a function that returns the factorial of a number using reduce.
python
from functools import reduce
def factorial_reduce(n):
return reduce(lambda x, y: x * y, range(1, n+1), 1)
print(factorial_reduce(5))
82. Write a program that downloads a webpage’s content using requests (if installed).
python
import requests
resp = requests.get("https://example.com")
print(resp.text[:200]) # first 200 chars
83. Write a function that removes all punctuation from a string (use string.punctuation).
python
import string
def remove_punctuation(s):
return ''.join(ch for ch in s if ch not in string.punctuation)
print(remove_punctuation("Hello, world!"))
84. Write a decorator that prints “Function called” before executing a function.
python
def decorator(func):
def wrapper(*args, **kwargs):
print("Function called")
return func(*args, **kwargs)
return wrapper
@decorator
def greet():
print("Hello")
greet()
85. Write a program that copies the contents of one file to another.
python
with open("source.txt", "r") as src:
with open("dest.txt", "w") as dest:
dest.write(src.read())
86. Write a function that splits a list into chunks of a given size.
python
def chunk_list(lst, chunk_size):
for i in range(0, len(lst), chunk_size):
yield lst[i:i+chunk_size]
print(list(chunk_list([1,2,3,4,5,6], 2)))
87. Write a program that calculates the sum of digits of a positive integer (e.g., 1234 -> 10).
python
num = 1234 digit_sum = sum(int(d) for d in str(num)) print(digit_sum)
88. Write a function that returns all permutations of a string (basic version).
python
from itertools import permutations
def permute_string(s):
return [''.join(p) for p in permutations(s)]
print(permute_string("abc")[:5])
89. Write a program that uses any and all to check list conditions.
python
nums = [2,4,6,8] print(all(x % 2 == 0 for x in nums)) print(any(x > 10 for x in nums))
90. Write a program that implements a simple online store using a dictionary of products and prices, then prints the total cost of a cart.
python
prices = {"apple": 0.5, "banana": 0.3, "cherry": 0.8}
cart = {"apple": 4, "banana": 6}
total = sum(prices[item] * qty for item, qty in cart.items())
print(total)
91. Write a function that returns the keys corresponding to a given value in a dictionary.
python
def get_keys_by_value(d, target):
return [k for k, v in d.items() if v == target]
print(get_keys_by_value({'a':1, 'b':2, 'c':1}, 1))
92. Write a program that finds all numbers in a given range (1-100) that are divisible by 5 or 7.
python
result = [x for x in range(1, 101) if x % 5 == 0 or x % 7 == 0] print(result)
93. Write a function that validates if a string is a valid email address (simple check).
python
import re
def is_valid_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
print(is_valid_email("test@example.com"))
94. Write a program that writes a list of strings to a file, one per line, then reads it back.
python
lines = ["first", "second", "third"]
with open("lines.txt", "w") as f:
f.write("\n".join(lines))
with open("lines.txt", "r") as f:
read_lines = f.read().splitlines()
print(read_lines)
95. Write a function that finds the mode of a list (most frequent value).
python
from collections import Counter
def mode(lst):
if not lst:
return None
return Counter(lst).most_common(1)[0][0]
96. Write a program that prints the current working directory and changes it to a new path.
python
import os
print("Current:", os.getcwd())
os.chdir("..")
print("New:", os.getcwd())
97. Write a function that returns the nth Fibonacci number using memoization.
python
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n <= 1:
return n
return fib_memo(n-1) + fib_memo(n-2)
print(fib_memo(10))
98. Write a context manager using with to create a temporary file that is automatically deleted.
python
import tempfile
import os
with tempfile.NamedTemporaryFile(mode='w', delete=True) as tmp:
tmp.write("temporary content")
print("File path:", tmp.name)
# file is deleted after exiting context
99. Write a program that uses hashing to store password hashes (simulate).
python
import hashlib password = "mysecret" hash_object = hashlib.sha256(password.encode()) print(hash_object.hexdigest())
100. Write a program that calculates the number of days between two dates.
python
from datetime import date d1 = date(2024, 1, 1) d2 = date(2024, 12, 31) delta = d2 - d1 print(delta.days)
Also try it: 100 Swift practice problems with solutions
Final Thoughts
That’s 100 Python problems — solved, understood, and behind you. Be proud. Every challenge sharpened your logic and built real coding confidence no tutorial alone can give. Bookmark this, revisit tough ones, and keep building. You’re not just learning Python anymore — you’re living it. Happy coding!