Python Practice Questions: 30 Exercises with Answers
You learn Python by writing small programs and checking what they print. These 30 Python practice questions go from your first print() to classes, generators and decorators. Every answer was run in Python 3.12 and its exact output is shown, so you can compare your result line by line. Open any answer in the free browser playground with one click. No sign-up, nothing to install.
हिन्दी में समझें
यहाँ 30 Python अभ्यास प्रश्न हैं, आसान से कठिन तक। हर प्रश्न का उत्तर और उसका असली output दिया गया है। "Run in playground" दबाकर कोड अपने ब्राउज़र में चलाइए। कोई लॉगिन या इंस्टॉल नहीं।
Before you start
- The playground runs real Python 3 in your browser. The first run downloads the engine and needs internet.
- Use fixed sample values instead of
input(); that is how every answer here is written. - Try each question for a few minutes before opening the hint, and open the answer only after you have run your own code.
Beginner Python practice questions
Covers print, variables, maths, if/else, loops, lists, strings and splitting text.
1Print the message Hello, Excel Keys! on the screen.
स्क्रीन पर Hello, Excel Keys! प्रिंट करें।
Hint
Use print() with the text in quotes.
2Store a product name and its price in two variables, then print them in one sentence.
product का नाम और price दो variables में रखें और एक वाक्य में प्रिंट करें।
Hint
An f-string puts variables inside text: f"{name} costs {price}".
Show answer and output
name = "Keyboard"
price = 1200
print(f"{name} costs {price}")Output
Keyboard costs 1200Run in playground →
3Calculate the total bill for 3 notebooks at 45 each, plus 18% tax. Round to 2 decimals.
45 वाले 3 notebooks का बिल 18% tax के साथ निकालें (2 decimal तक)।
Hint
Multiply first, then multiply by 1.18 and use round(value, 2).
Show answer and output
qty = 3
rate = 45
subtotal = qty * rate
total = round(subtotal * 1.18, 2)
print("Subtotal:", subtotal)
print("Total with tax:", total)Output
Subtotal: 135 Total with tax: 159.3Run in playground →
4Check whether a sales figure of 82,000 met a target of 75,000 and print "Target met" or "Target missed".
देखें कि 82,000 की sales ने 75,000 का target पूरा किया या नहीं।
Hint
Use if ... else with the >= operator.
Show answer and output
sales = 82000
target = 75000
if sales >= target:
print("Target met")
else:
print("Target missed")Output
Target metRun in playground →
5Give a grade for a score of 67: A for 80+, B for 60 to 79, otherwise C.
67 score का grade दें: 80+ A, 60 से 79 B, बाकी C।
Hint
Use if, elif and else, checking the highest band first.
Show answer and output
score = 67
if score >= 80:
grade = "A"
elif score >= 60:
grade = "B"
else:
grade = "C"
print("Grade:", grade)Output
Grade: BRun in playground →
6From the list of monthly sales [120, 95, 140, 110], print the highest, the lowest and the average.
monthly sales की list से highest, lowest और average निकालें।
Hint
max(), min(), sum() and len() all work on lists.
Show answer and output
sales = [120, 95, 140, 110]
print("Highest:", max(sales))
print("Lowest:", min(sales))
print("Average:", sum(sales) / len(sales))Output
Highest: 140 Lowest: 95 Average: 116.25Run in playground →
7Turn the name " asha VERMA " into "Asha Verma".
" asha VERMA " को "Asha Verma" में बदलें।
Hint
strip() removes spaces at the ends; title() capitalises each word.
Show answer and output
raw = " asha VERMA "
clean = raw.strip().title()
print(clean)Output
Asha VermaRun in playground →
8Print the multiplication table of 7 from 7 x 1 to 7 x 5.
7 का पहाड़ा 7 x 1 से 7 x 5 तक प्रिंट करें।
Hint
Loop over range(1, 6) and print with an f-string.
Show answer and output
for i in range(1, 6):
print(f"7 x {i} = {7 * i}")Output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35Run in playground →
9Print a numbered list of tasks starting from 1.
tasks की numbered list 1 से शुरू करके प्रिंट करें।
Hint
enumerate(list, start=1) gives a counter and the item.
Show answer and output
tasks = ["Download data", "Clean columns", "Build pivot"]
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task}")Output
1. Download data 2. Clean columns 3. Build pivotRun in playground →
10Split the CSV line "Asha,Delhi,52000" into fields and print each with a label.
CSV लाइन को fields में तोड़कर हर field label के साथ प्रिंट करें।
Hint
split(",") returns a list; unpack it into three variables.
Show answer and output
line = "Asha,Delhi,52000"
name, city, salary = line.split(",")
print("Name:", name)
print("City:", city)
print("Salary:", int(salary))Output
Name: Asha City: Delhi Salary: 52000Run in playground →
Intermediate Python practice questions
Covers Functions, dictionaries, list comprehensions, sorting with key, zip, sets and try/except.
11Write a function percent(part, whole) that returns the percentage rounded to 1 decimal. Test it with 45 of 60.
percent(part, whole) function बनाएँ जो 1 decimal तक प्रतिशत लौटाए।
Hint
Use def, return and round().
Show answer and output
def percent(part, whole):
return round(part / whole * 100, 1)
print(percent(45, 60))Output
75.0Run in playground →
12Store region-wise sales in a dictionary and print each region with its sales.
region-wise sales को dictionary में रखें और हर region प्रिंट करें।
Hint
Loop with for region, value in data.items().
Show answer and output
sales = {"North": 520, "South": 430, "West": 610}
for region, value in sales.items():
print(f"{region}: {value}")Output
North: 520 South: 430 West: 610Run in playground →
13Find the region with the highest sales in {"North": 520, "South": 430, "West": 610}.
सबसे ज़्यादा sales वाला region खोजें।
Hint
max(data, key=data.get) returns the key with the largest value.
Show answer and output
sales = {"North": 520, "South": 430, "West": 610}
best = max(sales, key=sales.get)
print(best, sales[best])Output
West 610Run in playground →
14Count how many times each status appears in ["paid", "pending", "paid", "cancelled", "paid"].
हर status कितनी बार आया, गिनें।
Hint
Use a dictionary with dict.get(key, 0) + 1.
Show answer and output
statuses = ["paid", "pending", "paid", "cancelled", "paid"]
counts = {}
for s in statuses:
counts[s] = counts.get(s, 0) + 1
print(counts)Output
{'paid': 3, 'pending': 1, 'cancelled': 1}Run in playground →15Make a new list with the square of every number from 1 to 6, using one line.
1 से 6 तक के हर number का square एक लाइन में list बनाएँ।
Hint
A list comprehension: [n * n for n in ...].
Show answer and output
squares = [n * n for n in range(1, 7)]
print(squares)Output
[1, 4, 9, 16, 25, 36]Run in playground →
16From [1200, 450, 3100, 980, 2600], keep only the orders above 1000.
1000 से बड़े orders ही रखें।
Hint
Add an if condition inside a list comprehension.
Show answer and output
orders = [1200, 450, 3100, 980, 2600]
big = [x for x in orders if x > 1000]
print(big)Output
[1200, 3100, 2600]Run in playground →
17Sort these employees by salary, highest first, and print name and salary.
employees को salary के अनुसार (सबसे ज़्यादा पहले) sort करें।
Hint
sorted(list, key=lambda e: e[1], reverse=True).
Show answer and output
employees = [("Tara", 90000), ("Om", 70000), ("Ira", 80000), ("Dev", 60000)]
for name, salary in sorted(employees, key=lambda e: e[1], reverse=True):
print(name, salary)Output
Tara 90000 Ira 80000 Om 70000 Dev 60000Run in playground →
18Pair each month with its sales and print them together.
हर month को उसकी sales के साथ जोड़कर प्रिंट करें।
Hint
zip() walks two lists side by side.
Show answer and output
months = ["Jan", "Feb", "Mar"]
sales = [120, 95, 140]
for m, s in zip(months, sales):
print(m, s)Output
Jan 120 Feb 95 Mar 140Run in playground →
19Find the customers who bought in both January and February.
जिन customers ने January और February दोनों में खरीदा, उन्हें खोजें।
Hint
Turn both lists into sets and use &.
Show answer and output
jan = {"Asha", "Ravi", "Neha", "Kabir"}
feb = {"Ravi", "Meera", "Neha"}
print(sorted(jan & feb))Output
['Neha', 'Ravi']Run in playground →
20Convert the text values ["120", "abc", "75"] to numbers, skipping anything that is not a number.
text values को number में बदलें, जो number नहीं है उसे छोड़ दें।
Hint
Wrap int() in try/except ValueError.
Show answer and output
values = ["120", "abc", "75"]
numbers = []
for v in values:
try:
numbers.append(int(v))
except ValueError:
print("Skipped:", v)
print(numbers)Output
Skipped: abc [120, 75]Run in playground →
Advanced Python practice questions
Covers Classes, Counter, defaultdict, dates, JSON, generators, regular expressions, dataclasses, recursion and decorators.
21Create an Employee class with a name and salary, and a method that returns the salary after a 10% raise.
Employee class बनाएँ जिसमें 10% raise के बाद salary लौटाने वाला method हो।
Hint
Define __init__ to store values and a method that uses self.
Show answer and output
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def with_raise(self, pct=10):
return round(self.salary * (1 + pct / 100))
emp = Employee("Ira", 80000)
print(emp.name, emp.with_raise())Output
Ira 88000Run in playground →
22Count the words in a sentence and show the two most common ones.
एक वाक्य के शब्द गिनें और सबसे ज़्यादा आने वाले दो शब्द दिखाएँ।
Hint
collections.Counter has a most_common() method.
Show answer and output
from collections import Counter
text = "data beats opinion and clean data beats messy data"
counts = Counter(text.split())
print(counts.most_common(2))Output
[('data', 3), ('beats', 2)]Run in playground →23Group these orders by region and add up the amount for each region.
orders को region के अनुसार group करके हर region का total निकालें।
Hint
collections.defaultdict(int) starts every new key at 0.
Show answer and output
from collections import defaultdict
orders = [("North", 200), ("South", 150), ("North", 300), ("West", 120), ("South", 80)]
totals = defaultdict(int)
for region, amount in orders:
totals[region] += amount
print(dict(totals))Output
{'North': 500, 'South': 230, 'West': 120}Run in playground →24Calculate how many days are between 2026-01-15 and 2026-03-01.
2026-01-15 और 2026-03-01 के बीच कितने दिन हैं, निकालें।
Hint
Subtract two datetime.date objects and read .days.
Show answer and output
from datetime import date
start = date(2026, 1, 15)
end = date(2026, 3, 1)
print((end - start).days)Output
45Run in playground →
25Convert a Python dictionary to JSON text and read it back.
Python dictionary को JSON text में बदलें और वापस पढ़ें।
Hint
json.dumps() writes text; json.loads() reads it.
Show answer and output
import json
report = {"month": "Jan", "sales": 520, "regions": ["North", "West"]}
text = json.dumps(report)
print(text)
back = json.loads(text)
print(back["regions"][1])Output
{"month": "Jan", "sales": 520, "regions": ["North", "West"]}
WestRun in playground →26Write a generator that yields running totals of [100, 250, 75, 300].
[100, 250, 75, 300] के running totals देने वाला generator लिखें।
Hint
A function with yield returns values one at a time.
Show answer and output
def running_total(values):
total = 0
for v in values:
total += v
yield total
print(list(running_total([100, 250, 75, 300])))Output
[100, 350, 425, 725]Run in playground →
27Find every email address in a block of text.
text में से सारे email address निकालें।
Hint
Use re.findall() with a simple email pattern.
Show answer and output
import re
text = "Contact asha@example.com or sales@example.org for the report."
emails = re.findall(r"[\w.]+@[\w.]+\.\w+", text)
print(emails)Output
['asha@example.com', 'sales@example.org']Run in playground →
28Use a dataclass to store products and print the total stock value (price x quantity).
dataclass से products रखें और कुल stock value निकालें।
Hint
@dataclass writes __init__ for you; then sum price * qty.
Show answer and output
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
qty: int
stock = [Product("Keyboard", 1200, 4), Product("Mouse", 600, 10), Product("Notebook", 100, 25)]
value = sum(p.price * p.qty for p in stock)
print(f"Total stock value: {value}")Output
Total stock value: 13300Run in playground →
29Write a recursive function that returns the factorial of 6.
6 का factorial निकालने वाला recursive function लिखें।
Hint
A recursive function calls itself with a smaller number until it reaches 1.
Show answer and output
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(6))Output
720Run in playground →
30Write a decorator that prints the name of a function every time it runs.
ऐसा decorator लिखें जो हर बार function का नाम प्रिंट करे।
Hint
A decorator takes a function and returns a wrapper function.
Show answer and output
def log_call(func):
def wrapper(*args):
print("Running", func.__name__)
return func(*args)
return wrapper
@log_call
def add_tax(amount):
return round(amount * 1.18, 2)
print(add_tax(500))Output
Running add_tax 590.0Run in playground →
How to get the most from these exercises
- Type the code yourself instead of copying it. Typing builds memory for the syntax.
- Predict the output before you press Run, then compare.
- Change one value (a number, a list item, a condition) and predict again.
- When you get an error, read the last line first: it names the problem.
- Finished all 30? Take the free Python course and its final test to earn a completion certificate, then try the 30 SQL practice exercises.
Python practice FAQ
Where can I practise Python online for free?
On this page. Read a question, write your code, then open it in the free Excel Keys Python playground. It runs real Python (Pyodide) inside your browser, so there is nothing to install and no sign-up. The first run downloads the Python engine, so it needs an internet connection.
Are these Python practice questions good for beginners?
Yes. The first ten use only print, variables, maths, if/else, loops, lists and strings. The next ten add functions, dictionaries, comprehensions, sorting, sets and error handling. The last ten cover classes, collections, dates, JSON, generators, regular expressions, dataclasses, recursion and decorators.
Which Python version do the answers use?
Every answer was run in Python 3.12 through Pyodide, the same engine used by the browser playground, and the output shown under each answer is the exact output of that run.
Why are the examples about sales, targets and employees?
Because most people who learn Python for work want to automate reports and analyse data. The same ideas apply to any data you work with.
Can I get a certificate?
Yes. Finish the free 32-lesson Python course and its final test in LearnLab to download an Excel Keys completion certificate. It is a self-paced completion certificate, not an accredited qualification.
References & corrections
For full language rules, use the official Python tutorial and the Python standard library reference. Found a mistake? Tell us with the question number.