PythonMastery
Python programs

195 Python programs for beginners

Classic programs, in order from your first print() to small tools and interview problems. Each page shows the code, the output and how it works, and you can press Run to try it here in your browser. Every output on these pages is checked when the site is built.

First programs · Math and numbers · Strings · Lists · Dictionaries and sets · Loops and control flow · Functions · Errors and exceptions · Files · Dates and time · Classes and objects · Useful programs

First programs

Printing, variables, input and simple calculations.
001 Hello World program in PythonThe first program everyone writes: print one line of text with print(). What the line does, and how to print more than one line.beginner002 Variables and print in PythonStore a name and an age in variables, then print them in one sentence with an f-string. Shows how variables and print() work together.beginner003 Take user input in PythonAsk the user for their name with input() and greet them. Also shows how to turn typed text into a number with int() or float().beginner004 Add two numbers in PythonRead two numbers with input(), convert them with float() or int(), and print their sum. Also shows why '12' + '30' gives '1230'.beginner005 Swap two variables in PythonSwap the values of two variables with a, b = b, a. How the one-line swap works, and the temporary-variable version other languages use.beginner006 Check the type of a variable in PythonFind out whether a value is an int, a float, a string or a list with type(), and test for a type with isinstance().beginner007 Type conversion in PythonConvert between types with int(), float(), str() and bool(), and see which conversions fail, such as int('3.5'), and how to handle them.beginner008 Find the ASCII value of a character in PythonGet the ASCII code of a character with ord(), turn a code back into a character with chr(), and print a range of letters with their codes.beginner009 Assign several variables at once in PythonGive several variables the same value with x = y = z = 0, or different values in one line with a, b, c = 1, 2, 3.beginner010 Basic arithmetic in PythonAdd, subtract, multiply and divide two numbers in Python, plus floor division (//), remainder (%) and powers (**), with the output of each.beginner011 Simple calculator program in PythonA beginner calculator: read two numbers and an operator, choose the operation with if/elif, and handle division by zero and unknown operators.beginner012 Celsius to Fahrenheit program in PythonRead a temperature in Celsius, convert it with F = C × 9/5 + 32, and print the result. Also shows the Fahrenheit to Celsius version.beginner013 Convert kilometres to miles in PythonRead a distance in kilometres, convert it to miles using 1 mile = 1.609344 km, and print a conversion table. Also shows miles to kilometres.beginner014 Area of a circle program in PythonRead the radius, calculate the area with math.pi × r², and print it rounded to two decimal places. Also calculates the circumference.beginner015 Simple interest program in PythonRead the principal, the yearly rate and the number of years, then calculate simple interest with P × R × T / 100 and the total amount.beginner016 Compound interest program in PythonCalculate compound interest with A = P(1 + r/100)^t, show the balance year by year, and compare yearly, monthly and daily compounding.beginner017 BMI calculator program in PythonRead weight in kilograms and height in metres, calculate the body mass index (weight / height²), and print the standard category.beginner018 Check if a number is odd or even in PythonRead a whole number and print whether it is odd or even, using the remainder operator: n % 2 is 0 for even numbers.beginner019 Check if a number is positive, negative or zero in PythonRead a number and print whether it is positive, negative or zero, using an if / elif / else chain.beginner020 Grade calculator program in PythonConvert marks out of 100 into a grade with if/elif/else, reject marks below 0 or above 100, and grade a whole class with a function.beginner021 Find the largest of three numbers in PythonFind the biggest of three numbers with the built-in max(), and with if / elif comparisons to see how the logic works.beginner022 Leap year program in PythonCheck whether a year is a leap year: divisible by 4, except years divisible by 100, unless they are also divisible by 400.beginner023 Solve a quadratic equation in PythonFind the roots of ax² + bx + c = 0 using the discriminant: two real roots, one repeated root, or two complex roots with the cmath module.beginner

Math and numbers

Factorials, primes, Fibonacci, digits and number checks.
024 Factorial program in PythonCalculate the factorial of a number with a for loop, check for negative input, and compare the result with math.factorial().beginner025 Factorial using recursion in PythonA recursive factorial function: the base case, the recursive call, and why very large inputs raise a RecursionError in Python.intermediate026 Fibonacci series program in PythonPrint the first n terms of the Fibonacci series with a for loop, and all Fibonacci numbers below a limit with a while loop.beginner027 Check prime number in PythonCheck whether a number is prime by testing divisors only up to its square root. Handles 0, 1 and negative numbers correctly.beginner028 Print prime numbers in a range in PythonPrint all prime numbers between two numbers with a loop, and find every prime up to a limit faster with the Sieve of Eratosthenes.beginner029 Prime factors of a number in PythonBreak a number into its prime factors, like 360 = 2 × 2 × 2 × 3 × 3 × 5, by dividing by 2, 3, 4 and so on, and print it with powers.beginner030 GCD of two numbers in PythonFind the greatest common divisor (GCD, also called HCF) of two numbers with Euclid's algorithm, and with the built-in math.gcd().beginner031 LCM of two numbers in PythonFind the least common multiple (LCM) of two numbers from their GCD, handle zero, and use math.lcm() for two or more numbers.beginner032 Sum of digits of a number in PythonAdd up the digits of a number with % and // in a while loop, and with a string. Works for negative numbers too.beginner033 Reverse a number in PythonReverse the digits of a number with % and // in a while loop, keep the minus sign for negative numbers, and do the same with string slicing.beginner034 Palindrome number program in PythonCheck whether a number reads the same forwards and backwards, like 12321, with string slicing and with a digit-by-digit loop.beginner035 Armstrong number program in PythonCheck whether a number is an Armstrong number, like 153 = 1³ + 5³ + 3³, and find every Armstrong number below 1000.beginner036 Strong number program in PythonCheck whether a number is a strong number, like 145 = 1! + 4! + 5!, and find every strong number below 100,000.beginner037 Perfect number program in PythonCheck whether a number is perfect, like 28 = 1 + 2 + 4 + 7 + 14, and find all perfect numbers below 10,000 with a faster divisor loop.beginner038 Find the factors of a number in PythonList every factor of a number with a for loop and %, then a faster version that stops at the square root and finds the factors in pairs.beginner039 Power of a number in Python without pow()Raise a number to a power with a loop instead of ** or pow(), handle zero and negative exponents, and see the faster squaring method.beginner040 Square root in PythonFind a square root with ** 0.5, math.sqrt() and math.isqrt(), handle negative numbers, and calculate one by hand with Newton's method.beginner041 Count the digits in a number in PythonCount how many digits a whole number has with a while loop, or with len(str()). Handles 0 and negative numbers correctly.beginner042 Convert decimal to binary, octal and hexadecimal in PythonConvert a decimal number to binary, octal and hexadecimal with bin(), oct(), hex() and format(), and to binary by hand with repeated division by 2.beginner043 Sum of a series in PythonAdd up the series 1 + 2 + ... + n, 1² + 2² + ... + n² and 1 + 1/2 + ... + 1/n with a loop, and check them with the formulas.beginner

Strings

Reversing, counting, checking and changing text.
044 Reverse a string in PythonReverse any text with the slice s[::-1]. Also shows how to reverse a string with a loop, and how to reverse the order of the words instead.beginner045 Palindrome string program in PythonCheck whether a word or phrase reads the same forwards and backwards. Ignores capital letters, spaces and punctuation, so phrases work too.beginner046 Count vowels in a string in PythonCount the vowels (a, e, i, o, u) in a sentence with a loop and the in operator, then count each vowel separately with a dictionary.beginner047 Check if a letter is a vowel or consonant in PythonRead one letter and print whether it is a vowel or a consonant. Capital letters work, and digits, symbols and longer text get a clear message.beginner048 Count uppercase, lowercase letters and digits in PythonCount the capital letters, small letters, digits, spaces and other characters in a sentence with isupper(), islower(), isdigit() and isspace().beginner049 Count words in a string in PythonCount the words in a sentence with len(text.split()). Extra spaces and empty input are handled correctly, and a common mistake with split is explained.beginner050 Check if two strings are anagrams in PythonCheck whether two words or phrases use exactly the same letters, ignoring case and spaces. Uses sorted(), with collections.Counter as a second way.beginner051 Check if a sentence is a pangram in PythonCheck whether a sentence uses every letter from a to z, and print the letters it is missing, with a set difference or a simple loop.beginner052 Convert a string to title case in PythonMake the first letter of every word a capital with str.title(). Also shows the apostrophe problem with title() and how string.capwords() avoids it.beginner053 Remove duplicate characters from a string in PythonKeep only the first copy of each character and keep the original order. Shown with a loop and a set, then with dict.fromkeys().beginner054 Find the most frequent character in a string in PythonCount every character with a dictionary and find the one that appears most often. Handles ties, and shows the shorter Counter.most_common() way.beginner055 Caesar cipher program in PythonShift every letter of a message a fixed number of places along the alphabet. The same function decrypts the message with a negative shift.intermediate056 Count occurrences of a substring in PythonCount how many times one piece of text appears inside another with str.count(). Also shows overlapping matches and a case-insensitive count.beginner057 Replace a word in a string in PythonReplace every match or only the first with str.replace(), ignore capital letters with re.sub(), and replace whole words only with \\b.beginner058 Capitalize the first letter of each word in PythonMake the first letter of each word a capital and keep the rest of the word as it was, so NASA stays NASA. Compared with capitalize() and title().beginner059 Check if a string contains only digits in PythonTest whether text is made only of digits with isdigit() and isdecimal(), what they say about spaces, minus signs and decimals, and a safer int() check.beginner060 Remove punctuation from a string in PythonStrip commas, full stops, question marks and other punctuation from text with str.translate() and string.punctuation, or with a simple loop.beginner061 Compress repeated characters in a string in PythonReplace each run of the same character with the character and its count, so aaabbbcc becomes a3b3c2. With a loop, and with itertools.groupby().intermediate062 Find the longest word in a sentence in PythonFind the longest word in a sentence with max() and key=len. Punctuation is removed first, and ties between words of the same length are handled.beginner063 Sort words in alphabetical order in PythonSplit a sentence into words and sort them in alphabetical order, ignore capital letters with key=str.lower, and list each word only once.beginner

Lists

Sums, sorting, searching and reshaping lists.
064 Sum and average of a list in PythonFind the total and the average of a list of numbers with sum() and len(), and avoid the ZeroDivisionError you get from an empty list.beginner065 Find the minimum and maximum of a list in PythonFind the smallest and largest number in a list with min() and max(), then the same thing with a loop, and what to do with an empty list.beginner066 Remove duplicates from a list in PythonRemove repeated items from a list in Python while keeping the original order, with dict.fromkeys(), with set(), and with a loop.beginner067 Reverse a list in PythonThree ways to reverse a list in Python: slicing with [::-1] for a new list, reverse() to change the list in place, and reversed() for a loop.beginner068 Sort a list in Python (ascending and descending)Sort a list of numbers in ascending and descending order with sorted() and list.sort(), and sort words without capital letters coming first.beginner069 Flatten a nested list in PythonTurn a list of lists into one flat list in Python with a nested loop or a list comprehension, and flatten lists nested to any depth.beginner070 Find common elements of two lists in PythonFind the items that appear in both of two lists in Python, keeping the order of the first list, and the shorter set & version.beginner071 Union of two lists in PythonCombine two lists in Python so that every item appears once, with the set | operator or with dict.fromkeys() to keep the order.beginner072 Count occurrences of an element in a list in PythonCount how many times an item appears in a list with list.count(), and count every item at once with collections.Counter.beginner073 Rotate a list in PythonRotate a list left or right by k places in Python with slicing, handle k larger than the list, and use collections.deque.rotate().beginner074 Split a list into chunks in PythonSplit a list into smaller lists of a fixed size in Python with range() and slicing, and with itertools.batched() in Python 3.12 and later.beginner075 Find the second largest number in a list in PythonFind the second largest number in a list in Python, with repeated values handled correctly, and a one-pass loop that works without sorting.beginner076 Convert two lists into a dictionary in PythonTurn a list of keys and a list of values into one dictionary with dict(zip(keys, values)), and catch lists of different lengths with strict=True.beginner077 Filter even numbers from a list in PythonMake a new list with only the even numbers from a list in Python, using a list comprehension, a for loop, or filter() with a lambda.beginner078 Split a list into even and odd numbers in PythonPut the even numbers of a list into one list and the odd numbers into another, with one for loop, with two list comprehensions, or with a dictionary.beginner079 Matrix addition in PythonAdd two matrices stored as nested lists in Python: add the numbers in the same row and column, and check first that both have the same shape.beginner080 Matrix multiplication in PythonMultiply two matrices stored as nested lists with three nested loops, check first that their shapes fit, then see a shorter version with zip().intermediate

Dictionaries and sets

Counting, merging, inverting and comparing.
081 Word frequency counter in PythonCount how many times each word appears in a piece of text, using a dictionary. Also handles capital letters and punctuation, and shows Counter.beginner082 Merge two dictionaries in PythonCombine two dictionaries into one with the | operator, {**a, **b} or update(). When both have the same key, the value from the second one is kept.beginner083 Invert a dictionary in PythonSwap the keys and values of a dictionary with a dict comprehension, and what to do when two keys share the same value.intermediate084 Sort a dictionary by value in PythonSort a dictionary by its values, smallest first or largest first, using sorted() with a key function. Also how to sort by key.beginner085 Filter a dictionary in PythonKeep only the dictionary entries that pass a test, such as scores of 60 or more, using a dict comprehension with an if condition.beginner086 Nested dictionary in PythonStore a dictionary inside a dictionary, read a value two levels down, change it, and avoid a KeyError when a key may be missing.beginner087 Count character frequency in PythonCount how many times each character appears in a string, first with a plain dictionary and then with collections.Counter and most_common().beginner088 Set operations in PythonUnion, intersection, difference and symmetric difference of two sets in Python, with the operator and the method name for each.beginner089 Check subset and superset in PythonCheck whether every item of one set is in another with issubset(), issuperset() or the <= and >= operators, plus isdisjoint().beginner090 Remove duplicate dictionaries from a list in PythonRemove repeated dictionaries from a list while keeping the original order, either by one key such as id or by comparing every field.intermediate091 defaultdict in PythonUse collections.defaultdict to group items into lists or count them, without checking first whether each key exists.intermediate092 namedtuple in PythonCreate a namedtuple so each item of a tuple has a name: p.x instead of p[0]. Also _replace(), _asdict() and the typed NamedTuple form.intermediate093 OrderedDict in PythonNormal dicts keep insertion order since Python 3.7. What OrderedDict still adds: move_to_end(), popitem(last=False) and order-aware ==.intermediate094 Find common keys in two dictionaries in PythonFind the keys two dictionaries share with keys() & keys(), and also the keys only one of them has, and the keys whose values differ.beginner095 Frequency table from a list in PythonCount each item in a list with collections.Counter and print a frequency table with counts, percentages and a small text bar chart.beginner

Loops and control flow

Patterns, games, comprehensions and loop tricks.
096 FizzBuzz program in PythonPrint the numbers 1 to 15, but Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both. Why the order of the checks matters.beginner097 Multiplication table program in PythonAsk for a number and print its multiplication table from 1 to 10 with a for loop, with the columns lined up. Also prints a full 1 to 5 grid.beginner098 Sum of first N natural numbers in PythonAdd up 1 + 2 + ... + n three ways: with a while loop, with sum(range()), and with the formula n(n+1)/2. All three give 5050 for n = 100.beginner099 Number guessing game in PythonThe computer picks a number from 1 to 100 and the player guesses until they find it, with too high and too low hints, a guess counter and input checks.beginner100 Rock paper scissors game in PythonPlay rock paper scissors against the computer for five rounds. A dictionary holds the rules, input is checked, and the program keeps the score.beginner101 Dice roller in PythonRoll any number of dice with random.randint and add up the total. Then roll 6000 times and count how often each face appears.beginner102 Coin toss program in PythonToss a coin once with random.choice, then toss it 1000 times and count heads and tails with their percentages.beginner103 Print a star triangle pattern in PythonPrint a right-angled triangle of stars with a for loop and string repetition, then a centred pyramid and a number triangle.beginner104 Number pyramid pattern in PythonPrint a centred pyramid of numbers with a for loop, then a palindrome pyramid where each row counts up and back down: 1, 121, 12321.beginner105 Floyd's triangle in PythonPrint Floyd's triangle, a right-angled triangle of consecutive numbers 1, 2 3, 4 5 6, with nested loops, then line the columns up neatly.beginner106 Pascal's triangle in PythonPrint Pascal's triangle by building each row from the one above it, then a centred version that uses math.comb() for each value.intermediate107 Diamond pattern in PythonPrint a diamond of stars with two for loops, one for the top half and one for the bottom half, then a hollow diamond outline.beginner108 Inverted triangle pattern in PythonPrint an upside-down triangle of stars by counting down with range(rows, 0, -1), plus a right-aligned version, an inverted pyramid and numbers.beginner109 break and continue in Pythoncontinue skips the rest of one pass of a loop; break ends the whole loop. A short demo of each, then a practical example that uses both.beginner110 while loop with else in PythonA while loop can have an else block. It runs when the condition becomes false, but not when the loop ends with break. A countdown and a password check.intermediate111 List comprehension with if condition in PythonUse a list comprehension with an if clause to keep only the items you want: positive numbers, negative numbers, or words of a certain length.beginner112 Nested list comprehension in PythonBuild a 2D list (a matrix) with a list comprehension inside another, then flatten it and transpose it. How to read the order of the for clauses.intermediate113 if else in a list comprehension in PythonUse if else inside a list comprehension to choose a value for every item, such as odd or even labels. Why it goes before for, but a filter goes after.intermediate114 match case statement in PythonUse match and case (Python 3.10 and later) to compare a value with several patterns: plain values, several values at once, and lists that capture words.intermediate115 Menu driven program in PythonA shopping list program with a menu: add, show, remove and quit. A while loop shows the menu again after each choice until the user quits.beginner116 for else in PythonA for loop can have an else block that runs only when the loop was not stopped by break. Use it to report 'not found' without a flag variable.intermediate117 enumerate and zip together in PythonLoop over two lists side by side with zip(), number the rows with enumerate(), and use both at once. What zip does when the lists have different lengths.beginner118 Walrus operator (:=) in PythonThe walrus operator := (Python 3.8 and later) stores a value and uses it in the same expression. Examples with a while loop, input() and a list comprehension.intermediate119 Generator expression vs list comprehension in PythonA list comprehension builds every value at once; a generator expression makes one value at a time. Compare their memory use, and see when to use each one.intermediate

Functions

Arguments, closures, decorators, recursion, searching and sorting.
120 Default arguments in PythonGive a function parameter a default value so callers can leave it out. Also shows the mutable default mistake and how to avoid it.beginner121 *args and **kwargs in PythonWrite functions that accept any number of arguments. *args collects extra positional arguments into a tuple, **kwargs collects keyword arguments into a dict.beginner122 Return multiple values from a function in PythonReturn several values from one function by separating them with commas. Python packs them into a tuple, and you unpack them into separate variables.beginner123 Lambda function in PythonA lambda is a small function written as one expression. See how to write one and where it is useful: as the key for sorted(), max() and min().beginner124 map, filter and reduce in PythonUse map() to change every item, filter() to keep some items, and reduce() to combine items into one value. Also shows the list comprehension way.beginner125 Closure in PythonA closure is an inner function that remembers variables from the function that created it. Build a multiplier and a counter with nonlocal.intermediate126 Decorator in PythonA decorator wraps a function to add behaviour before and after it runs, without changing its code. Build one step by step, then a timing decorator.intermediate127 Memoization with functools.cache in PythonMake a slow recursive function fast by remembering its results. One line, @cache, turns millions of Fibonacci calls into a few dozen.intermediate128 Generator function in Python (yield)A function with yield gives back values one at a time instead of building a whole list. Write a countdown, step through it with next(), and make an endless one.intermediate129 Linear search in PythonFind an item by checking every item of a list in order, return its index or -1, and count the comparisons to compare it with binary search.beginner130 Binary search in Python (recursive)Find an item in a sorted list by checking the middle and throwing away half the list each time. Recursive version, loop version and the bisect module.intermediate131 Bubble sort in PythonSort a list by swapping neighbours that are in the wrong order, pass after pass. Includes the early exit that stops when the list is already sorted.beginner132 Selection sort in PythonSort a list by finding the smallest remaining item and swapping it into place, one position at a time. Includes a trace of each pass.beginner133 Insertion sort in PythonSort a list by taking each item in turn and inserting it into its place among the sorted items before it. Includes a trace of each step.beginner134 Merge sort in PythonSort a list by splitting it in half, sorting each half with recursion, then merging the two sorted halves. Includes the merge step on its own.intermediate135 Quick sort in PythonSort a list by picking a pivot, splitting the items into smaller, equal and larger, and sorting each part with recursion. Includes a trace of the calls.intermediate136 Merge two sorted lists in PythonCombine two sorted lists into one sorted list by walking through both with two positions, then the shorter ways with heapq.merge() and sorted().beginner137 Stack in Python using a listA stack is last in, first out. Use a list with append() and pop() as a stack, then use one to check that brackets in a string are balanced.beginner138 Queue in Python using dequeA queue is first in, first out. Use collections.deque with append() and popleft(), and see why list.pop(0) is the slow way to do it.beginner139 Linked list in PythonBuild a singly linked list with a Node class: add items to the end and the front, print the list, and remove an item by value.intermediate

Errors and exceptions

Catching errors, checking input and raising your own.

Files

Reading and writing text, CSV and JSON files.
145 Write to a file in PythonCreate a text file and write lines to it with open() in 'w' mode and a with block. Shows why you add the new line yourself and how writelines() works.beginner146 Read a file in PythonRead the whole contents of a text file into one string with read(), and handle the case where the file does not exist.beginner147 Read a file line by line in PythonLoop over a file object to read one line at a time, remove the new line with strip(), and number the lines with enumerate().beginner148 Append to a file in PythonAdd new lines to the end of a file without deleting what is already there, using open() in 'a' (append) mode.beginner149 Count lines in a file in PythonCount the lines in a text file without loading it all into memory, then count words and characters too, like the wc command.beginner150 Read a CSV file in PythonRead a CSV file with the csv module: each row becomes a dictionary keyed by the header. Also shows converting numbers and totalling a column.beginner151 Write a CSV file in PythonSave a list of dictionaries as a CSV file with csv.DictWriter: write the header, then the rows. Also shows csv.writer for lists.beginner152 Read and write a JSON file in PythonSave a dictionary to a JSON file with json.dump() and load it back with json.load(). Shows which Python types survive the round trip.beginner153 Check if a file exists in PythonCheck whether a file or folder exists with pathlib.Path.exists(), is_file() and is_dir(), and print the file size when it does.beginner154 List all files in a folder in PythonList the files in a folder with pathlib.Path.iterdir(), filter them by extension with glob(), and search subfolders with rglob().beginner

Dates and time

Today's date, ages, gaps between dates and calendars.

Classes and objects

Classes, inheritance, special methods and dataclasses.
160 Create a class in PythonA simple Python class with __init__, attributes and methods. Create two objects from it and see that each one keeps its own data.beginner161 Bank account class in PythonA BankAccount class with deposit and withdraw methods, a read-only balance, a transaction history and __repr__. Overdrafts are refused with a clear error.beginner162 Class variables in PythonA class variable is shared by every object of the class. Count how many objects were created, and see the mistake of using a list as a class variable.intermediate163 Inheritance in PythonMake a child class that inherits attributes and methods from a parent class, override a method, and call the parent's __init__ with super().intermediate164 Dunder methods in PythonMake your own class work with +, ==, * and print() by writing dunder (magic) methods. Example: a 2D Vector class.intermediate165 Property decorator in PythonUse @property to check a value when it is set (a radius cannot be negative) and to compute a value, such as an area, every time it is read.intermediate166 Static method in PythonA static method is a function kept inside a class that needs no object. Compare @staticmethod, @classmethod and a normal method in one class.intermediate167 Dataclass in PythonUse @dataclass to get __init__, __repr__ and __eq__ written for you. Includes default values, field(default_factory=list) and sorting objects.intermediate168 Abstract base class in PythonUse ABC and @abstractmethod to define methods every subclass must write. Python refuses to create an object from a class that forgot one.intermediate169 Create a context manager in PythonWrite a class with __enter__ and __exit__ so it works with the with statement. Example: a timer. Also the shorter way with contextlib.advanced170 Singleton pattern in PythonMake a class that can only ever have one object, using __new__. Shows the __init__ problem, and why a module is often the simpler choice.advanced

Useful programs

Small tools and classic interview problems.
171 Password generator in PythonGenerate random passwords that always contain a lowercase letter, a capital, a digit and a symbol. Also shows the secrets module for real passwords.beginner172 Email validation in PythonCheck whether a string looks like an email address with a regular expression and re.fullmatch(), and what a regex check cannot tell you.intermediate173 URL validation in PythonCheck whether a string is a web address starting with http:// or https://, first with a regular expression, then with urllib.parse.urlparse().intermediate174 Flatten a deeply nested list in PythonTurn a list with lists inside lists, at any depth, into one flat list. A recursive function, then a generator version with yield from.intermediate175 Roman numeral converter in PythonConvert a number from 1 to 3999 into Roman numerals, such as 2024 to MMXXIV, and convert Roman numerals back into numbers.beginner176 Convert binary to decimal and back in PythonConvert a decimal number to binary, octal and hexadecimal with format(), turn binary text back into a number with int(text, 2), and do both by hand.beginner177 Countdown timer and stopwatch in PythonA countdown timer that prints minutes and seconds with time.sleep(), and a stopwatch that measures elapsed time with time.perf_counter().beginner178 Transpose a matrix in PythonSwap the rows and columns of a matrix stored as a list of lists, first with nested loops, then in one line with zip(*matrix).beginner179 Acronym generator in PythonBuild an acronym from the first letter of each word, such as Portable Network Graphics to PNG, skipping small words like of and the.beginner180 Text-based calculator in PythonA calculator that reads lines like 7 * 6 and prints the answer, handles bad input and division by zero, and never uses eval().intermediate181 Coin change problem in PythonFind the fewest coins that add up to an amount with dynamic programming, see which coins to use, and see why always taking the largest coin can fail.intermediate182 Group anagrams in PythonPut words that are anagrams of each other, like listen and silent, into groups, using the sorted letters of each word as a dictionary key.intermediate183 Run-length encoding in PythonCompress repeated characters with run-length encoding, so AAABBC becomes 3A2B1C, and decode it back. Also the itertools.groupby version.intermediate184 Find all permutations of a string in PythonList every ordering of the letters in a string, first with a recursive function, then with itertools.permutations, and handle repeated letters.intermediate185 Two Sum problem in PythonFind two numbers in a list that add up to a target and return their positions, in one pass with a dictionary instead of two nested loops.intermediate186 Check if a linked list is a palindrome in PythonBuild a small linked list from Node objects and check whether its values read the same forwards and backwards. Also the one-line check for a Python list.intermediate187 Sort a list by frequency in PythonSort a list so the most common values come first, with ties in order, using collections.Counter and a sort key. Count once, not inside the key.intermediate188 Rolling average (moving average) in PythonCompute a moving average over a window of values, such as a 3-day average temperature, with a running total that keeps the program fast.intermediate189 Retry decorator in PythonWrite a decorator that calls a function again when it raises an error, waits between attempts, and raises the last error when every attempt fails.advanced190 Logging decorator in PythonA decorator that prints each call to a function, with its arguments and its return value. Then the same idea with the logging module.intermediate191 Process a list in batches in PythonHandle a long list a few items at a time, for example saving records in groups of 4, with slicing and with itertools.batched() from Python 3.12.intermediate192 Read a config file in PythonLoad settings from a JSON config file on top of default values, keep working when the file is missing, and read an INI file with configparser.intermediate193 Memoization in Python without a libraryWrite your own memoize decorator with a dictionary, and see it cut a recursive Fibonacci function from thousands of calls to a few.intermediate194 Progress bar in PythonDraw a text progress bar with a percentage, and redraw it on one line in the terminal with a carriage return.beginner195 Mini unit test runner in PythonA small test runner that calls a function with test inputs, compares each result with the expected value, and prints PASS or FAIL with a summary.intermediate
want to learn the ideas?The Academy

These programs show what Python can do in a few lines. The Academy lessons teach each idea step by step, and every program page links to the lesson behind it.