Python Programs with Output
Complete programs, each explained step by step with its output. Run them here, open them in the editor, or step through them with Visualize.
No programs match . Try fewer or shorter words.
Numbers
Even or odd, primes, factorials, Fibonacci, Armstrong numbers and other school programs.
- Armstrong number check Checks whether a number equals the sum of its digits, each raised to the power of how many digits it has.
- Even or odd check Checks whether a number is even or odd with the % operator, which gives the remainder after dividing by 2.
- Factorial of a number Finds the factorial of a number, the product of every whole number from 1 to n, with a for loop.
- Fibonacci sequence Builds the first n terms of the Fibonacci sequence, where each term is the sum of the two before it, as a list.
- GCD and LCM Finds the greatest common divisor (HCF) of two numbers with Euclid's algorithm, then their least common multiple from it.
- Grade calculator Turns marks out of 100 into a letter grade from A to F by checking, from the top down, which range they fall in.
- Largest of three numbers Finds the largest of three numbers by comparing them with if, elif and else.
- Leap year check Checks whether a year is a leap year: divisible by 4, except century years, which must be divisible by 400.
- Multiplication table Prints the multiplication table of a number from 1 to 10, one line per multiple, with a for loop.
- Palindrome number check Checks whether a number reads the same backwards as forwards by reversing its digits and comparing.
- Perfect number check Checks whether a number equals the sum of its proper divisors, the smaller numbers that divide it exactly, as 28 does.
- Prime number check Checks whether a number is prime by trying every divisor from 2 up to its square root.
- Prime numbers in a range Lists every prime number between two numbers, such as 10 and 50, by checking each number in turn.
- Quadratic equation roots Finds the roots of ax² + bx + c = 0 from the discriminant: two real roots, one repeated root, or two complex roots.
- Reverse a number Reverses the digits of a number, so 1234 becomes 4321, by taking them off the end with % 10 and // 10.
- Simple and compound interest Works out the simple and the compound interest on the same principal, rate and number of years, shown to two decimal places.
- Simple calculator A calculator function that adds, subtracts, multiplies or divides two numbers, with a message instead of an error for division by zero.
- Sum of digits Adds up the digits of a number, taking the last digit with % 10 and removing it with // 10 until none are left.
- Swap two numbers Swaps the values of two variables in one line with a, b = b, a, without a temporary variable.
- Temperature conversion Converts a temperature from Celsius to Fahrenheit and from Fahrenheit back to Celsius with the two standard formulas.
Patterns
Star, number and Pascal triangle patterns printed with loops.
- Diamond pattern Prints a diamond of stars: the rows of a pyramid going down to the widest one, then the same rows again in reverse.
- Number triangle pattern Prints a triangle of numbers where row 1 is 1, row 2 is 1 2, row 3 is 1 2 3, and so on for as many rows as you ask.
- Pascal's triangle Prints Pascal's triangle, working out each row from the one above it: every number inside a row is the sum of the two above it.
- Pyramid pattern Prints a centred pyramid of stars: each row has one space less in front and two more stars than the row above.
- Right-angled triangle pattern Prints a right-angled triangle of stars with one more star on each row, using a loop and string repetition.
Strings
Palindromes, vowels, word counts, anagrams and other text programs.
- Anagram check Checks whether two words or phrases are anagrams, made of exactly the same letters, by sorting the letters of each and comparing them.
- Count vowels Counts the vowels (a, e, i, o and u) in a string, capital letters included, by checking each character in turn.
- Palindrome string check Checks whether a word or sentence reads the same backwards as forwards, ignoring capitals, spaces and punctuation.
- Reverse words in a string Reverses the order of the words in a sentence, keeping each word spelt forwards, with split(), list slicing and join().
- Word frequency Counts how many times each word appears in a sentence, with a dictionary that has the words as keys and their counts as values.
Searching and sorting
Linear and binary search, and the classic sorting algorithms step by step.
- Bubble sort Sorts a list by swapping neighbours that are out of order, pass after pass, and stops early once a pass makes no swaps.
- Insertion sort Sorts a list by taking each item in turn and inserting it into its place among the sorted items before it.
- Linear search Finds a value in a list by checking each item in turn, from the first to the last, until one matches.
- Selection sort Sorts a list by finding the smallest item left and swapping it to the front of the unsorted part, one place at a time.
- Binary search Finds a value in a sorted list by checking the middle item and halving the part still to search at every step.
- Merge sort Sorts a list by splitting it in half, sorting each half the same way, then merging the two sorted halves into one.
- Quick sort Sorts a list in place by moving smaller items before a pivot and the rest after it, then sorting each side: O(n log n) time on average.
Data structures
Stacks, queues, linked lists, trees, heaps and techniques built on lists.
- Balanced brackets Checks whether every bracket in a string is closed in the right order, using a list as a stack of the brackets still open.
- Queue A first-in, first-out print queue built on collections.deque: jobs join at the back, leave from the front, and peek shows the next one.
- Binary search tree Builds a binary search tree, where smaller values go left and larger ones right, then searches it and lists its values in sorted order.
- Binary tree traversals Visits every node of a small binary tree in in-order, pre-order and post-order with three short recursive functions.
- Linked list A singly linked list of Node objects that adds values at the end, deletes a value, reverses itself and prints as 1 -> 2 -> 3.
- Prefix sums Stores the running totals of a list in one O(n) pass, then answers each range sum query with one subtraction, in O(1).
- Sliding window Finds the largest sum of k items in a row by sliding a window along the list, adding the item that enters and taking away the one that leaves.
- Top k items with a heap Finds the k largest items in a list with heapq, keeping a min-heap of the k biggest seen so far, so the list never has to be sorted.
Graphs
Breadth-first and depth-first search, shortest paths, ordering and connected groups.
- Breadth-first search Visits the nodes of a graph from a start node, nearest first, keeping the nodes still to visit in a queue.
- Depth-first search Visits the nodes of a graph from a start node, following each path as deep as it goes before backing up to try the next.
- Dijkstra's shortest path Finds the shortest distance from one node to every other in a weighted graph, always going on from the closest node, with heapq.
- Topological sort Orders courses so that each comes after the courses it needs, with Kahn's algorithm: count each one's prerequisites, then use a queue.
- Union-find Puts friends into groups with union-find, where merging two groups and asking if two people share one each take almost constant time.
Dynamic programming
Problems solved by remembering the answers to smaller problems.
- Coin change Finds the fewest coins that add up to an amount by solving every smaller amount first, or -1 when no mix of the coins makes it.
- Fibonacci with memoization Works out Fibonacci numbers with recursion, remembering each answer in a dict so that no number is ever calculated twice.
- 0/1 knapsack Finds the most value that fits in a bag with a weight limit, taking each item at most once, by filling in a table.
- Longest common subsequence Finds the longest run of letters that appears in the same order, not always side by side, in both of two strings, with a table.
Backtracking
Trying every choice and undoing the ones that fail: permutations, subsets, N-Queens.
- Permutations Lists every ordering of a list's items by choosing an item for each place in turn, then undoing the choice to try the next one.
- Subsets Lists every subset of a list's items (the power set) by deciding for each item in turn whether to include it or skip it.
- N-Queens Places N queens on an N×N chessboard so that no two attack each other, trying each column row by row and backing up from dead ends.