Python Programming · Practice by type
Python Programming Programs for Practice with Output
Practice programs for every Python Programming topic, each with a full solution, its real output and an explanation. Try writing each one yourself first.
- 250 questions
- 24 topics
- Answers checked on a real compiler
Python Basics and Syntax 10 questions
- Greet the user and print their age next year in Python Easy
- Simple interest calculator in Python Easy
- Area and circumference of a circle in Python Easy
- Swap two variables in Python Easy
- Celsius to Fahrenheit table in Python Easy
- Convert seconds to hours, minutes and seconds in Python Medium
- Sum and average of three numbers on one line in Python Medium
- Electricity bill with fixed charge and tax in Python Medium
- Multiplication table of a number in Python Easy
- Print initials and a username from a full name in Python Hard
Variables and Data Types 10 questions
- Detect whether input is an integer, a decimal or text in Python Medium
- Decimal to binary, octal and hexadecimal in Python Easy
- Sum and count of digits using arithmetic in Python Medium
- Factorial of a large number in Python Medium
- Roots of a quadratic equation, including complex roots, in Python Hard
- Distance between two points in Python Easy
- Split a bill equally in paise without rounding errors in Python Medium
- Convert body temperatures from Fahrenheit to Celsius in Python Easy
- Print a truthiness table of Python values Medium
- GST invoice with exact Decimal arithmetic in Python Hard
Operators and Expressions 10 questions
- Even or odd and power of two using bitwise operators in Python Easy
- Swap two numbers using XOR in Python Medium
- Simple calculator for + - * / // % ** in Python Medium
- Count the set bits of a number in Python Medium
- Reverse a number and check for a palindrome in Python Easy
- Check whether three sides form a triangle, and its type, in Python Medium
- Time difference between two clock times in Python Medium
- Compound interest with different compounding frequencies in Python Medium
- Sum numbers until 0 using the walrus operator in Python Hard
- Count leap years in a range in Python Easy
Conditional Statements 10 questions
- Grade and remark calculator in Python Easy
- Largest of three numbers in Python Easy
- Check whether a character is a vowel, consonant, digit or symbol in Python Easy
- Find the quadrant of a point with match-case in Python Medium
- Password strength checker in Python Medium
- ATM menu with match-case in Python Medium
- Day name and weekend check with match-case in Python Easy
- FizzBuzz from 1 to 15 in Python Easy
- Classify a triangle by its angles in Python Medium
- Shipping charge calculator with nested conditions in Python Hard
Loops 10 questions
- Fibonacci series in Python Easy
- GCD and LCM using the Euclidean algorithm in Python Medium
- Armstrong numbers between 100 and 999 in Python Medium
- Number pyramid pattern in Python Medium
- Floyd's triangle in Python Easy
- Collatz sequence in Python Medium
- Count vowels, consonants, digits and spaces in Python Easy
- Number guessing game with limited attempts in Python Medium
- Perfect numbers below 10,000 in Python Hard
- Multiplication grid with headers in Python Easy
Strings 10 questions
- Reverse the order of words and each word in Python Easy
- Check whether two strings are anagrams in Python Easy
- Character frequency in a string in Python Medium
- Caesar cipher encryption and decryption in Python Medium
- Remove duplicate characters keeping the first occurrence in Python Easy
- String compression (run-length encoding) in Python Medium
- Find the longest word in a sentence in Python Easy
- Convert snake_case to camelCase and back in Python Medium
- Simple email address validation with string methods in Python Hard
- Count words and unique words in a paragraph in Python Medium
Lists 10 questions
- Remove duplicates from a list keeping the order in Python Easy
- Rotate a list by k positions in Python Medium
- Merge two sorted lists in Python Medium
- Matrix addition and transpose with nested lists in Python Medium
- Find all pairs with a given sum in Python Medium
- Move all zeros to the end of a list in Python Medium
- Flatten a nested list in Python Hard
- Running total and 3-day moving average in Python Medium
- Rank students by marks then name in Python Medium
- Mean, median and mode of a list in Python Hard
Tuples 10 questions
- Rotate the values of three variables in Python Easy
- Return the lowest, highest and average marks as a tuple in Python Easy
- Sort student records stored as tuples in Python Medium
- Department payroll with namedtuple in Python Medium
- Split a list of pairs into two tuples in Python Medium
- Transpose a matrix stored as tuples in Python Medium
- Remove duplicates from a tuple keeping the order in Python Easy
- Find tuples whose elements are all divisible by k in Python Easy
- Track visited grid cells with tuple keys in Python Hard
- Sort and compare dates stored as tuples in Python Medium
Sets 10 questions
- Find the duplicate values in a list using sets in Python Easy
- Check whether a sentence is a pangram in Python Easy
- Common elements of three lists in Python Easy
- Find the missing numbers from 1 to n in Python Easy
- Check whether two numbers add up to a target using a set in Python Medium
- Jaccard similarity of two sentences in Python Medium
- First repeating and first non-repeating character in Python Medium
- Course enrolment report with set operations in Python Medium
- Words that appear in only one of two texts in Python Easy
- Match candidates to job requirements with subsets in Python Hard
Dictionaries 10 questions
- Word frequency sorted by count in Python Easy
- Invert a dictionary, grouping keys with the same value in Python Medium
- Merge two dictionaries adding the values of common keys in Python Medium
- Group words by their first letter with defaultdict in Python Easy
- Phone book with add, find, delete and list commands in Python Medium
- Top three scorers from a dictionary in Python Easy
- Two Sum: indices of two numbers adding to a target in Python Medium
- Inventory valuation with nested dictionaries in Python Medium
- Group anagrams together using a dictionary in Python Hard
- First non-repeating character using a dictionary in Python Medium
Functions 10 questions
- Prime number checker function in Python Easy
- Factorial, nPr and nCr functions in Python Easy
- Temperature converter with keyword arguments in Python Medium
- Average of any number of values with *args in Python Medium
- Function returning summary statistics as a dictionary in Python Easy
- Build an HTML tag with **kwargs attributes in Python Medium
- Counter with a closure and nonlocal in Python Medium
- Validate and format phone numbers with a function in Python Medium
- Calculator using a dictionary of functions in Python Medium
- Loan EMI calculator function in Python Hard
Recursion 10 questions
- Factorial: recursive and iterative versions in Python Easy
- Fibonacci with a memo dictionary in Python Medium
- All permutations of a string recursively in Python Medium
- Recursive binary search with step count in Python Medium
- Flatten a deeply nested list recursively in Python Medium
- Generate all subsets (power set) recursively in Python Medium
- Digital root of a number recursively in Python Easy
- Check a palindrome recursively in Python Easy
- Ways to climb stairs with 1, 2 or 3 steps in Python Hard
- Merge sort with a count of merges in Python Hard
Lambda Functions 10 questions
- Sort employees by department, salary and name with a lambda in Python Easy
- Prices with GST above a limit using map and filter in Python Easy
- Product, maximum and joined string with reduce in Python Medium
- Unit converter with a dictionary of lambdas in Python Medium
- Multiplication tables with closures in Python Medium
- Sort a dictionary by value (descending) then key in Python Easy
- Sort numbers by number of 1-bits in Python Medium
- Group records with itertools.groupby and a lambda in Python Hard
- Compose several functions into one with lambdas in Python Hard
- Apply the best discount rule with a list of lambdas in Python Medium
List Comprehensions 10 questions
- FizzBuzz in a single list comprehension in Python Easy
- Primes below 60 with a comprehension and all() in Python Medium
- Matrix multiplication with comprehensions in Python Hard
- Word lengths and long words with comprehensions in Python Easy
- Flatten nested tags and remove duplicates in Python Medium
- Parse CSV text into dictionaries with comprehensions in Python Medium
- Character frequency with a dict comprehension in Python Easy
- Identity matrix and symmetric check with comprehensions in Python Medium
- Statistics over a large range with generator expressions in Python Medium
- Pythagorean triples with a given perimeter using comprehensions in Python Hard
Modules and Packages 10 questions
- Create and use your own module in Python Easy
- Create a package with sub-modules and __init__.py in Python Medium
- Days left until exams with datetime in Python Easy
- Word statistics with collections.Counter in Python Easy
- Match fixtures and team pairings with itertools in Python Medium
- Save and load student records as JSON in Python Medium
- Geometry calculator with the math module in Python Easy
- Inspect a module: list its public functions in Python Medium
- Which file does an import load? sys.path and __file__ in Python Hard
- Optional imports with a fallback in Python Medium
Exception Handling 10 questions
- Keep asking until a valid integer is entered in Python Easy
- Safe division of value pairs with error reporting in Python Easy
- Bank account with a custom InsufficientBalance exception in Python Medium
- Validate a registration form and collect all errors in Python Medium
- Parse configuration lines and report bad ones in Python Medium
- Retry a failing operation a limited number of times in Python Hard
- Wrap low-level errors in a domain exception with raise from in Python Hard
- A context manager that logs and suppresses errors in Python Hard
- Evaluate simple expressions and report every kind of error in Python Medium
- Guarantee clean-up with finally in Python Medium
File Handling 10 questions
- Write marks to a file and compute the average in Python Easy
- Count lines, words and characters of a file in Python Easy
- Append timestamped entries to a log file in Python Medium
- Copy a file adding line numbers in Python Easy
- Find the lines containing a word in a file in Python Medium
- Read a CSV file and compute totals per category in Python Medium
- Load, update and save a JSON settings file in Python Medium
- Merge two files of names into one sorted, duplicate-free file in Python Medium
- Copy a binary file in chunks and verify it in Python Hard
- Summarise the files in a folder with pathlib in Python Medium
OOP in Python 10 questions
- Bank account class with deposit, withdraw and statement in Python Easy
- Rectangle class with validated and computed properties in Python Medium
- Student report card class in Python Easy
- Auto-incrementing IDs with a class attribute in Python Medium
- Temperature class with Celsius, Fahrenheit and Kelvin properties in Python Medium
- Shopping cart class with dunder methods in Python Medium
- Vector class with equality, length and string form in Python Medium
- Employee records with a classmethod constructor and a staticmethod in Python Medium
- Sort objects with an ordered dataclass in Python Hard
- Parking lot system with classes in Python Hard
Inheritance and Polymorphism 10 questions
- Payroll with Employee, Manager and Intern classes in Python Easy
- Shape hierarchy with an abstract base class in Python Medium
- Vehicle rental cost with polymorphism in Python Easy
- Fraction class with operator overloading in Python Hard
- Savings and current accounts with overridden withdraw rules in Python Medium
- Send notifications through different channels with duck typing in Python Easy
- Multilevel inheritance: Person, Employee, Manager in Python Medium
- Add JSON and comparison abilities with mixins in Python Hard
- Full comparisons from __eq__ and __lt__ with total_ordering in Python Medium
- Game characters with an abstract attack() in Python Medium
Iterators and Generators 10 questions
- A float range iterator class in Python Medium
- Fibonacci numbers with a generator in Python Easy
- Read a large CSV file lazily with a generator in Python Medium
- Split data into batches with a generator in Python Medium
- An infinite prime number generator in Python Hard
- A data cleaning pipeline built from generators in Python Medium
- Flatten any nested structure with yield from in Python Medium
- A running average coroutine with send() in Python Hard
- Moving averages with a sliding window generator in Python Medium
- Round-robin scheduling of several iterators in Python Hard
Decorators 10 questions
- A call logger decorator showing arguments and results in Python Easy
- A retry decorator with a configurable number of attempts in Python Medium
- A decorator that validates numeric arguments in Python Medium
- Write your own memoize decorator in Python Medium
- A call-limit (rate limit) decorator in Python Medium
- Wrap output in HTML tags with stacked decorators in Python Easy
- A plugin registry built with a decorator in Python Medium
- Check argument types from annotations with a decorator in Python Hard
- Trace recursive calls with indentation using a decorator in Python Hard
- A class decorator that makes a singleton in Python Hard
Regular Expressions 10 questions
- Extract and group email addresses by domain in Python Easy
- Validate and normalise Indian mobile numbers with regex in Python Medium
- Mask credit card numbers in text with regex in Python Medium
- Extract hashtags and mentions from posts in Python Easy
- Convert dates in several formats to ISO format with regex in Python Hard
- Parse key = value configuration lines with regex in Python Medium
- Word frequency ignoring punctuation with regex in Python Easy
- Tokenise an arithmetic expression with regex in Python Hard
- Find and remove repeated words with a backreference in Python Medium
- Password strength report with individual regex checks in Python Medium
Python Built-in Functions 10 questions
- Sentence statistics using only built-ins in Python Easy
- Transpose a table and compute column totals with zip in Python Medium
- Top 3 products by revenue with sorted() in Python Easy
- Remove duplicates keeping order, case-insensitively, in Python Medium
- Number base converter with bin, oct, hex and int in Python Easy
- Validate form fields with all() and any() in Python Medium
- Day-to-day changes with zip in Python Medium
- Most frequent item with max() and a key in Python Easy
- Caesar cipher with chr() and ord() in Python Medium
- Attendance report with enumerate, zip and sum in Python Medium
Python Coding Interview Questions 20 questions
- Valid parentheses using a stack in Python Easy
- Longest substring without repeating characters in Python Medium
- Maximum subarray sum with indices (Kadane) in Python Medium
- Product of array except self without division in Python Hard
- Longest common prefix of a list of strings in Python Easy
- Find the duplicate and the missing number in Python Medium
- Rotate an array in place with the reversal trick in Python Medium
- Palindrome after deleting at most one character in Python Hard
- Count-and-say sequence with run-length grouping in Python Medium
- Merge overlapping intervals in Python Medium
- Implement an LRU cache with OrderedDict in Python Medium
- Top k frequent elements with Counter and heapq in Python Medium
- Reverse a singly linked list in Python Medium
- Detect a cycle in a linked list (Floyd's algorithm) in Python Hard
- Binary tree level-order traversal and maximum depth in Python Medium
- Shortest path in a grid with obstacles using BFS in Python Hard
- K-th largest element using a size-k min-heap in Python Medium
- Spiral order traversal of a matrix in Python Medium
- Minimum coins for an amount (coin change) with DP in Python Hard
- Longest increasing subsequence in O(n log n) with bisect in Python Hard
Ready to test your Programming?
Timed online tests with instant scores and explanations.