LearnFrenzy
Sign in Take a free test

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

  1. Greet the user and print their age next year in Python Easy
  2. Simple interest calculator in Python Easy
  3. Area and circumference of a circle in Python Easy
  4. Swap two variables in Python Easy
  5. Celsius to Fahrenheit table in Python Easy
  6. Convert seconds to hours, minutes and seconds in Python Medium
  7. Sum and average of three numbers on one line in Python Medium
  8. Electricity bill with fixed charge and tax in Python Medium
  9. Multiplication table of a number in Python Easy
  10. Print initials and a username from a full name in Python Hard

Variables and Data Types 10 questions

  1. Detect whether input is an integer, a decimal or text in Python Medium
  2. Decimal to binary, octal and hexadecimal in Python Easy
  3. Sum and count of digits using arithmetic in Python Medium
  4. Factorial of a large number in Python Medium
  5. Roots of a quadratic equation, including complex roots, in Python Hard
  6. Distance between two points in Python Easy
  7. Split a bill equally in paise without rounding errors in Python Medium
  8. Convert body temperatures from Fahrenheit to Celsius in Python Easy
  9. Print a truthiness table of Python values Medium
  10. GST invoice with exact Decimal arithmetic in Python Hard

Operators and Expressions 10 questions

  1. Even or odd and power of two using bitwise operators in Python Easy
  2. Swap two numbers using XOR in Python Medium
  3. Simple calculator for + - * / // % ** in Python Medium
  4. Count the set bits of a number in Python Medium
  5. Reverse a number and check for a palindrome in Python Easy
  6. Check whether three sides form a triangle, and its type, in Python Medium
  7. Time difference between two clock times in Python Medium
  8. Compound interest with different compounding frequencies in Python Medium
  9. Sum numbers until 0 using the walrus operator in Python Hard
  10. Count leap years in a range in Python Easy

Conditional Statements 10 questions

  1. Grade and remark calculator in Python Easy
  2. Largest of three numbers in Python Easy
  3. Check whether a character is a vowel, consonant, digit or symbol in Python Easy
  4. Find the quadrant of a point with match-case in Python Medium
  5. Password strength checker in Python Medium
  6. ATM menu with match-case in Python Medium
  7. Day name and weekend check with match-case in Python Easy
  8. FizzBuzz from 1 to 15 in Python Easy
  9. Classify a triangle by its angles in Python Medium
  10. Shipping charge calculator with nested conditions in Python Hard

Loops 10 questions

  1. Fibonacci series in Python Easy
  2. GCD and LCM using the Euclidean algorithm in Python Medium
  3. Armstrong numbers between 100 and 999 in Python Medium
  4. Number pyramid pattern in Python Medium
  5. Floyd's triangle in Python Easy
  6. Collatz sequence in Python Medium
  7. Count vowels, consonants, digits and spaces in Python Easy
  8. Number guessing game with limited attempts in Python Medium
  9. Perfect numbers below 10,000 in Python Hard
  10. Multiplication grid with headers in Python Easy

Strings 10 questions

  1. Reverse the order of words and each word in Python Easy
  2. Check whether two strings are anagrams in Python Easy
  3. Character frequency in a string in Python Medium
  4. Caesar cipher encryption and decryption in Python Medium
  5. Remove duplicate characters keeping the first occurrence in Python Easy
  6. String compression (run-length encoding) in Python Medium
  7. Find the longest word in a sentence in Python Easy
  8. Convert snake_case to camelCase and back in Python Medium
  9. Simple email address validation with string methods in Python Hard
  10. Count words and unique words in a paragraph in Python Medium

Lists 10 questions

  1. Remove duplicates from a list keeping the order in Python Easy
  2. Rotate a list by k positions in Python Medium
  3. Merge two sorted lists in Python Medium
  4. Matrix addition and transpose with nested lists in Python Medium
  5. Find all pairs with a given sum in Python Medium
  6. Move all zeros to the end of a list in Python Medium
  7. Flatten a nested list in Python Hard
  8. Running total and 3-day moving average in Python Medium
  9. Rank students by marks then name in Python Medium
  10. Mean, median and mode of a list in Python Hard

Tuples 10 questions

  1. Rotate the values of three variables in Python Easy
  2. Return the lowest, highest and average marks as a tuple in Python Easy
  3. Sort student records stored as tuples in Python Medium
  4. Department payroll with namedtuple in Python Medium
  5. Split a list of pairs into two tuples in Python Medium
  6. Transpose a matrix stored as tuples in Python Medium
  7. Remove duplicates from a tuple keeping the order in Python Easy
  8. Find tuples whose elements are all divisible by k in Python Easy
  9. Track visited grid cells with tuple keys in Python Hard
  10. Sort and compare dates stored as tuples in Python Medium

Sets 10 questions

  1. Find the duplicate values in a list using sets in Python Easy
  2. Check whether a sentence is a pangram in Python Easy
  3. Common elements of three lists in Python Easy
  4. Find the missing numbers from 1 to n in Python Easy
  5. Check whether two numbers add up to a target using a set in Python Medium
  6. Jaccard similarity of two sentences in Python Medium
  7. First repeating and first non-repeating character in Python Medium
  8. Course enrolment report with set operations in Python Medium
  9. Words that appear in only one of two texts in Python Easy
  10. Match candidates to job requirements with subsets in Python Hard

Dictionaries 10 questions

  1. Word frequency sorted by count in Python Easy
  2. Invert a dictionary, grouping keys with the same value in Python Medium
  3. Merge two dictionaries adding the values of common keys in Python Medium
  4. Group words by their first letter with defaultdict in Python Easy
  5. Phone book with add, find, delete and list commands in Python Medium
  6. Top three scorers from a dictionary in Python Easy
  7. Two Sum: indices of two numbers adding to a target in Python Medium
  8. Inventory valuation with nested dictionaries in Python Medium
  9. Group anagrams together using a dictionary in Python Hard
  10. First non-repeating character using a dictionary in Python Medium

Functions 10 questions

  1. Prime number checker function in Python Easy
  2. Factorial, nPr and nCr functions in Python Easy
  3. Temperature converter with keyword arguments in Python Medium
  4. Average of any number of values with *args in Python Medium
  5. Function returning summary statistics as a dictionary in Python Easy
  6. Build an HTML tag with **kwargs attributes in Python Medium
  7. Counter with a closure and nonlocal in Python Medium
  8. Validate and format phone numbers with a function in Python Medium
  9. Calculator using a dictionary of functions in Python Medium
  10. Loan EMI calculator function in Python Hard

Recursion 10 questions

  1. Factorial: recursive and iterative versions in Python Easy
  2. Fibonacci with a memo dictionary in Python Medium
  3. All permutations of a string recursively in Python Medium
  4. Recursive binary search with step count in Python Medium
  5. Flatten a deeply nested list recursively in Python Medium
  6. Generate all subsets (power set) recursively in Python Medium
  7. Digital root of a number recursively in Python Easy
  8. Check a palindrome recursively in Python Easy
  9. Ways to climb stairs with 1, 2 or 3 steps in Python Hard
  10. Merge sort with a count of merges in Python Hard

Lambda Functions 10 questions

  1. Sort employees by department, salary and name with a lambda in Python Easy
  2. Prices with GST above a limit using map and filter in Python Easy
  3. Product, maximum and joined string with reduce in Python Medium
  4. Unit converter with a dictionary of lambdas in Python Medium
  5. Multiplication tables with closures in Python Medium
  6. Sort a dictionary by value (descending) then key in Python Easy
  7. Sort numbers by number of 1-bits in Python Medium
  8. Group records with itertools.groupby and a lambda in Python Hard
  9. Compose several functions into one with lambdas in Python Hard
  10. Apply the best discount rule with a list of lambdas in Python Medium

List Comprehensions 10 questions

  1. FizzBuzz in a single list comprehension in Python Easy
  2. Primes below 60 with a comprehension and all() in Python Medium
  3. Matrix multiplication with comprehensions in Python Hard
  4. Word lengths and long words with comprehensions in Python Easy
  5. Flatten nested tags and remove duplicates in Python Medium
  6. Parse CSV text into dictionaries with comprehensions in Python Medium
  7. Character frequency with a dict comprehension in Python Easy
  8. Identity matrix and symmetric check with comprehensions in Python Medium
  9. Statistics over a large range with generator expressions in Python Medium
  10. Pythagorean triples with a given perimeter using comprehensions in Python Hard

Modules and Packages 10 questions

  1. Create and use your own module in Python Easy
  2. Create a package with sub-modules and __init__.py in Python Medium
  3. Days left until exams with datetime in Python Easy
  4. Word statistics with collections.Counter in Python Easy
  5. Match fixtures and team pairings with itertools in Python Medium
  6. Save and load student records as JSON in Python Medium
  7. Geometry calculator with the math module in Python Easy
  8. Inspect a module: list its public functions in Python Medium
  9. Which file does an import load? sys.path and __file__ in Python Hard
  10. Optional imports with a fallback in Python Medium

Exception Handling 10 questions

  1. Keep asking until a valid integer is entered in Python Easy
  2. Safe division of value pairs with error reporting in Python Easy
  3. Bank account with a custom InsufficientBalance exception in Python Medium
  4. Validate a registration form and collect all errors in Python Medium
  5. Parse configuration lines and report bad ones in Python Medium
  6. Retry a failing operation a limited number of times in Python Hard
  7. Wrap low-level errors in a domain exception with raise from in Python Hard
  8. A context manager that logs and suppresses errors in Python Hard
  9. Evaluate simple expressions and report every kind of error in Python Medium
  10. Guarantee clean-up with finally in Python Medium

File Handling 10 questions

  1. Write marks to a file and compute the average in Python Easy
  2. Count lines, words and characters of a file in Python Easy
  3. Append timestamped entries to a log file in Python Medium
  4. Copy a file adding line numbers in Python Easy
  5. Find the lines containing a word in a file in Python Medium
  6. Read a CSV file and compute totals per category in Python Medium
  7. Load, update and save a JSON settings file in Python Medium
  8. Merge two files of names into one sorted, duplicate-free file in Python Medium
  9. Copy a binary file in chunks and verify it in Python Hard
  10. Summarise the files in a folder with pathlib in Python Medium

OOP in Python 10 questions

  1. Bank account class with deposit, withdraw and statement in Python Easy
  2. Rectangle class with validated and computed properties in Python Medium
  3. Student report card class in Python Easy
  4. Auto-incrementing IDs with a class attribute in Python Medium
  5. Temperature class with Celsius, Fahrenheit and Kelvin properties in Python Medium
  6. Shopping cart class with dunder methods in Python Medium
  7. Vector class with equality, length and string form in Python Medium
  8. Employee records with a classmethod constructor and a staticmethod in Python Medium
  9. Sort objects with an ordered dataclass in Python Hard
  10. Parking lot system with classes in Python Hard

Inheritance and Polymorphism 10 questions

  1. Payroll with Employee, Manager and Intern classes in Python Easy
  2. Shape hierarchy with an abstract base class in Python Medium
  3. Vehicle rental cost with polymorphism in Python Easy
  4. Fraction class with operator overloading in Python Hard
  5. Savings and current accounts with overridden withdraw rules in Python Medium
  6. Send notifications through different channels with duck typing in Python Easy
  7. Multilevel inheritance: Person, Employee, Manager in Python Medium
  8. Add JSON and comparison abilities with mixins in Python Hard
  9. Full comparisons from __eq__ and __lt__ with total_ordering in Python Medium
  10. Game characters with an abstract attack() in Python Medium

Iterators and Generators 10 questions

  1. A float range iterator class in Python Medium
  2. Fibonacci numbers with a generator in Python Easy
  3. Read a large CSV file lazily with a generator in Python Medium
  4. Split data into batches with a generator in Python Medium
  5. An infinite prime number generator in Python Hard
  6. A data cleaning pipeline built from generators in Python Medium
  7. Flatten any nested structure with yield from in Python Medium
  8. A running average coroutine with send() in Python Hard
  9. Moving averages with a sliding window generator in Python Medium
  10. Round-robin scheduling of several iterators in Python Hard

Decorators 10 questions

  1. A call logger decorator showing arguments and results in Python Easy
  2. A retry decorator with a configurable number of attempts in Python Medium
  3. A decorator that validates numeric arguments in Python Medium
  4. Write your own memoize decorator in Python Medium
  5. A call-limit (rate limit) decorator in Python Medium
  6. Wrap output in HTML tags with stacked decorators in Python Easy
  7. A plugin registry built with a decorator in Python Medium
  8. Check argument types from annotations with a decorator in Python Hard
  9. Trace recursive calls with indentation using a decorator in Python Hard
  10. A class decorator that makes a singleton in Python Hard

Regular Expressions 10 questions

  1. Extract and group email addresses by domain in Python Easy
  2. Validate and normalise Indian mobile numbers with regex in Python Medium
  3. Mask credit card numbers in text with regex in Python Medium
  4. Extract hashtags and mentions from posts in Python Easy
  5. Convert dates in several formats to ISO format with regex in Python Hard
  6. Parse key = value configuration lines with regex in Python Medium
  7. Word frequency ignoring punctuation with regex in Python Easy
  8. Tokenise an arithmetic expression with regex in Python Hard
  9. Find and remove repeated words with a backreference in Python Medium
  10. Password strength report with individual regex checks in Python Medium

Python Built-in Functions 10 questions

  1. Sentence statistics using only built-ins in Python Easy
  2. Transpose a table and compute column totals with zip in Python Medium
  3. Top 3 products by revenue with sorted() in Python Easy
  4. Remove duplicates keeping order, case-insensitively, in Python Medium
  5. Number base converter with bin, oct, hex and int in Python Easy
  6. Validate form fields with all() and any() in Python Medium
  7. Day-to-day changes with zip in Python Medium
  8. Most frequent item with max() and a key in Python Easy
  9. Caesar cipher with chr() and ord() in Python Medium
  10. Attendance report with enumerate, zip and sum in Python Medium

Python Coding Interview Questions 20 questions

  1. Valid parentheses using a stack in Python Easy
  2. Longest substring without repeating characters in Python Medium
  3. Maximum subarray sum with indices (Kadane) in Python Medium
  4. Product of array except self without division in Python Hard
  5. Longest common prefix of a list of strings in Python Easy
  6. Find the duplicate and the missing number in Python Medium
  7. Rotate an array in place with the reversal trick in Python Medium
  8. Palindrome after deleting at most one character in Python Hard
  9. Count-and-say sequence with run-length grouping in Python Medium
  10. Merge overlapping intervals in Python Medium
  11. Implement an LRU cache with OrderedDict in Python Medium
  12. Top k frequent elements with Counter and heapq in Python Medium
  13. Reverse a singly linked list in Python Medium
  14. Detect a cycle in a linked list (Floyd's algorithm) in Python Hard
  15. Binary tree level-order traversal and maximum depth in Python Medium
  16. Shortest path in a grid with obstacles using BFS in Python Hard
  17. K-th largest element using a size-k min-heap in Python Medium
  18. Spiral order traversal of a matrix in Python Medium
  19. Minimum coins for an amount (coin change) with DP in Python Hard
  20. 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.

Search LearnFrenzy

Esc

Quick links