Skip to main content

40+ Python Programs for Beginners and Intermediates Level

40+ Python Programs for Beginners and Intermediates Level
python-programs-for-beginners-and-intermediates-level

40+ Python Programs for Beginners and Intermediates Level

Getting hands-on with real-world programs is the best way to learn and master Python programming. Below, we cover over 40 Python programs suitable for beginner and intermediate coders. Each program example includes code and explanation to help you practice programming fundamentals, problem-solving, and Python syntax.


Beginner Level Programs

These programs focus on basic Python concepts like loops, conditionals, simple functions, string and number manipulation.

1. Hello World

print("Hello, world!")
Hello, world!

2. Add Two Numbers

a = 3
b = 4
print(a + b)
7

3. Check if Number is Even or Odd

num = int(input("Enter a number: "))
if num % 2 == 0:
    print("Even")
else:
    print("Odd")
<!-- For input 5 --> Odd

4. Find Largest of Three Numbers

a, b, c = 5, 9, 3
if a > b and a > c:
    print(a, "is largest")
elif b > a and b > c:
    print(b, "is largest")
else:
    print(c, "is largest")
9 is largest

5. Calculate Factorial of a Number

def factorial(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

print(factorial(5))
120

6. Reverse a String

text = "Python"
reversed_text = text[::-1]
print(reversed_text)
nohtyP

7. Count Vowels in a String

sentence = "Hello World"
vowels = "aeiouAEIOU"
count = sum(1 for ch in sentence if ch in vowels)
print("Number of vowels:", count)
Number of vowels: 3

8. Check Palindrome String

word = "radar"
if word == word[::-1]:
    print(word, "is palindrome")
else:
    print(word, "is not palindrome")
radar is palindrome

9. Print Fibonacci Sequence up to n Terms

n = 10
a, b = 0, 1
for _ in range(n):
    print(a, end=" ")
    a, b = b, a + b
print()
0 1 1 2 3 5 8 13 21 34

10. Simple Calculator

def calculator(a, b, op):
    if op == '+':
        return a + b
    elif op == '-':
        return a - b
    elif op == '*':
        return a * b
    elif op == '/':
        return a / b
    else:
        return "Invalid operator"

print(calculator(5, 3, '+'))
8

Intermediate Level Programs

These examples involve more complex logic like file handling, classes, list comprehensions, recursion, and algorithms.

11. Read a File and Count Lines

with open("example.txt", "r") as f:
    lines = f.readlines()
print("Line count:", len(lines))
<!-- Example output if example.txt has 5 lines --> Line count: 5

12. Write User Input to a File and Read It Back


# Ask the user to enter some text
text = input("Enter some text: ")

# Write the text to a file
with open("output.txt", "w") as file:
    file.write(text)

# Read the content from the file
with open("output.txt", "r") as file:
    savedText = file.read()

# Display the saved text
print("\nText saved in 'output.txt':")
print(savedText)
    
Sample Output: Enter some text: Hello, world! Text saved in 'output.txt': Hello, world!

13. Count Word Frequency in Text

text = "apple banana apple orange banana apple"
words = text.split()
freq = {}
for word in words:
    freq[word] = freq.get(word, 0) + 1
print(freq)
{'apple': 3, 'banana': 2, 'orange': 1}

14. Check Prime Number

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(29))
True

15. Generate List of Prime Numbers up to n

n = 50
primes = [x for x in range(2, n + 1) if is_prime(x)]
print(primes)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

16. Recursive Fibonacci Function

def fib(n):
    if n <= 1:
        return n
    else:
        return fib(n - 1) + fib(n - 2)

print(fib(7))
13

17. Class Example: Simple Bank Account

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
        else:
            print("Insufficient funds")

account = BankAccount("Alice")
account.deposit(100)
account.withdraw(30)
print(account.balance)
70

18. Sort List of Dictionaries by Key

people = [
    {"name": "John", "age": 25},
    {"name": "Jane", "age": 22},
    {"name": "Dave", "age": 30}
]
sorted_people = sorted(people, key=lambda x: x["age"])
print(sorted_people)
[{'name': 'Jane', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Dave', 'age': 30}]

19. Find Common Elements in Two Lists

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common = [x for x in list1 if x in list2]
print(common)
[3, 4]

20. Flatten a Nested List

nested = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat = [num for sublist in nested for num in sublist]
print(flat)
[1, 2, 3, 4, 5, 6, 7, 8]

21. Calculate Factorial Using Recursion

def factorial_recursive(n):
    if n == 0:
        return 1
    else:
        return n * factorial_recursive(n - 1)

print(factorial_recursive(6))
720

22. Detect Palindromic Numbers in a Range

palindromes = [x for x in range(1, 200) if str(x) == str(x)[::-1]]
print(palindromes)
[1, 2, 3, ..., 191, 202]

23. Merge Two Sorted Lists

def merge_sorted(lst1, lst2):
    i, j = 0, 0
    merged = []
    while i < len(lst1) and j < len(lst2):
        if lst1[i] < lst2[j]:
            merged.append(lst1[i])
            i += 1
        else:
            merged.append(lst2[j])
            j += 1
    merged.extend(lst1[i:])
    merged.extend(lst2[j:])
    return merged

print(merge_sorted([1, 3, 5], [2, 4, 6]))
[1, 2, 3, 4, 5, 6]

24. Remove Duplicates from a List

lst = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(lst))
print(unique)
[1, 2, 3, 4, 5]

25. Validate Email Address (Basic Check)

import re

def is_valid_email(email):
    pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
    return re.match(pattern, email) is not None

print(is_valid_email("test@example.com"))
True

26. Count Characters in a String

text = "abracadabra"
counts = {}
for ch in text:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)
{'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}

27. Generate List of Squares Using List Comprehension

squares = [x * x for x in range(10)]
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

28. Transpose a Matrix

matrix = [
    [1, 2, 3],
    [4, 5, 6]
]
transpose = list(zip(*matrix))
print(transpose)
[(1, 4), (2, 5), (3, 6)]

29. Find the Intersection of Two Sets

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
print(set1 & set2)
{3, 4}

30. Generate Random Password

import random
import string

def generate_password(length=8):
    chars = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(chars) for _ in range(length))

print(generate_password(10))
<!-- Example: outputs a random 10-character password --> # (Random password output varies)

31. Count Words in a Sentence

sentence = "This is an example sentence"
words_count = len(sentence.split())
print("Word count:", words_count)
Word count: 5

32. Check if String is a Valid Number

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

print(is_number("12.34"))
True

33. Convert Celsius to Fahrenheit

def c_to_f(c):
    return (c * 9/5) + 32

print(c_to_f(20))
68.0

34. Find GCD of Two Numbers

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

print(gcd(48, 18))
6

35. Check if a List is Sorted

def is_sorted(lst):
    return all(lst[i] <= lst[i+1] for i in range(len(lst)-1))

print(is_sorted([1, 2, 2, 3]))
True

36. Find the Second Largest Number in a List

lst = [5, 8, 2, 9, 4]
unique_lst = list(set(lst))
unique_lst.sort()
print(unique_lst[-2])
8

37. Convert Decimal to Binary

def dec_to_bin(n):
    return bin(n)[2:]

print(dec_to_bin(23))
10111

38. Merge Two Dictionaries

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2}
print(merged)
{'a': 1, 'b': 3, 'c': 4}

39. Create a Simple To-Do List Application

todos = []

def add_task(task):
    todos.append(task)

def show_tasks():
    for i, task in enumerate(todos, 1):
        print(f"{i}. {task}")

add_task("Learn Python")
add_task("Practice coding")
show_tasks()
1. Learn Python 2. Practice coding

40. Calculate the Power of a Number Using Recursion

def power(base, exp):
    if exp == 0:
        return 1
    return base * power(base, exp - 1)

print(power(2, 5))
32

41. Remove Punctuation from a String

import string

text = "Hello, world! How's it going?"
no_punct = ''.join(ch for ch in text if ch not in string.punctuation)
print(no_punct)
Hello world Hows it going

42. Find Largest Word in a Sentence

sentence = "Find the biggest word in this sentence"
words = sentence.split()
largest = max(words, key=len)
print(largest)
biggest

43. Check if Two Strings Are Anagrams

def are_anagrams(s1, s2):
    return sorted(s1) == sorted(s2)

print(are_anagrams("listen", "silent"))
True

44. Print Multiplication Table

num = 7
for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70

45. Calculate Average of Numbers in a List

nums = [10, 20, 30, 40, 50]
average = sum(nums) / len(nums)
print(average)
30.0

Useful Tips for Practicing

  • Understand each program: Don't just run code — try to read and understand every line.
  • Modify and experiment: Change input values or add features to deepen learning.
  • Write from scratch: Try rewriting the program without looking to improve retention.
  • Learn debugging: Intentionally create errors to practice fixing problems.
  • Use online interpreters or local setup: Practice executing these scripts often.
  • Challenge yourself: Combine simple programs into bigger projects pushing your skills.

Conclusion

Practicing these 40+ Python programs will build your confidence and skills from beginner to intermediate levels. Focus on understanding concepts behind each example, and challenge yourself with variations or expansions of these scripts. With steady practice, you'll soon be able to tackle real-world problems with Python efficiently and elegantly.

Comments