#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Python Sample Code for Beginners

Looking for basic Python programs or simple Python code examples to practise? If you have just installed Python and don’t know what to write next, this page is for you. Below are 18 short programs. Each one teaches one small idea — variables, if conditions, loops, functions or strings. Type them yourself instead of copy-pasting. Typing is how your fingers and brain learn the syntax.

Blogging Illustration

18 Simple Python Programs for Beginners (With Code and Output)

All programs were run on Python 3.12. If you use Python 3.8 or newer, the output will be the same.

How to run a program: save the code in a file such as practice.py, open the terminal in that folder and run python practice.py (on some Mac and Linux systems the command is python3).

1. Hello, World!

print("Hello, World!")

Output

Hello, World!

print() shows text on the screen. Text must be inside quotes.

2. Add two numbers

a = 10
b = 5
print("Sum:", a + b)

Output

Sum: 15

a and b are variables — names that store values. When you give print() two things separated by a comma, it puts a space between them.

3. Take input from the user

name = input("Enter your name: ")
print("Hello, " + name + "!")

Sample output (user typed Riya)

Enter your name: Riya
Hello, Riya!

input() always gives you text (a string). If you need a number, convert it: age = int(input("Age: ")).

4. Check even or odd

num = 7
if num % 2 == 0:
    print(num, "is even")
else:
    print(num, "is odd")

Output

7 is odd

% gives the remainder. If a number divided by 2 leaves remainder 0, it is even. Notice the 4 spaces before the print lines — Python uses indentation to know which lines belong to the if.

5. Largest of three numbers

x, y, z = 12, 45, 29
print("Largest:", max(x, y, z))

largest = x
if y > largest:
    largest = y
if z > largest:
    largest = z
print("Largest (without max):", largest)

Output

Largest: 45
Largest (without max): 45

In real code you will use max(). In interviews and exams you may be asked to do it without built-in functions, so practise both ways.

6. Swap two variables

p, q = 3, 8
p, q = q, p
print("p =", p, "q =", q)

Output

p = 8 q = 3

Python can swap in one line. In C or Java you would need a third temporary variable.

7. Simple interest

principal = 50000
rate = 8
years = 3
si = (principal * rate * years) / 100
print("Simple interest:", si)

Output

Simple interest: 12000.0

The answer has .0 because / always returns a decimal (float) in Python 3. Use // if you want whole-number division.

8. Factorial using a loop

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

Output

Factorial of 5 is 120

range(1, n + 1) gives 1, 2, 3, 4, 5. The end value is not included, which is why we write n + 1.

9. Fibonacci series

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

Output

0 1 1 2 3 5 8 13 21 34

Each number is the sum of the two before it. end=" " keeps the numbers on one line.

10. Check if a number is prime

def is_prime(n):
    if n < 2:
        return False
    i = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += 1
    return True

for n in [1, 2, 15, 17, 97]:
    print(n, "->", "prime" if is_prime(n) else "not prime")

Output

1 -> not prime
2 -> prime
15 -> not prime
17 -> prime
97 -> prime

We only check divisors up to the square root (i * i <= n). If a number has a factor bigger than its square root, it must also have one smaller, so checking further is wasted work.

11. Reverse a string

text = "uncodemy"
print(text[::-1])

Output

ymedocnu

[::-1] is slicing with a step of -1, which reads the string from the end.

12. Palindrome check

word = "Madam"
clean = word.lower()
print(word, "is a palindrome" if clean == clean[::-1] else "is not a palindrome")

Output

Madam is a palindrome

We convert to lower case first, otherwise “M” and “m” are treated as different letters.

13. Total and average of marks

marks = [78, 85, 62, 90, 71]
total = sum(marks)
print("Total:", total, "Average:", total / len(marks))

Output

Total: 386 Average: 77.2

A list stores many values in one variable. len() tells you how many items it has.

14. Count vowels in a sentence

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

Output

Vowels: 7

You can loop over a string one character at a time. in checks whether the character exists in “aeiou”.

15. Multiplication table

n = 7
for i in range(1, 11):
    print(n, "x", i, "=", n * i)

Output

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

16. A small calculator using a function

def calculate(a, b, op):
    if op == "+":
        return a + b
    elif op == "-":
        return a - b
    elif op == "*":
        return a * b
    elif op == "/":
        if b == 0:
            return "Cannot divide by zero"
        return a / b
    else:
        return "Unknown operator"

print(calculate(20, 4, "/"))
print(calculate(20, 0, "/"))
print(calculate(6, 7, "*"))

Output

5.0
Cannot divide by zero
42

Always handle division by zero. Without that check, Python stops with a ZeroDivisionError.

17. Celsius to Fahrenheit

c = 37
f = (c * 9 / 5) + 32
print(c, "C =", f, "F")

Output

37 C = 98.6 F

18. Leap year check

for year in [1900, 2000, 2024, 2026]:
    leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
    print(year, "leap" if leap else "not leap")

Output

1900 not leap
2000 leap
2024 leap
2026 not leap

Many beginners write only year % 4 == 0. That gives the wrong answer for 1900. A year divisible by 100 is a leap year only if it is also divisible by 400.

A typical first-week situation

Imagine a beginner — let’s call her Riya — writing program 3 and program 2 together. She asks for two numbers with input(), adds them, and proudly types 5 and 3. The screen says 53. She checks the code five times and finds nothing wrong, because there is no typing mistake. The problem is that input() gave her two pieces of text, and adding text just joins it. One small change — int(input(...)) — and the answer becomes 8.

This exact moment is worth more than ten programs copied from a website. Once you have been confused by your own output and fixed it yourself, you never forget how data types work.

Common mistakes beginners make with these programs

  • Forgetting to convert input. input() returns text, so "5" + "3" gives "53", not 8. Use int() or float().
  • Mixing tabs and spaces. Pick 4 spaces and stick to it. Most editors (VS Code, PyCharm) do this automatically.
  • Using = instead of == in conditions. = stores a value; == compares.
  • Naming a variable sum, list or input. It hides the built-in function and causes confusing errors later.
  • Copy-pasting without running. Change the numbers, break the code on purpose, read the error message. That is where real learning happens.

Practice tasks (try before you look anything up)

  1. Change program 10 to print all prime numbers between 1 and 100.
  2. Change program 12 so it ignores spaces: “nurses run” should count as a palindrome.
  3. Write a program that asks for 5 numbers and prints the smallest one without using min().
  4. Make the calculator in program 16 keep asking for input until the user types exit.

What to learn after these programs

Once these feel easy, move to: lists and dictionaries in more depth, reading and writing files, error handling with try/except, and small projects like a to-do list or a quiz game. The official Python tutorial is the best free next step.

Frequently asked questions

Which Python version should I install?

Install the latest stable Python 3 version from python.org. Python 2 is no longer supported.

Do I need to know maths to learn Python?

Only basic school maths for these programs. Data science and machine learning need more statistics later.

How many programs should I practise daily?

Quality matters more than quantity. Two or three programs that you write, run and modify yourself are better than ten you only read.

References

Placed Students

Our Clients

Partners