A good way to learn Python is to write small programs: check if a number is prime, reverse a string, sort a list, read a file. Each one teaches one idea, and together they cover what a beginner needs for college practicals and coding rounds.
This page has 100 Python programs with examples, grouped from basic to advanced. Every program shows its real output, and you can edit and run it right here in your browser, with no installation. After the programs come 30 Python programs for practice that test your code automatically. Want to study offline? Download all 100 programs as a free PDF.
What you will find on this page
- 100 Python programs with clear explanations and real output, from Hello World to classes and files.
- A “Run this program” button on every program. Python runs in your browser, so you can change the code and see what happens.
- 30 practice questions (10 easy, 12 medium, 8 hard) that run your code against test cases and show what passed.
- Links to step-by-step guides for 23 of the programs, with dry runs and time complexity.
- A free 45-page PDF of everything.
Jump to a topic
Run Python programs online
Type any Python code below and press Run (or Ctrl + Enter). It runs on real Python inside your browser, so it works on a phone or a college lab computer with nothing installed. Python loads the first time you press Run. input() is not supported here, so put your values in variables, as the programs on this page do.
Online Python editor
Real Python running in your browser. Nothing is sent to a server.
Basic Python programs
Start here if you are new to Python. These simple Python programs cover printing, variables, arithmetic and the math module.
1. Print Hello, World!
The traditional first program. print() writes text to the screen.
print("Hello, World!")
print("Welcome to Code and Debug")Output:
Hello, World!
Welcome to Code and Debug2. Add two numbers
Store numbers in variables and add them. On your own computer, use int(input("Enter a number: ")) to read them from the keyboard.
a = 15
b = 27
total = a + b
print("Sum:", total)
print(f"{a} + {b} = {total}")Output:
Sum: 42
15 + 27 = 423. Swap two variables
Python can swap two values in one line with tuple unpacking, without a temporary variable.
x = 5
y = 10
print("Before:", x, y)
x, y = y, x
print("After:", x, y)Output:
Before: 5 10
After: 10 54. Area and circumference of a circle
Use math.pi and round() to keep the output tidy.
import math
r = 7
area = math.pi * r ** 2
circumference = 2 * math.pi * r
print("Area:", round(area, 2))
print("Circumference:", round(circumference, 2))Output:
Area: 153.94
Circumference: 43.985. Simple and compound interest
Simple interest is P × R × T / 100. Compound interest grows on the interest already earned.
p, r, t = 10000, 8, 3 # principal, rate %, years
simple = p * r * t / 100
compound = p * (1 + r / 100) ** t - p
print("Simple interest:", simple)
print("Compound interest:", round(compound, 2))Output:
Simple interest: 2400.0
Compound interest: 2597.126. Convert Celsius to Fahrenheit
F = C × 9/5 + 32, and the reverse.
c = 37
f = c * 9 / 5 + 32
print(f"{c}°C = {f}°F")
f = 98.6
c = (f - 32) * 5 / 9
print(f"{f}°F = {round(c, 1)}°C")Output:
37°C = 98.6°F
98.6°F = 37.0°C7. Convert kilometres to miles
One kilometre is about 0.621371 miles.
km = 21.1 # a half marathon
miles = km * 0.621371
print(f"{km} km = {miles:.2f} miles")Output:
21.1 km = 13.11 miles8. Find the square root of a number
math.sqrt() works for positive numbers; ** 0.5 does the same job.
import math
n = 50
print("math.sqrt:", round(math.sqrt(n), 4))
print("n ** 0.5:", round(n ** 0.5, 4))
print("math.isqrt:", math.isqrt(n)) # whole-number partOutput:
math.sqrt: 7.0711
n ** 0.5: 7.0711
math.isqrt: 79. Solve a quadratic equation
The roots of ax² + bx + c = 0 come from the quadratic formula. cmath also handles negative discriminants (complex roots).
import cmath
a, b, c = 1, -5, 6
d = b * b - 4 * a * c
root1 = (-b + cmath.sqrt(d)) / (2 * a)
root2 = (-b - cmath.sqrt(d)) / (2 * a)
print("Roots:", root1.real, root2.real)
a, b, c = 1, 2, 5
d = b * b - 4 * a * c
print("Complex roots:", (-b + cmath.sqrt(d)) / (2 * a), (-b - cmath.sqrt(d)) / (2 * a))Output:
Roots: 3.0 2.0
Complex roots: (-1+2j) (-1-2j)10. Generate random numbers
random.seed() makes the “random” results repeatable, which is useful for testing. Remove it to get new numbers every run.
import random
random.seed(42)
print("Dice roll:", random.randint(1, 6))
print("Random choice:", random.choice(["Python", "Java", "C++"]))
cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print("Shuffled:", cards)Output:
Dice roll: 6
Random choice: Python
Shuffled: [2, 4, 5, 3, 1]Number programs in Python
Classic programs on numbers: even and odd, prime, Armstrong, palindrome, GCD and more. These come up often in Python practical exams and fresher interviews.
11. Check if a number is even or odd
A number is even when dividing by 2 leaves no remainder: n % 2 == 0.
for n in [7, 12, 0, -3]:
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")Output:
7 is odd
12 is even
0 is even
-3 is odd12. Find the largest of three numbers
Compare with if-elif-else, or simply use the built-in max().
a, b, c = 42, 87, 19
if a >= b and a >= c:
largest = a
elif b >= c:
largest = b
else:
largest = c
print("Largest:", largest)
print("Using max():", max(a, b, c))Output:
Largest: 87
Using max(): 8713. Check for a leap year
A year is a leap year if it is divisible by 4, except century years, which must be divisible by 400.
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
for y in [2024, 1900, 2000, 2026]:
print(y, "is a leap year" if is_leap(y) else "is not a leap year")Output:
2024 is a leap year
1900 is not a leap year
2000 is a leap year
2026 is not a leap year14. Check if a number is positive, negative or zero
A simple if-elif-else chain.
for n in [15, -4, 0]:
if n > 0:
print(n, "is positive")
elif n < 0:
print(n, "is negative")
else:
print(n, "is zero")Output:
15 is positive
-4 is negative
0 is zero15. Check if a number is prime
A prime number has no divisors other than 1 and itself. You only need to test divisors up to the square root of n.
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 [2, 15, 29, 97, 100]:
print(n, "is prime" if is_prime(n) else "is not prime")Output:
2 is prime
15 is not prime
29 is prime
97 is prime
100 is not primeStep-by-step guide with a dry run and time complexity: Check if a number is prime.
16. Print all prime numbers in a range
Reuse the prime check in a loop. For large ranges, the Sieve of Eratosthenes is much faster.
def is_prime(n):
if n < 2:
return False
return all(n % i for i in range(2, int(n ** 0.5) + 1))
primes = [n for n in range(1, 51) if is_prime(n)]
print("Primes up to 50:", primes)
print("Count:", len(primes))Output:
Primes up to 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Count: 1517. Find the factorial of a number
n! = 1 × 2 × … × n. Here is a loop version; the linked post explains the recursive one.
import math
n = 6
fact = 1
for i in range(1, n + 1):
fact *= i
print(f"{n}! = {fact}")
print("math.factorial:", math.factorial(10))Output:
6! = 720
math.factorial: 3628800Step-by-step guide with a dry run and time complexity: Find the factorial of a number.
18. Print the Fibonacci series
Each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8…
n = 10
a, b = 0, 1
series = []
for _ in range(n):
series.append(a)
a, b = b, a + b
print("First", n, "Fibonacci numbers:", series)Output:
First 10 Fibonacci numbers: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Step-by-step guide with a dry run and time complexity: Print the Fibonacci series.
19. Check for an Armstrong number
An Armstrong number equals the sum of its digits, each raised to the power of the number of digits. 153 = 1³ + 5³ + 3³.
def is_armstrong(n):
digits = str(n)
power = len(digits)
return n == sum(int(d) ** power for d in digits)
for n in [153, 370, 9474, 123]:
print(n, "is an Armstrong number" if is_armstrong(n) else "is not an Armstrong number")Output:
153 is an Armstrong number
370 is an Armstrong number
9474 is an Armstrong number
123 is not an Armstrong numberStep-by-step guide with a dry run and time complexity: Check for an Armstrong number.
20. Find Armstrong numbers in an interval
Loop over a range and keep the numbers that pass the check.
def is_armstrong(n):
s = str(n)
return n == sum(int(d) ** len(s) for d in s)
print([n for n in range(100, 10000) if is_armstrong(n)])Output:
[153, 370, 371, 407, 1634, 8208, 9474]21. Check if a number is a palindrome
A palindrome number reads the same backwards, like 121 or 1331.
def is_palindrome(n):
original, reverse = n, 0
while n > 0:
reverse = reverse * 10 + n % 10
n //= 10
return original == reverse
for n in [121, 1331, 123, 7]:
print(n, "->", is_palindrome(n))Output:
121 -> True
1331 -> True
123 -> False
7 -> TrueStep-by-step guide with a dry run and time complexity: Check if a number is a palindrome.
22. Reverse a number
Take the last digit with % 10, remove it with // 10, and build the reversed number.
n = 12345
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
print("Reversed:", rev)
print("Using strings:", int(str(9870)[::-1]))Output:
Reversed: 54321
Using strings: 789Step-by-step guide with a dry run and time complexity: Reverse a number.
23. Find the sum of digits of a number
The same digit-extraction trick, adding each digit to a total.
n = 98765
total = 0
while n > 0:
total += n % 10
n //= 10
print("Sum of digits:", total)
print("One-liner:", sum(int(d) for d in str(98765)))Output:
Sum of digits: 35
One-liner: 35Step-by-step guide with a dry run and time complexity: Find the sum of digits of a number.
24. Count the digits in a number
Count how many times you can remove a digit, or use len(str(n)).
n = 4096013
count = 0
temp = n
while temp > 0:
count += 1
temp //= 10
print("Digits:", count)
print("Using len:", len(str(n)))Output:
Digits: 7
Using len: 7Step-by-step guide with a dry run and time complexity: Count the digits in a number.
25. Find the GCD (HCF) of two numbers
The Euclidean algorithm: replace (a, b) with (b, a % b) until b is 0.
import math
def gcd(a, b):
while b:
a, b = b, a % b
return a
print("GCD of 48 and 180:", gcd(48, 180))
print("math.gcd:", math.gcd(48, 180))Output:
GCD of 48 and 180: 12
math.gcd: 1226. Find the LCM of two numbers
LCM(a, b) = a × b / GCD(a, b).
import math
a, b = 12, 18
lcm = a * b // math.gcd(a, b)
print("LCM:", lcm)
print("math.lcm:", math.lcm(4, 6, 10))Output:
LCM: 36
math.lcm: 6027. Print all divisors of a number
Check every number up to n, or only up to √n and add both i and n // i.
n = 36
divisors = [i for i in range(1, n + 1) if n % i == 0]
print("Divisors of", n, ":", divisors)Output:
Divisors of 36 : [1, 2, 3, 4, 6, 9, 12, 18, 36]Step-by-step guide with a dry run and time complexity: Print all divisors of a number.
28. Check for a perfect number
A perfect number equals the sum of its proper divisors: 28 = 1 + 2 + 4 + 7 + 14.
def is_perfect(n):
return n > 1 and sum(i for i in range(1, n) if n % i == 0) == n
print([n for n in range(1, 10000) if is_perfect(n)])Output:
[6, 28, 496, 8128]29. Check for a strong number
A strong number equals the sum of the factorials of its digits: 145 = 1! + 4! + 5!.
import math
def is_strong(n):
return n == sum(math.factorial(int(d)) for d in str(n))
for n in [145, 40585, 123]:
print(n, "->", is_strong(n))Output:
145 -> True
40585 -> True
123 -> False30. Convert decimal to binary, octal and hexadecimal
Built-in bin(), oct() and hex(), plus a manual binary conversion.
n = 156
print(bin(n), oct(n), hex(n))
bits = ""
temp = n
while temp > 0:
bits = str(temp % 2) + bits
temp //= 2
print("Manual binary:", bits)
print("Back to decimal:", int("10011100", 2))Output:
0b10011100 0o234 0x9c
Manual binary: 10011100
Back to decimal: 15631. Print a multiplication table
A for loop with an f-string for neat alignment.
n = 7
for i in range(1, 11):
print(f"{n} x {i:2} = {n * i:3}")Output:
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 = 7032. Find the sum of natural numbers
Use a loop, sum(range()), or the formula n(n + 1)/2.
n = 100
total = 0
for i in range(1, n + 1):
total += i
print("Loop:", total)
print("sum(range):", sum(range(1, n + 1)))
print("Formula:", n * (n + 1) // 2)Output:
Loop: 5050
sum(range): 5050
Formula: 505033. Calculate the power of a number
Multiply in a loop, or use ** and pow(). pow(a, b, m) computes a to the power b modulo m efficiently.
base, exp = 3, 5
result = 1
for _ in range(exp):
result *= base
print("Loop:", result)
print("** operator:", base ** exp)
print("pow with mod:", pow(2, 100, 1_000_000_007))Output:
Loop: 243
** operator: 243
pow with mod: 976371285Pattern programs in Python
Pattern programs train you to think in nested loops: the outer loop picks the row, the inner loop prints what goes in it.
34. Print 1 to N without a loop
Recursion can replace a loop: the function prints a number and calls itself with the next one.
def print_up_to(i, n):
if i > n:
return
print(i, end=" ")
print_up_to(i + 1, n)
print_up_to(1, 10)
print()Output:
1 2 3 4 5 6 7 8 9 10 Step-by-step guide with a dry run and time complexity: Print 1 to N without a loop.
35. Right-angled triangle of stars
Row i has i stars.
n = 5
for i in range(1, n + 1):
print("*" * i)Output:
*
**
***
****
*****36. Inverted triangle of stars
Count rows down instead of up.
n = 5
for i in range(n, 0, -1):
print("*" * i)Output:
*****
****
***
**
*37. Pyramid pattern
Each row has spaces on the left and an odd number of stars.
n = 5
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))Output:
*
***
*****
*******
*********38. Diamond pattern
A pyramid followed by an upside-down pyramid.
n = 4
for i in list(range(1, n + 1)) + list(range(n - 1, 0, -1)):
print(" " * (n - i) + "*" * (2 * i - 1))Output:
*
***
*****
*******
*****
***
*39. Number triangle
Print the numbers 1 to i on row i.
n = 5
for i in range(1, n + 1):
print(" ".join(str(j) for j in range(1, i + 1)))Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 540. Floyd’s triangle
Consecutive numbers fill each row, one more per row.
n = 5
num = 1
for i in range(1, n + 1):
row = []
for _ in range(i):
row.append(f"{num:2}")
num += 1
print(" ".join(row))Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 1541. Pascal’s triangle
Each number is the sum of the two numbers above it.
n = 6
row = [1]
for i in range(n):
print(" " * (n - i) + " ".join(map(str, row)))
row = [1] + [row[j] + row[j + 1] for j in range(len(row) - 1)] + [1]Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 142. Alphabet pattern
chr() turns a number into a letter: chr(65) is “A”.
n = 5
for i in range(n):
print(" ".join(chr(65 + j) for j in range(i + 1)))Output:
A
A B
A B C
A B C D
A B C D E43. Hollow square
Print a star only on the border: first row, last row, first column or last column.
n = 5
for i in range(n):
row = ""
for j in range(n):
row += "* " if i in (0, n - 1) or j in (0, n - 1) else " "
print(row.rstrip())Output:
* * * * *
* *
* *
* *
* * * * *String programs in Python
Strings are sequences of characters, so slicing, loops and dictionaries all work on them. Remember that strings are immutable: every change creates a new string.
44. Reverse a string
Slicing with a step of -1 is the shortest way.
s = "Code and Debug"
print(s[::-1])
print("".join(reversed(s)))Output:
gubeD dna edoC
gubeD dna edoC45. Check if a string is a palindrome
Clean the string (lowercase, letters only), then compare it with its reverse.
def is_palindrome(s):
clean = "".join(ch.lower() for ch in s if ch.isalnum())
return clean == clean[::-1]
for s in ["madam", "Never odd or even", "python"]:
print(repr(s), "->", is_palindrome(s))Output:
'madam' -> True
'Never odd or even' -> True
'python' -> FalseStep-by-step guide with a dry run and time complexity: Check if a string is a palindrome.
46. Count vowels and consonants
Check each letter against a set of vowels.
s = "Python Programming"
vowels = set("aeiouAEIOU")
v = sum(1 for ch in s if ch in vowels)
c = sum(1 for ch in s if ch.isalpha() and ch not in vowels)
print("Vowels:", v)
print("Consonants:", c)Output:
Vowels: 4
Consonants: 1347. Count the words in a sentence
split() with no argument splits on any whitespace and ignores extra spaces.
s = " Python is easy to learn "
words = s.split()
print("Words:", words)
print("Count:", len(words))Output:
Words: ['Python', 'is', 'easy', 'to', 'learn']
Count: 548. Count the frequency of each character
Use a dictionary, or collections.Counter.
from collections import Counter
s = "programming"
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
print(freq)
print(Counter(s).most_common(3))Output:
{'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}
[('r', 2), ('g', 2), ('m', 2)]49. Remove punctuation from a string
string.punctuation lists every punctuation character.
import string
s = "Hello!!! How are you, Riya? (Fine.)"
clean = "".join(ch for ch in s if ch not in string.punctuation)
print(clean)Output:
Hello How are you Riya Fine50. Check if two strings are anagrams
Anagrams have the same letters in a different order, so their sorted letters match.
def is_anagram(a, b):
return sorted(a.replace(" ", "").lower()) == sorted(b.replace(" ", "").lower())
print(is_anagram("listen", "silent"))
print(is_anagram("Dormitory", "dirty room"))
print(is_anagram("hello", "world"))Output:
True
True
False51. Capitalise the first letter of each word
title() does it in one call; the manual way gives you more control.
s = "learn python with code and debug"
print(s.title())
print(" ".join(w[0].upper() + w[1:] for w in s.split()))Output:
Learn Python With Code And Debug
Learn Python With Code And Debug52. Remove duplicate characters from a string
Keep the first time each character appears. dict.fromkeys() preserves order.
s = "programming"
seen = ""
for ch in s:
if ch not in seen:
seen += ch
print(seen)
print("".join(dict.fromkeys(s)))Output:
progamin
progamin53. Find the longest word in a sentence
max() with key=len picks the longest item.
s = "Python makes programming surprisingly enjoyable"
longest = max(s.split(), key=len)
print("Longest word:", longest, "with", len(longest), "letters")Output:
Longest word: surprisingly with 12 letters54. Reverse the words in a sentence
Split into words, reverse the list, and join it back.
s = "Code and Debug teaches Python"
print(" ".join(s.split()[::-1]))Output:
Python teaches Debug and CodeStep-by-step guide with a dry run and time complexity: Reverse the words in a sentence.
55. Count uppercase and lowercase letters
isupper() and islower() check one character at a time.
s = "Hello World From INDIA"
upper = sum(1 for ch in s if ch.isupper())
lower = sum(1 for ch in s if ch.islower())
print("Uppercase:", upper)
print("Lowercase:", lower)Output:
Uppercase: 8
Lowercase: 1156. Check if a sentence is a pangram
A pangram uses every letter of the alphabet at least once.
import string
def is_pangram(s):
return set(string.ascii_lowercase) <= set(s.lower())
print(is_pangram("The quick brown fox jumps over the lazy dog"))
print(is_pangram("Hello world"))Output:
True
False57. Sort the words in alphabetical order
Lowercase the words first, because uppercase letters sort before lowercase ones.
s = "banana apple Cherry date"
print(sorted(s.split()))
print(sorted(s.split(), key=str.lower))Output:
['Cherry', 'apple', 'banana', 'date']
['apple', 'banana', 'Cherry', 'date']List programs in Python
Lists are the most used data structure in Python. These programs cover searching, cleaning and transforming them.
58. Find the sum and average of a list
sum() and len() do the work.
marks = [78, 92, 85, 64, 90]
total = sum(marks)
average = total / len(marks)
print("Total:", total)
print("Average:", average)Output:
Total: 409
Average: 81.859. Find the largest and smallest element
Use max() and min(), or one loop that tracks both.
nums = [34, 7, 89, 12, 56, 3]
largest = smallest = nums[0]
for n in nums:
if n > largest:
largest = n
if n < smallest:
smallest = n
print("Largest:", largest, "Smallest:", smallest)
print("Built-ins:", max(nums), min(nums))Output:
Largest: 89 Smallest: 3
Built-ins: 89 360. Find the second largest number
Track the largest and second largest in one pass, which also handles duplicates.
def second_largest(nums):
first = second = float("-inf")
for n in nums:
if n > first:
first, second = n, first
elif first > n > second:
second = n
return second
print(second_largest([10, 45, 32, 45, 8]))Output:
3261. Reverse a list
Three ways: slicing (new list), reverse() (in place) and two pointers.
nums = [1, 2, 3, 4, 5]
print(nums[::-1])
nums.reverse()
print(nums)
arr = [10, 20, 30, 40]
i, j = 0, len(arr) - 1
while i < j:
arr[i], arr[j] = arr[j], arr[i]
i, j = i + 1, j - 1
print(arr)Output:
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
[40, 30, 20, 10]Step-by-step guide with a dry run and time complexity: Reverse a list.
62. Remove duplicates from a list
set() removes duplicates but loses order; dict.fromkeys() keeps it.
nums = [3, 1, 3, 2, 1, 5, 2]
print(sorted(set(nums)))
print(list(dict.fromkeys(nums)))Output:
[1, 2, 3, 5]
[3, 1, 2, 5]63. Find the common elements of two lists
Set intersection with &.
a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7]
print(sorted(set(a) & set(b)))
print([x for x in a if x in b])Output:
[4, 5]
[4, 5]64. Rotate a list by k positions
Slicing makes rotation a one-liner. k % len handles k larger than the list.
nums = [1, 2, 3, 4, 5, 6, 7]
k = 3
k %= len(nums)
print("Right by 3:", nums[-k:] + nums[:-k])
print("Left by 3: ", nums[k:] + nums[:k])Output:
Right by 3: [5, 6, 7, 1, 2, 3, 4]
Left by 3: [4, 5, 6, 7, 1, 2, 3]65. Separate even and odd numbers
Two list comprehensions with a condition.
nums = list(range(1, 16))
evens = [n for n in nums if n % 2 == 0]
odds = [n for n in nums if n % 2]
print("Even:", evens)
print("Odd:", odds)Output:
Even: [2, 4, 6, 8, 10, 12, 14]
Odd: [1, 3, 5, 7, 9, 11, 13, 15]66. Flatten a nested list
A nested comprehension handles one level; recursion handles any depth.
nested = [[1, 2], [3, 4, 5], [6]]
print([x for sub in nested for x in sub])
def flatten(lst):
out = []
for item in lst:
if isinstance(item, list):
out.extend(flatten(item))
else:
out.append(item)
return out
print(flatten([1, [2, [3, [4, 5]]], 6]))Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]67. Square every number with a list comprehension
A list comprehension builds a new list in one readable line.
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums]
print(squares)
print([n * n for n in nums if n % 2 == 1])Output:
[1, 4, 9, 16, 25]
[1, 9, 25]68. Merge two sorted lists
Walk both lists with two pointers and always take the smaller element. Merge sort uses this same step.
def merge(a, b):
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
return out + a[i:] + b[j:]
print(merge([1, 4, 7, 10], [2, 3, 8]))Output:
[1, 2, 3, 4, 7, 8, 10]69. Check if a list is sorted
Compare each element with the next one.
def is_sorted(nums):
return all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1))
print(is_sorted([1, 2, 2, 5, 9]))
print(is_sorted([1, 3, 2]))Output:
True
FalseStep-by-step guide with a dry run and time complexity: Check if a list is sorted.
70. Find the missing number from 1 to n
The expected sum is n(n + 1)/2; the difference from the actual sum is the missing number.
nums = [1, 2, 4, 5, 6, 7, 8]
n = len(nums) + 1
missing = n * (n + 1) // 2 - sum(nums)
print("Missing number:", missing)Output:
Missing number: 3Step-by-step guide with a dry run and time complexity: Find the missing number from 1 to n.
71. Count how often an element appears
list.count() for one value, Counter for all of them.
from collections import Counter
nums = [2, 4, 2, 7, 2, 4, 9]
print("2 appears", nums.count(2), "times")
print(dict(Counter(nums)))Output:
2 appears 3 times
{2: 3, 4: 2, 7: 1, 9: 1}Dictionary, set and tuple programs
Dictionaries map keys to values, sets keep unique items, and tuples are fixed sequences. Lookups in dictionaries and sets take O(1) time on average.
72. Count words with a dictionary
The classic word-frequency program.
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)Output:
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}73. Merge two dictionaries
The | operator (Python 3.9+) or {**a, **b}. Values from the right-hand dictionary win.
a = {"name": "Riya", "city": "Pune"}
b = {"city": "Surat", "course": "Python"}
print(a | b)
print({**a, **b})Output:
{'name': 'Riya', 'city': 'Surat', 'course': 'Python'}
{'name': 'Riya', 'city': 'Surat', 'course': 'Python'}74. Sort a dictionary by value
sorted() with a key function returns a sorted list of pairs.
marks = {"Riya": 88, "Arjun": 95, "Meera": 72, "Kabir": 91}
by_marks = dict(sorted(marks.items(), key=lambda kv: kv[1], reverse=True))
print(by_marks)
print("Topper:", max(marks, key=marks.get))Output:
{'Arjun': 95, 'Kabir': 91, 'Riya': 88, 'Meera': 72}
Topper: Arjun75. Swap the keys and values of a dictionary
A dictionary comprehension. Values must be unique and hashable.
codes = {"IN": "India", "JP": "Japan", "BR": "Brazil"}
print({v: k for k, v in codes.items()})Output:
{'India': 'IN', 'Japan': 'JP', 'Brazil': 'BR'}76. Set operations: union, intersection, difference
Sets support maths-style operators.
python = {"Riya", "Arjun", "Meera"}
java = {"Arjun", "Kabir", "Meera"}
print("Both:", sorted(python & java))
print("Either:", sorted(python | java))
print("Only Python:", sorted(python - java))
print("Exactly one:", sorted(python ^ java))Output:
Both: ['Arjun', 'Meera']
Either: ['Arjun', 'Kabir', 'Meera', 'Riya']
Only Python: ['Riya']
Exactly one: ['Kabir', 'Riya']77. Tuple unpacking and namedtuple
Tuples can be unpacked into variables; namedtuple gives the fields names.
from collections import namedtuple
point = (3, 4)
x, y = point
print("x =", x, "y =", y)
Student = namedtuple("Student", ["name", "marks"])
s = Student("Riya", 92)
print(s.name, s.marks)
print(s)Output:
x = 3 y = 4
Riya 92
Student(name='Riya', marks=92)Function and recursion programs
Functions let you reuse code. A recursive function calls itself and must always have a base case that stops the calls.
78. Factorial using recursion
n! = n × (n − 1)!, with 0! = 1 as the base case.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
print(factorial(12))Output:
120
479001600Step-by-step guide with a dry run and time complexity: Factorial using recursion.
79. Fibonacci with recursion and memoisation
Plain recursion repeats work and gets slow; @lru_cache remembers results so each value is computed once.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(10)])
print("fib(80) =", fib(80))Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
fib(80) = 23416728348467685Step-by-step guide with a dry run and time complexity: Fibonacci with recursion and memoisation.
80. Sum of a list using recursion
The sum of a list is its first element plus the sum of the rest.
def list_sum(nums):
if not nums:
return 0
return nums[0] + list_sum(nums[1:])
print(list_sum([4, 8, 15, 16, 23, 42]))Output:
10881. Power of a number using recursion
Fast exponentiation halves the exponent at each step, so it needs only O(log n) multiplications.
def power(base, exp):
if exp == 0:
return 1
half = power(base, exp // 2)
return half * half if exp % 2 == 0 else half * half * base
print(power(2, 10))
print(power(3, 13))Output:
1024
159432382. Lambda with map, filter and reduce
Small anonymous functions for quick transformations.
from functools import reduce
nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * 10, nums)))
print(list(filter(lambda n: n % 2 == 0, nums)))
print(reduce(lambda a, b: a * b, nums))Output:
[10, 20, 30, 40, 50, 60]
[2, 4, 6]
72083. Functions with *args and **kwargs
*args collects extra positional arguments into a tuple, **kwargs collects keyword arguments into a dict.
def total(*args):
return sum(args)
def profile(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print(total(1, 2, 3, 4))
profile(name="Riya", city="Pune", course="Python")Output:
10
name: Riya
city: Pune
course: Python84. Write a simple decorator
A decorator wraps a function to add behaviour before or after it runs.
def log_call(func):
def wrapper(*args):
print(f"Calling {func.__name__}{args}")
result = func(*args)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@log_call
def add(a, b):
return a + b
add(3, 4)Output:
Calling add(3, 4)
add returned 7Sorting and searching programs
Every sorting and searching algorithm below has a full post with dry runs and complexity analysis; follow the links to go deeper.
85. Linear search
Check each element one by one. O(n) time.
def linear_search(nums, target):
for i, n in enumerate(nums):
if n == target:
return i
return -1
nums = [12, 45, 7, 23, 56]
print(linear_search(nums, 23))
print(linear_search(nums, 99))Output:
3
-1Step-by-step guide with a dry run and time complexity: Linear search.
86. Binary search
On a sorted list, compare with the middle element and discard half the list each time. O(log n) time.
def binary_search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
nums = [3, 8, 15, 23, 42, 56, 71]
print(binary_search(nums, 42))
print(binary_search(nums, 10))Output:
4
-187. Bubble sort
Repeatedly swap neighbours that are out of order; stop early if a pass makes no swaps.
def bubble_sort(nums):
n = len(nums)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
swapped = True
if not swapped:
break
return nums
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))Output:
[11, 12, 22, 25, 34, 64, 90]Step-by-step guide with a dry run and time complexity: Bubble sort.
88. Selection sort
Find the smallest remaining element and move it to the front.
def selection_sort(nums):
for i in range(len(nums)):
smallest = min(range(i, len(nums)), key=nums.__getitem__)
nums[i], nums[smallest] = nums[smallest], nums[i]
return nums
print(selection_sort([29, 10, 14, 37, 13]))Output:
[10, 13, 14, 29, 37]Step-by-step guide with a dry run and time complexity: Selection sort.
89. Insertion sort
Take each element and insert it into its place in the sorted part on the left.
def insertion_sort(nums):
for i in range(1, len(nums)):
key = nums[i]
j = i - 1
while j >= 0 and nums[j] > key:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = key
return nums
print(insertion_sort([12, 11, 13, 5, 6]))Output:
[5, 6, 11, 12, 13]Step-by-step guide with a dry run and time complexity: Insertion sort.
90. Merge sort
Split the list in half, sort each half recursively, and merge them. O(n log n) time.
def merge_sort(nums):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left, right = merge_sort(nums[:mid]), merge_sort(nums[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]
print(merge_sort([38, 27, 43, 3, 9, 82, 10]))Output:
[3, 9, 10, 27, 38, 43, 82]Step-by-step guide with a dry run and time complexity: Merge sort.
91. Quick sort
Pick a pivot, put smaller elements on its left and larger ones on its right, then sort both sides.
def quick_sort(nums):
if len(nums) <= 1:
return nums
pivot = nums[len(nums) // 2]
left = [x for x in nums if x < pivot]
middle = [x for x in nums if x == pivot]
right = [x for x in nums if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
print(quick_sort([10, 7, 8, 9, 1, 5]))Output:
[1, 5, 7, 8, 9, 10]Step-by-step guide with a dry run and time complexity: Quick sort.
92. Sort with a custom key
In real code you will mostly use sorted() with a key function.
students = [("Riya", 88), ("Arjun", 95), ("Meera", 88), ("Kabir", 72)]
print(sorted(students, key=lambda s: s[1], reverse=True))
print(sorted(students, key=lambda s: (-s[1], s[0])))
print(sorted(["banana", "kiwi", "apple"], key=len))Output:
[('Arjun', 95), ('Riya', 88), ('Meera', 88), ('Kabir', 72)]
[('Arjun', 95), ('Meera', 88), ('Riya', 88), ('Kabir', 72)]
['kiwi', 'apple', 'banana']Matrix programs in Python
A matrix is a list of lists. Nested loops and zip() make matrix work short.
93. Add two matrices
Add elements in the same position.
A = [[1, 2, 3], [4, 5, 6]]
B = [[9, 8, 7], [6, 5, 4]]
result = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
for row in result:
print(row)Output:
[10, 10, 10]
[10, 10, 10]94. Transpose a matrix
Rows become columns. zip(*matrix) does it in one line.
M = [[1, 2, 3], [4, 5, 6]]
T = [list(row) for row in zip(*M)]
for row in T:
print(row)Output:
[1, 4]
[2, 5]
[3, 6]95. Multiply two matrices
Each result cell is the dot product of a row of A and a column of B.
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
result = [[sum(a * b for a, b in zip(row, col)) for col in zip(*B)] for row in A]
for row in result:
print(row)Output:
[19, 22]
[43, 50]OOP, exception and file handling programs
Classes group data with the functions that work on it. Exceptions handle errors cleanly, and files let your programs save data. Our OOPs interview questions post covers the theory behind these.
96. Create a class and objects
A class is a blueprint; __init__ sets up each new object, and __str__ controls how it prints.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def grade(self):
return "A" if self.marks >= 90 else "B" if self.marks >= 75 else "C"
def __str__(self):
return f"{self.name}: {self.marks} ({self.grade()})"
for s in [Student("Riya", 92), Student("Arjun", 78), Student("Meera", 64)]:
print(s)Output:
Riya: 92 (A)
Arjun: 78 (B)
Meera: 64 (C)97. Inheritance and method overriding
A child class reuses the parent and can override its methods; super() calls the parent version.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
def intro(self):
return f"{self.name} says {self.speak()}"
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
for pet in [Dog("Bruno"), Cat("Misty")]:
print(pet.intro())Output:
Bruno says Woof
Misty says Meow98. Bank account with a custom exception
Raise your own exception when a rule is broken, and catch it where you can respond.
class InsufficientFunds(Exception):
pass
class Account:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFunds(f"Balance is only {self.balance}")
self.balance -= amount
acc = Account(1000)
acc.deposit(500)
try:
acc.withdraw(2000)
except InsufficientFunds as e:
print("Error:", e)
acc.withdraw(300)
print("Balance:", acc.balance)Output:
Error: Balance is only 1500
Balance: 120099. Write to and read from a file
with open(...) closes the file automatically. Mode “w” writes, “a” appends and “r” reads.
with open("notes.txt", "w") as f:
f.write("Python\n")
f.write("Java\n")
with open("notes.txt", "a") as f:
f.write("SQL\n")
with open("notes.txt") as f:
for i, line in enumerate(f, 1):
print(i, line.strip())Output:
1 Python
2 Java
3 SQL100. Handle errors with try, except, else and finally
Catch specific exceptions; else runs when nothing failed and finally always runs.
def safe_divide(a, b):
try:
result = int(a) / int(b)
except ValueError:
return "Please enter numbers only"
except ZeroDivisionError:
return "Cannot divide by zero"
else:
return f"Result: {result}"
finally:
print(f"Tried {a} / {b}")
print(safe_divide("10", "4"))
print(safe_divide("10", "0"))
print(safe_divide("ten", "2"))Output:
Tried 10 / 4
Result: 2.5
Tried 10 / 0
Cannot divide by zero
Tried ten / 2
Please enter numbers onlyPython programs for practice: 30 questions with tests
Now write the programs yourself. Each question gives you a function to complete. Press Run tests and the page runs your function on several inputs and shows which ones passed. Your code and your “Done” progress are saved in this browser, so you can come back later.
Start with the easy ones. The “Show solution” link under each question has a model answer, but try for at least ten minutes before you open it.
Your progress
Easy Python practice programs
Basic Python programs for practice: conditions, loops and simple string work.
1. Even or odd
Write is_even(n) that returns True if n is even and False otherwise.
Example: is_even(4) → True
Show solution
def is_even(n):
return n % 2 == 02. Largest of three
Write max_of_three(a, b, c) that returns the largest of three numbers, without using max().
Example: max_of_three(1, 2, 3) → 3
Show solution
def max_of_three(a, b, c):
if a >= b and a >= c:
return a
if b >= c:
return b
return c3. Celsius to Fahrenheit
Write to_fahrenheit(c) that converts a temperature from Celsius to Fahrenheit (F = C × 9/5 + 32).
Example: to_fahrenheit(0) → 32.0
Show solution
def to_fahrenheit(c):
return c * 9 / 5 + 324. Sum of digits
Write sum_digits(n) that returns the sum of the digits of a non-negative integer n.
Example: sum_digits(12345) → 15
Show solution
def sum_digits(n):
total = 0
while n > 0:
total += n % 10
n //= 10
return total5. Count vowels
Write count_vowels(s) that returns how many vowels (a, e, i, o, u, in either case) are in the string s.
Example: count_vowels('Python') → 1
Show solution
def count_vowels(s):
return sum(1 for ch in s.lower() if ch in "aeiou")6. Leap year
Write is_leap(year) that returns True for leap years: divisible by 4, but century years must be divisible by 400.
Example: is_leap(2024) → True
Show solution
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)7. Reverse a string
Write reverse_string(s) that returns the string reversed.
Example: reverse_string('hello') → 'olleh'
Show solution
def reverse_string(s):
return s[::-1]8. Factorial
Write factorial(n) that returns n! for n ≥ 0. Remember that 0! is 1.
Example: factorial(0) → 1
Show solution
def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result9. Palindrome string
Write is_palindrome(s) that returns True if s reads the same forwards and backwards, ignoring case.
Example: is_palindrome('madam') → True
Show solution
def is_palindrome(s):
s = s.lower()
return s == s[::-1]10. Average of a list
Write average(nums) that returns the average of a non-empty list of numbers.
Example: average([1, 2, 3, 4]) → 2.5
Show solution
def average(nums):
return sum(nums) / len(nums)Medium Python practice programs
Lists, dictionaries, recursion and number logic.
11. Prime check
Write is_prime(n) that returns True if n is a prime number. Numbers below 2 are not prime.
Example: is_prime(1) → False
Show solution
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True12. Nth Fibonacci number
Write fib(n) that returns the nth Fibonacci number, where fib(0) = 0 and fib(1) = 1. It should be fast for n = 90.
Example: fib(0) → 0
Show solution
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a13. GCD of two numbers
Write gcd(a, b) that returns the greatest common divisor of two positive integers, without using math.gcd.
Example: gcd(48, 180) → 12
Show solution
def gcd(a, b):
while b:
a, b = b, a % b
return a14. Second largest
Write second_largest(nums) that returns the second largest distinct value in the list, or None if there is none.
Example: second_largest([10, 45, 32, 45, 8]) → 32
Show solution
def second_largest(nums):
distinct = sorted(set(nums), reverse=True)
return distinct[1] if len(distinct) > 1 else None15. Character frequency
Write char_count(s) that returns a dictionary mapping each character of s to how many times it appears.
Example: char_count('hello') → {'h': 1, 'e': 1, 'l': 2, 'o': 1}
Show solution
def char_count(s):
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
return counts16. Remove duplicates, keep order
Write unique(nums) that returns a new list without duplicates, keeping the first occurrence of each value in its original order.
Example: unique([3, 1, 3, 2, 1]) → [3, 1, 2]
Show solution
def unique(nums):
seen = set()
out = []
for n in nums:
if n not in seen:
seen.add(n)
out.append(n)
return out17. Anagram check
Write is_anagram(a, b) that returns True if the two words contain exactly the same letters, ignoring case.
Example: is_anagram('listen', 'silent') → True
Show solution
def is_anagram(a, b):
return sorted(a.lower()) == sorted(b.lower())18. Decimal to binary
Write to_binary(n) that returns the binary form of a non-negative integer as a string, without using bin(). to_binary(0) should return “0”.
Example: to_binary(0) → '0'
Show solution
def to_binary(n):
if n == 0:
return "0"
bits = ""
while n > 0:
bits = str(n % 2) + bits
n //= 2
return bits19. Flatten a nested list
Write flatten(lst) that turns a list nested to any depth into a flat list.
Example: flatten([1, [2, 3], 4]) → [1, 2, 3, 4]
Show solution
def flatten(lst):
out = []
for item in lst:
if isinstance(item, list):
out.extend(flatten(item))
else:
out.append(item)
return out20. Word count
Write word_count(text) that returns a dictionary of how many times each word appears. Words are separated by spaces and compared in lowercase.
Example: word_count('the cat and the hat') → {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}
Show solution
def word_count(text):
counts = {}
for w in text.lower().split():
counts[w] = counts.get(w, 0) + 1
return counts21. Rotate a list
Write rotate_right(nums, k) that returns the list rotated to the right by k positions. k can be larger than the length.
Example: rotate_right([1, 2, 3, 4, 5], 2) → [4, 5, 1, 2, 3]
Show solution
def rotate_right(nums, k):
if not nums:
return []
k %= len(nums)
return nums[-k:] + nums[:-k] if k else nums[:]22. Armstrong number
Write is_armstrong(n) that returns True if n equals the sum of its digits each raised to the number of digits (153 = 1³ + 5³ + 3³).
Example: is_armstrong(153) → True
Show solution
def is_armstrong(n):
s = str(n)
return n == sum(int(d) ** len(s) for d in s)Hard Python practice programs
Algorithms asked in coding rounds: two pointers, binary search, stacks and hashing.
23. Merge two sorted lists
Write merge_sorted(a, b) that merges two sorted lists into one sorted list in O(n + m) time, without calling sorted().
Example: merge_sorted([1, 4, 7], [2, 3, 8]) → [1, 2, 3, 4, 7, 8]
Show solution
def merge_sorted(a, b):
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
return out + a[i:] + b[j:]24. Binary search
Write binary_search(nums, target) that returns the index of target in the sorted list nums, or -1 if it is not there. Use binary search, not index().
Example: binary_search([1, 3, 5, 7, 9], 7) → 3
Show solution
def binary_search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -125. Row of Pascal’s triangle
Write pascal_row(n) that returns row n of Pascal’s triangle as a list, where row 0 is [1].
Example: pascal_row(0) → [1]
Show solution
def pascal_row(n):
row = [1]
for _ in range(n):
row = [1] + [row[i] + row[i + 1] for i in range(len(row) - 1)] + [1]
return row26. Balanced brackets
Write is_balanced(s) that returns True if every bracket in s, of the kinds (), [] and {}, is closed in the correct order. Other characters are ignored.
Example: is_balanced('()[]{}') → True
Show solution
def is_balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack27. Two sum
Write two_sum(nums, target) that returns the indices [i, j] (i < j) of the two numbers that add up to target. Exactly one answer exists. Aim for O(n) time with a dictionary.
Example: two_sum([2, 7, 11, 15], 9) → [0, 1]
Show solution
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = i28. Run-length encoding
Write compress(s) that replaces each run of repeated characters with the character followed by the run length: “aaabcc” becomes “a3b1c2”.
Example: compress('aaabcc') → 'a3b1c2'
Show solution
def compress(s):
if not s:
return ""
out = []
count = 1
for i in range(1, len(s) + 1):
if i < len(s) and s[i] == s[i - 1]:
count += 1
else:
out.append(s[i - 1] + str(count))
count = 1
return "".join(out)29. Matrix multiplication
Write matmul(a, b) that multiplies two matrices given as lists of lists. You can assume the sizes are compatible.
Example: matmul([[1, 2], [3, 4]], [[5, 6], [7, 8]]) → [[19, 22], [43, 50]]
Show solution
def matmul(a, b):
return [[sum(x * y for x, y in zip(row, col)) for col in zip(*b)] for row in a]30. Longest word
Write longest_word(sentence) that returns the longest word in a sentence. If several words tie, return the first one. Ignore the punctuation marks . , ! and ?.
Example: longest_word('I love Python programming') → 'programming'
Show solution
def longest_word(sentence):
for p in ".,!?":
sentence = sentence.replace(p, "")
best = ""
for w in sentence.split():
if len(w) > len(best):
best = w
return bestPython programs PDF
The PDF has all 100 programs with their output and the 30 practice questions with solutions, in 45 printable pages with a clickable table of contents. It is handy for lab practicals and for revising before a coding round. It is free, with no sign-up.
Python Programs with Examples
45 pages · 100 programs with output · 30 practice questions
Frequently asked questions
What are the basic Python programs for beginners?
Start with Hello World, adding two numbers, even or odd, the largest of three numbers, a leap year check, a multiplication table, factorial, the Fibonacci series, prime numbers, reversing a string and simple star patterns. Programs 1 to 43 on this page cover them in that order.
Which Python programs are asked in interviews for freshers?
Common ones are prime check, palindrome (number and string), Fibonacci, factorial, Armstrong number, reversing a string or list, finding the second largest element, removing duplicates, anagram check, character frequency, binary search and simple sorting. All of them are on this page, and our Python interview questions post covers the theory questions.
Can I run these Python programs online?
Yes. Every program has a “Run this program” button, and there is a free Python editor at the top of the page. Python runs inside your browser, so nothing needs to be installed. The only limit is that input() does not work in the browser, so the programs use fixed values instead.
How should I practise Python programs?
Read a program, close it, and write it again from memory. Then change it: use different inputs, add a condition, or make it a function. The 30 practice questions on this page test your code automatically, which tells you quickly whether your logic works.
Do I need to know Python syntax before trying these programs?
Only the basics: variables, if-else, loops and functions. If you are completely new, start with the free Python course for beginners on codeanddebug.in, then come back to these programs to practise.
Can I download these Python programs as a PDF?
Yes. All 100 programs with their output and the 30 practice questions with solutions are in a free 45-page PDF. Use the Download PDF button at the top of the page; no sign-up is needed.
Next steps
Work through the programs one section at a time, run each one, and change it until you understand why it prints what it prints. Then solve the practice questions and press “Mark as done” as you finish each one. New to Python? Our free Python course for beginners teaches the syntax step by step. Preparing for placements? Continue with our Python interview questions, time and space complexity guide and DSA interview cheat sheet. Happy coding!
