Python example programs for beginners
63 classic Python programs, from Hello World to binary search, each with complete code, its real output and a plain-English explanation. Press Run and edit on any program to change it and see what happens.
Basics
- Hello, World!: Print a message on the screen: the traditional first program in any language.
- Add two numbers: Add two numbers and print the result in a sentence.
- Swap two variables: Exchange the values of two variables.
- Area and circumference of a circle: Given a radius, calculate the area (πr²) and circumference (2πr).
- Convert Celsius to Fahrenheit: Convert temperatures from Celsius to Fahrenheit (F = C × 9/5 + 32) and back.
- Simple and compound interest: Compare simple interest with compound interest on savings.
- BMI calculator: Calculate body mass index (weight ÷ height²) and its category.
Conditions
- Even or odd: Check whether numbers are even or odd.
- Largest of three numbers: Find the largest of three numbers, with if/elif and with max().
- Positive, negative or zero: Classify numbers as positive, negative or zero.
- Check a leap year: A year is a leap year if it is divisible by 4, except century years, which must be divisible by 400.
- Grade calculator: Turn percentage marks into grades.
- Vowel or consonant: Check whether each letter of a word is a vowel or a consonant.
Loops and numbers
- Multiplication table: Print the multiplication table of a number.
- Sum of the first n numbers: Add up 1 + 2 + … + n, with a loop and with the formula.
- Factorial of a number: n! = 1 × 2 × … × n. Calculate it with a loop, recursion and the math module.
- Fibonacci sequence: Print the first terms of the Fibonacci sequence, where each number is the sum of the two before it.
- Check whether a number is prime: A prime has exactly two divisors: 1 and itself.
- All primes up to a limit (sieve): List every prime number up to a limit with the Sieve of Eratosthenes.
- Sum of the digits of a number: Add up the digits of a whole number, with maths and with strings.
- Reverse a number: Reverse the digits of a number: 1234 becomes 4321.
- Armstrong numbers: An Armstrong number equals the sum of its digits, each raised to the power of the number of digits (153 = 1³ + 5³ + 3³).
- Greatest common divisor and least common multiple: Find the GCD and LCM of two numbers with Euclid's algorithm.
- Print a pyramid pattern: Print triangle and pyramid patterns with nested loops and string repetition.
- Convert decimal to binary: Convert whole numbers to binary by repeated division by 2, and check with bin().
Strings
- Reverse a string: Reverse text in three ways.
- Check for a palindrome: A palindrome reads the same forwards and backwards, ignoring spaces, punctuation and capitals.
- Count vowels and consonants: Count the vowels, consonants, digits and spaces in a sentence.
- Count word frequency: Find the most common words in a piece of text.
- Check whether two words are anagrams: Anagrams use exactly the same letters: "listen" and "silent".
- Capitalise the first letter of each word: Turn "hello world" into "Hello World".
- Remove punctuation from text: Strip punctuation marks from a sentence.
- Count each character: Count how many times each character appears in a word.
- Find the longest word: Find the longest word in a sentence.
- Caesar cipher: Encrypt and decrypt text by shifting each letter along the alphabet.
- Count lines, words and characters: Count the lines, words and characters in a block of text, like the Unix wc command.
Lists
- Largest and smallest in a list: Find the largest and smallest numbers in a list, with a loop and with max/min.
- Second largest number in a list: Find the second largest distinct number.
- Remove duplicates from a list: Remove repeated items, keeping the original order.
- Average, median and spread of a list: Summarise a list of numbers.
- Flatten a nested list: Turn a list of lists into one flat list.
- Rotate a list: Move items from the end of a list to the front.
- Common elements of two lists: Find the items two lists share, and the ones they do not.
- Bubble sort: Sort a list by repeatedly swapping neighbours that are in the wrong order.
- Binary search: Find a value in a sorted list by halving the search range each step.
- Multiply two matrices: Multiply matrices stored as lists of lists, then check with NumPy.
Dictionaries and sets
- Merge two dictionaries: Combine two dictionaries; when a key is in both, the second wins.
- Sort a dictionary by value: List the items of a dictionary from highest to lowest value.
- Swap keys and values: Turn a {key: value} dictionary into {value: key}.
- Group words that are anagrams: Put words made of the same letters into groups.
Files and data
- Read a CSV file and total a column: Read a CSV of sales and total them per product.
- Save and load data as JSON: Store a list of records in a JSON file and read it back.
- List files by type: Find all files with a given extension in a folder, with their sizes.
Functions and recursion
- Fast recursive Fibonacci with memoisation: Make a slow recursive function fast by remembering its answers.
- Tower of Hanoi: Move a stack of discs between three pegs, one disc at a time, never putting a larger disc on a smaller one.
- All subsets of a set: List every subset (the power set) of a small set of items.
Useful mini-programs
- Password generator: Generate strong random passwords.
- Simulate rolling dice: Roll two dice many times and see how often each total appears.
- Age and days until a birthday: Work out an exact age and the days until the next birthday.
- Print a monthly calendar: Print the calendar for a month with the calendar module.
- A simple calculator: A calculator that applies + − × ÷ to two numbers, with error handling.
- A to-do list in the terminal: Manage a to-do list: add, complete and show tasks (a longer version is in the course's projects lesson).
- Number guessing game: The computer picks a number and the player guesses, with "too high" and "too low" hints.