Python Programs with Output: 34 Basic Programs for Practice (with Engineering Examples)

Python Programs with Output – 34 tested programs for practice

Quick answer: Below are 34 Python programs with code and output for beginners and students – basic programs (hello world, add numbers, even/odd, leap year), number programs (factorial, Fibonacci, prime, Armstrong), string programs (reverse string, palindrome, anagram), list programs (sorting, duplicates, binary search) and engineering programs (stress, Reynolds number, beam deflection). Every program was run on Python 3.13 and the output shown is real.

Practise by typing each program yourself, running it, then changing the input values. Use them for lab records, practice questions and interview preparation.

Contents

Basic Python Programs

1. Hello World program

The first program in any language – print() writes text to the screen.

print("Hello, World!")

Output:

Hello, World!

2. Add two numbers

Variables store values; + adds them.

a = 15
b = 27
print("Sum:", a + b)

Output:

Sum: 42

3. Swap two variables

Python can swap values in one line using tuple unpacking.

a, b = 5, 9
a, b = b, a
print("a =", a, "b =", b)

Output:

a = 9 b = 5

4. Check even or odd

The modulus operator % gives the remainder.

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

Output:

7 is odd

5. Largest of three numbers

max() returns the largest value.

a, b, c = 12, 45, 30
print("Largest:", max(a, b, c))

Output:

Largest: 45

6. Check leap year

A year is a leap year if divisible by 4 but not by 100, or divisible by 400.

year = 2024
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")

Output:

2024 is a leap year

7. Celsius to Fahrenheit

F = C × 9/5 + 32.

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

Output:

37 C = 98.6 F

8. Multiplication table

A for loop with range() repeats a block.

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

Output:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

9. Roots of a quadratic equation

Use the discriminant d = b² − 4ac and math.sqrt().

import math
a, b, c = 1, -5, 6
d = b * b - 4 * a * c
r1 = (-b + math.sqrt(d)) / (2 * a)
r2 = (-b - math.sqrt(d)) / (2 * a)
print("Roots:", r1, r2)

Output:

Roots: 3.0 2.0

Number Programs

10. Factorial of a number

Multiply all integers from 1 to n.

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

Output:

Factorial of 5 is 120

11. Fibonacci series

Each number is the sum of the previous two.

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

Output:

0 1 1 2 3 5 8 13 21 34

12. Check prime number

Check divisibility only up to the square root of n.

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

Output:

29 is prime

13. Prime numbers in a range

A list comprehension with all() collects primes from 2 to 50.

primes = [n for n in range(2, 51) if all(n % i for i in range(2, int(n ** 0.5) + 1))]
print(primes)

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

14. Reverse a number

Take the last digit with % 10 and remove it with // 10.

n = 12345
rev = 0
while n > 0:
    rev = rev * 10 + n % 10
    n //= 10
print(rev)

Output:

54321

15. Armstrong number

A number equal to the sum of its digits each raised to the number of digits.

n = 153
digits = str(n)
total = sum(int(d) ** len(digits) for d in digits)
print(n, "is an Armstrong number" if total == n else "is not an Armstrong number")

Output:

153 is an Armstrong number

16. Sum of digits

Convert to a string and add each digit.

n = 9875
print("Sum of digits:", sum(int(d) for d in str(n)))

Output:

Sum of digits: 29

17. GCD and LCM

math.gcd() gives the GCD; LCM = a × b / GCD.

import math
print("GCD:", math.gcd(48, 36))
print("LCM:", 48 * 36 // math.gcd(48, 36))

Output:

GCD: 12
LCM: 144

String Programs

18. Reverse a string

Slicing with step −1 reverses any sequence.

s = "Engineers"
print(s[::-1])

Output:

sreenignE

19. Check palindrome string

A palindrome reads the same forwards and backwards.

s = "madam"
print(s, "is a palindrome" if s == s[::-1] else "is not a palindrome")

Output:

madam is a palindrome

20. Count vowels in a string

Loop through characters and count those in “aeiou”.

s = "mechanical engineering"
count = sum(1 for ch in s if ch in "aeiou")
print("Vowels:", count)

Output:

Vowels: 9

21. Character frequency

collections.Counter counts each character.

from collections import Counter
s = "banana"
print(dict(Counter(s)))

Output:

{'b': 1, 'a': 3, 'n': 2}

22. Check anagrams

Two words are anagrams if their sorted letters match.

a, b = "listen", "silent"
print(sorted(a) == sorted(b))

Output:

True

List and Array Programs

23. Max, min and average of a list

Built-in functions max(), min(), sum() and len().

marks = [72, 85, 64, 91, 78]
print("Max:", max(marks), "Min:", min(marks), "Average:", sum(marks) / len(marks))

Output:

Max: 91 Min: 64 Average: 78.0

24. Remove duplicates from a list

dict.fromkeys() keeps order and removes repeats.

nums = [3, 1, 3, 2, 1, 5]
unique = list(dict.fromkeys(nums))
print(unique)

Output:

[3, 1, 2, 5]

25. Sort a list

sorted() returns a new sorted list; reverse=True sorts in descending order.

nums = [42, 7, 19, 3, 25]
print(sorted(nums))
print(sorted(nums, reverse=True))

Output:

[3, 7, 19, 25, 42]
[42, 25, 19, 7, 3]

26. Second largest number

Remove duplicates, sort and pick the second last value.

nums = [10, 45, 32, 45, 28]
print("Second largest:", sorted(set(nums))[-2])

Output:

Second largest: 32

27. Bubble sort

Repeatedly swap adjacent elements that are in the wrong order.

arr = [64, 34, 25, 12, 22]
n = len(arr)
for i in range(n):
    for j in range(n - i - 1):
        if arr[j] > arr[j + 1]:
            arr[j], arr[j + 1] = arr[j + 1], arr[j]
print(arr)

Output:

[12, 22, 25, 34, 64]

28. Binary search

Search a sorted list by halving the range each step.

def binary_search(arr, target):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if arr[mid] == target:
            return mid
        if arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

print(binary_search([3, 8, 15, 21, 34, 50], 21))

Output:

3

29. Add two matrices

Nested list comprehension adds element by element.

A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
C = [[A[i][j] + B[i][j] for j in range(2)] for i in range(2)]
print(C)

Output:

[[6, 8], [10, 12]]

30. Star pattern

String multiplication repeats a character.

for i in range(1, 5):
    print("*" * i)

Output:

*
**
***
****

Python Programs for Engineering Students

31. Normal stress calculator

Stress = Force / Area. Convert Pa to MPa by dividing by 10⁶.

force = 5000        # N
area = 25e-6        # m^2 (25 mm^2)
stress = force / area
print("Stress =", stress / 1e6, "MPa")

Output:

Stress = 200.0 MPa

32. Reynolds number and flow type

Re = ρVD/μ decides laminar or turbulent pipe flow.

rho, v, d, mu = 1000, 2.0, 0.05, 0.001
re = rho * v * d / mu
flow = "laminar" if re < 2000 else "turbulent" if re > 4000 else "transitional"
print("Re =", re, "->", flow)

Output:

Re = 100000.0 -> turbulent

33. Cantilever beam deflection

Maximum deflection under an end load: δ = PL³ / (3EI).

P, L, E, I = 1000, 2.0, 200e9, 8e-6   # N, m, Pa, m^4
deflection = P * L**3 / (3 * E * I)
print(f"Max deflection = {deflection * 1000:.3f} mm")

Output:

Max deflection = 1.667 mm

34. Otto cycle efficiency

η = 1 − 1/r^(γ−1) for different compression ratios.

gamma = 1.4
for r in [6, 8, 10]:
    eff = 1 - 1 / r ** (gamma - 1)
    print(f"r = {r}: efficiency = {eff * 100:.1f}%")

Output:

r = 6: efficiency = 51.2%
r = 8: efficiency = 56.5%
r = 10: efficiency = 60.2%

Python Practice Questions (Try Yourself)

  1. Find the sum of all even numbers from 1 to 100.
  2. Count the words in a sentence.
  3. Check whether a number is a perfect number.
  4. Convert a decimal number to binary without bin().
  5. Find common elements in two lists.
  6. Calculate the area and perimeter of a circle for radius input.
  7. Print a number pyramid.
  8. Find the factorial using recursion.
  9. Merge two dictionaries.
  10. Calculate torque from force and radius for 5 values using a loop.

Frequently Asked Questions

What are the basic Python programs for beginners?

Hello world, adding numbers, even or odd, largest of three numbers, leap year, factorial, Fibonacci series, prime numbers, palindrome and reversing a string are the standard beginner programs.

How do I practise Python programs?

Type each program yourself, run it, change the inputs, then solve a similar problem without looking at the code. Ten to fifteen programs a week builds strong basics.

Which Python programs are asked in interviews?

Reverse a string, palindrome, Fibonacci, prime check, second largest number, anagrams, duplicates removal, character frequency and binary search are common. See our Python interview questions for more.

Can I run these programs online?

Yes. You can paste them into any online Python interpreter or Google Colab, or install Python from python.org and run them locally.

Related Python Guides

Scroll to Top