Skip to content
Tutorials

15 Simple Python Programs for Beginners (with Code)

Fifteen short, tested Python programs for beginners, from Hello World and even/odd to prime numbers, palindromes, a shopping bill and a guessing game, each with its output and what it teaches.

M Muninder Singh 8 min read
15 Simple Python Programs for Beginners (with Code)
On this page
  1. How to run the programs
  2. 1. Hello with your name
  3. 2. Simple calculator
  4. 3. Even or odd
  5. 4. Marks, percentage and result
  6. 5. Multiplication table
  7. 6. Leap year check
  8. 7. Factorial
  9. 8. Prime number check
  10. 9. Fibonacci series
  11. 10. Palindrome check
  12. 11. Count words and vowels
  13. 12. Largest, smallest and average from a list
  14. 13. Celsius to Fahrenheit
  15. 14. Shopping bill with a dictionary
  16. 15. Number guessing game
  17. Common errors and how to fix them
  18. How to practise with this list
  19. Practice task
  20. Keep going

The fastest way to learn programming is to write small programs, run them, break them and fix them. This list of 15 simple Python programs for beginners starts with printing a greeting and builds up to loops, lists, dictionaries and a small game. Each program includes the code, a sample run with the exact output, and a note on what it teaches. Every program has been tested in Python 3.

These are also the kind of programs that appear in school and college practicals, computer exams and fresher interviews, so practising them is time well spent.

How to run the programs

  1. Install Python 3 from python.org (on Windows, tick Add Python to PATH during installation).
  2. Open IDLE (installed with Python) or a code editor such as VS Code.
  3. Create a new file, type the program and save it with a .py extension, for example even_odd.py.
  4. Run it: in IDLE press F5; in a terminal type python even_odd.py (or python3 even_odd.py on Mac and Linux).

In the sample runs below, the text after a prompt (such as Priya) is what the user types.

Please type the code yourself instead of copying and pasting. Typing builds the habit of noticing colons, brackets and indentation, which is where most beginner errors happen.

1. Hello with your name

name = input("What is your name? ")
print("Hello,", name + "! Welcome to Python.")

Sample run:

What is your name? Priya
Hello, Priya! Welcome to Python.

Teaches: input() to read text, variables, and print(). A comma in print adds a space; + joins text with no space.

2. Simple calculator

a = float(input("First number: "))
b = float(input("Second number: "))
print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
if b != 0:
    print("Quotient:", round(a / b, 2))
else:
    print("Cannot divide by zero")

Sample run with 12 and 5:

Sum: 17.0
Difference: 7.0
Product: 60.0
Quotient: 2.4

Teaches: converting text to numbers with float(), arithmetic operators, round() and checking for division by zero before it crashes the program.

3. Even or odd

n = int(input("Enter a whole number: "))
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")

Sample run with 7: 7 is odd

Teaches: the modulus operator %, which gives the remainder. A number is even when the remainder after dividing by 2 is 0. Note == compares values, while = assigns them.

4. Marks, percentage and result

marks = [78, 85, 62, 90, 71]
total = sum(marks)
percentage = total / len(marks)
if percentage >= 75:
    grade = "Distinction"
elif percentage >= 60:
    grade = "First Division"
elif percentage >= 40:
    grade = "Pass"
else:
    grade = "Fail"
print("Total:", total, "out of", len(marks) * 100)
print("Percentage:", round(percentage, 2))
print("Result:", grade)

Output:

Total: 386 out of 500
Percentage: 77.2
Result: Distinction

Teaches: lists, sum() and len(), and if / elif / else chains. Python checks the conditions from top to bottom and stops at the first true one, so the order matters.

5. Multiplication table

n = int(input("Table of: "))
for i in range(1, 11):
    print(n, "x", i, "=", n * i)

Sample run with 7 (first and last lines):

7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70

Teaches: for loops and range(). range(1, 11) gives 1 to 10, because the end value is not included.

6. Leap year check

year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(year, "is a leap year")
else:
    print(year, "is not a leap year")

Sample runs: 2024 gives 2024 is a leap year; 1900 gives 1900 is not a leap year.

Teaches: combining conditions with and and or. The full rule: divisible by 4, except century years, which must be divisible by 400. That is why 1900 was not a leap year but 2000 was.

7. Factorial

n = 5
factorial = 1
for i in range(1, n + 1):
    factorial = factorial * i
print("Factorial of", n, "is", factorial)

Output: Factorial of 5 is 120

Teaches: the accumulator pattern, where a variable starts at a value (1 here) and is updated inside a loop. 5! = 1 × 2 × 3 × 4 × 5 = 120. Python also has math.factorial(5) built in, but writing it yourself teaches the logic.

8. Prime number check

n = 29
is_prime = n > 1
for i in range(2, int(n ** 0.5) + 1):
    if n % i == 0:
        is_prime = False
        break
print(n, "is prime" if is_prime else "is not prime")

Output: 29 is prime

Teaches: break to leave a loop early, a True/False flag variable, and a shortcut: you only need to test divisors up to the square root of n (n ** 0.5). Change n to 21 and you get 21 is not prime.

9. Fibonacci series

count = 10
a, b = 0, 1
for _ in range(count):
    print(a, end=" ")
    a, b = b, a + b
print()

Output: 0 1 1 2 3 5 8 13 21 34

Teaches: updating two variables at once with a, b = b, a + b, and end=" " to print on one line. The underscore _ is a common name for a loop variable you do not use.

10. Palindrome check

word = input("Enter a word: ").lower()
if word == word[::-1]:
    print("Palindrome")
else:
    print("Not a palindrome")

Sample run with Madam: Palindrome

Teaches: string slicing. word[::-1] reverses a string. .lower() makes "Madam" and "madam" compare equally.

11. Count words and vowels

sentence = "Python is easy to learn and Python is fun"
vowels = 0
for ch in sentence.lower():
    if ch in "aeiou":
        vowels += 1
print("Words:", len(sentence.split()))
print("Vowels:", vowels)

Output:

Words: 9
Vowels: 11

Teaches: looping through characters, the in operator, += and split(), which breaks text into a list of words at spaces.

12. Largest, smallest and average from a list

prices = [450, 1200, 80, 999, 300]
print("Highest:", max(prices))
print("Lowest:", min(prices))
print("Sorted:", sorted(prices))
print("Average:", sum(prices) / len(prices))

Output:

Highest: 1200
Lowest: 80
Sorted: [80, 300, 450, 999, 1200]
Average: 605.8

Teaches: built-in functions that work on lists. sorted() returns a new sorted list without changing the original. As an exercise, find the largest value with a loop instead of max(); interviewers often ask for that.

13. Celsius to Fahrenheit

celsius = float(input("Temperature in Celsius: "))
fahrenheit = celsius * 9 / 5 + 32
print(celsius, "C =", fahrenheit, "F")

Sample run with 37: 37.0 C = 98.6 F

Teaches: using a formula in code and operator precedence (multiplication and division happen before addition). Try writing the reverse conversion: (f - 32) * 5 / 9.

14. Shopping bill with a dictionary

cart = {"Notebook": 40, "Pen": 10, "Geometry box": 120}
quantity = {"Notebook": 5, "Pen": 4, "Geometry box": 1}
bill = 0
for item, price in cart.items():
    amount = price * quantity[item]
    print(item, "x", quantity[item], "=", amount)
    bill += amount
print("Total bill: Rs.", bill)

Output:

Notebook x 5 = 200
Pen x 4 = 40
Geometry box x 1 = 120
Total bill: Rs. 360

Teaches: dictionaries, which store key–value pairs (item and price), and .items() to loop through both at once. This is the starting point of any billing program.

15. Number guessing game

import random

secret = random.randint(1, 20)
tries = 0
while True:
    guess = int(input("Guess a number from 1 to 20: "))
    tries += 1
    if guess < secret:
        print("Too low")
    elif guess > secret:
        print("Too high")
    else:
        print("Correct! You took", tries, "tries.")
        break

Sample run (your numbers will differ, because the secret is random):

Guess a number from 1 to 20: 10
Too low
Guess a number from 1 to 20: 15
Too high
Guess a number from 1 to 20: 13
Correct! You took 3 tries.

Teaches: importing a module, random.randint(), a while True loop that runs until break, and counting attempts. Improve it by limiting the player to five tries.

Common errors and how to fix them

Error messageUsual causeFix
SyntaxError: expected ':'Missing colon after if, for, while, else or defAdd the colon at the end of the line
IndentationErrorLines in a block are not indented the sameUse four spaces consistently; do not mix tabs and spaces
TypeError: can only concatenate strAdding text and a number with +Convert with str(), or use commas in print
ValueError: invalid literal for int()User typed text or a decimal into int(input())Type a whole number, or use float() for decimals
NameError: name 'Print' is not definedSpelling or capital letters wrongPython is case-sensitive: use print
ZeroDivisionErrorDividing by zeroCheck the divisor first, as in program 2

Reading error messages is a skill in itself. Python tells you the line number and the type of error; start there.

How to practise with this list

  • Change one thing at a time. Make the table go to 20, the guessing game go to 100, or the marks list take input from the user.
  • Predict before you run. Write down what you expect the output to be, then run the program and compare.
  • Combine programs. For example, use program 8 inside a loop to print all prime numbers from 1 to 50 (there are 15 of them).
  • Explain your code aloud. If you can explain each line, you are ready for viva and interview questions.

Practice task

Write a program that asks for a student's name and marks in three subjects, then prints the total, the percentage and the result using the grades from program 4. Then extend it to handle five students using a loop and print the class topper at the end.

Keep going

Once these programs feel easy, you are ready for functions, files and small projects. Our free Python Programming for Beginners course covers all of this step by step, with practice exercises and a verifiable certificate. Preparing for a job? Try our Python interview questions for beginners. Still deciding where to start? Read Which Programming Language Should You Learn First?

Frequently asked questions

How do I run these Python programs?
Install Python from python.org, save the code in a file such as program.py, and run it with python program.py (or python3 program.py on Mac and Linux). You can also use the IDLE editor that comes with Python, or an online Python editor.
Why does input() give me an error when I add numbers?
input() always returns text. Convert it with int() for whole numbers or float() for decimals before doing arithmetic, for example int(input("Enter a number: ")).
What is an IndentationError?
Python uses indentation to group code. Lines inside if, for, while and def blocks must be indented by the same amount, usually four spaces. Mixing tabs and spaces also causes this error.
Which Python programs are asked in exams and interviews?
Common ones include even or odd, largest of numbers, factorial, prime check, Fibonacci series, palindrome, leap year, multiplication table and simple pattern or string programs, much like the ones in this list.
Can I learn Python on a mobile phone?
You can practise small programs with a Python app or an online editor in your phone browser, but a laptop or desktop is much more comfortable for regular practice and bigger projects.

Keep reading

Tutorials 7 min read

Excel Skills Employers Want: A Beginner Roadmap

From typing data neatly to building pivot tables and dashboards, here is a step-by-step roadmap of the Excel skills employers actually test: with a 6-week practice plan and interview tips.

Read article →
Tutorials 8 min read

VLOOKUP vs XLOOKUP in Excel: Which Should You Use?

VLOOKUP and XLOOKUP both fetch values from a table, but they behave differently. See both on the same product list, learn where VLOOKUP goes wrong, and decide which one to use in your work.

Read article →