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.
Table of Content
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!")
2. Add Two Numbers
a = 3
b = 4
print(a + b)
3. Check if Number is Even or Odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("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")
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))
6. Reverse a String
text = "Python"
reversed_text = text[::-1]
print(reversed_text)
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)
8. Check Palindrome String
word = "radar"
if word == word[::-1]:
print(word, "is palindrome")
else:
print(word, "is not 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()
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, '+'))
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))
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)
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)
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))
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)
16. Recursive Fibonacci Function
def fib(n):
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2)
print(fib(7))
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)
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)
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)
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)
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))
22. Detect Palindromic Numbers in a Range
palindromes = [x for x in range(1, 200) if str(x) == str(x)[::-1]]
print(palindromes)
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]))
24. Remove Duplicates from a List
lst = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(lst))
print(unique)
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"))
26. Count Characters in a String
text = "abracadabra"
counts = {}
for ch in text:
counts[ch] = counts.get(ch, 0) + 1
print(counts)
27. Generate List of Squares Using List Comprehension
squares = [x * x for x in range(10)]
print(squares)
28. Transpose a Matrix
matrix = [
[1, 2, 3],
[4, 5, 6]
]
transpose = list(zip(*matrix))
print(transpose)
29. Find the Intersection of Two Sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}
print(set1 & set2)
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))
31. Count Words in a Sentence
sentence = "This is an example sentence"
words_count = len(sentence.split())
print("Word count:", words_count)
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"))
33. Convert Celsius to Fahrenheit
def c_to_f(c):
return (c * 9/5) + 32
print(c_to_f(20))
34. Find GCD of Two Numbers
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(48, 18))
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]))
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])
37. Convert Decimal to Binary
def dec_to_bin(n):
return bin(n)[2:]
print(dec_to_bin(23))
38. Merge Two Dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2}
print(merged)
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()
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))
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)
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)
43. Check if Two Strings Are Anagrams
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
print(are_anagrams("listen", "silent"))
44. Print Multiplication Table
num = 7
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
45. Calculate Average of Numbers in a List
nums = [10, 20, 30, 40, 50]
average = sum(nums) / len(nums)
print(average)
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
Post a Comment