
Python Course
Basic Programs in Python
You have spent 14 lessons learning individual concepts — variables, loops, conditionals, strings, lists, tuples, dictionaries, sets, and type casting. This lesson is where everything comes together. You will write 12 complete Python programs, each one solving a real problem using exactly what you already know. No new syntax. Just new thinking.
Every professional programmer started here — learning to combine concepts into a working solution. By the end of this lesson you will be comfortable building complete programs from scratch, which is the foundation every future lesson builds on.
Program 1 — Swap Two Numbers
Swapping means exchanging the values of two variables. If a = 10 and b = 20, after swapping, a should be 20 and b should be 10. In most languages this requires a third temporary variable. Python does it in one clean line using tuple unpacking.
a = 10
b = 20
print("Before swap: a =", a, "| b =", b)
# One-line swap — Python evaluates right side first
a, b = b, a
print("After swap : a =", a, "| b =", b)
- Python evaluates
b, aon the right side first — giving the pair(20, 10)— then assigns both values simultaneously toaandb. - This is called tuple unpacking and is one of Python's most elegant features. The same technique works to swap any two variables in one line.
- Real use: swapping elements during sorting algorithms.
Program 2 — Check Odd or Even
A number is even if it divides by 2 with no remainder. A number is odd if the remainder is 1. The modulus operator % gives the remainder — making this check a single condition.
numbers = [4, 7, 12, 19, 0, 33]
for num in numbers:
if num % 2 == 0:
print(num, "→ Even")
else:
print(num, "→ Odd")
num % 2is the remainder when dividing by 2. Zero remainder means even, remainder of 1 means odd.0 % 2 == 0— zero is mathematically even, and Python confirms this correctly.- The loop + conditional pattern used here appears in almost every real data processing program you will ever write.
Program 3 — Simple Calculator
A calculator takes two numbers and an operation, then performs the correct calculation. The if / elif / else chain decides which operation to run based on the operator symbol — a classic menu-driven program pattern.
num1 = 20
num2 = 4
operator = "/" # change to: "+", "-", "*", "/", "%"
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
result = "Cannot divide by zero"
else:
result = num1 / num2
elif operator == "%":
result = num1 % num2
else:
result = "Unknown operator"
print(num1, operator, num2, "=", result)
- The division branch has a special inner check —
if num2 == 0. Dividing by zero crashes a program, so we handle it gracefully by returning a safe message instead. - Change
operatorto"+","-","*", or"%"and run again — the same code handles every case cleanly. - This pattern — an outer condition choosing an operation — is used in chatbots, command menus, and routing logic in web apps.
Program 4 — Find the Largest of Three Numbers
Given three numbers, determine which is the biggest using conditions. This program teaches you to think through all possible combinations — a core logical reasoning skill every programmer needs.
a = 45
b = 78
c = 33
# Manual approach — teaches the logic
if a >= b and a >= c:
print("Largest is:", a)
elif b >= a and b >= c:
print("Largest is:", b)
else:
print("Largest is:", c)
# Python's built-in shortcut
print("Using max():", max(a, b, c))
- The first
ifchecks ifais greater than or equal to both others. If not, it checksb. If neither wins,cmust be the largest. max()does the same thing in one word — but understanding the manual version first shows you whatmax()is doing internally.- Try setting all three to the same value — the first
ifhandles equal values correctly because of the>=operator.
Program 5 — Multiplication Table
Print every multiple of a number from 1 to 10. A perfect loop exercise — the loop runs 10 times and multiplies the target number by the current count on each step.
number = 7
print(f"--- Multiplication Table of {number} ---")
for i in range(1, 11): # i goes from 1 to 10
result = number * i
print(f" {number} x {i:2} = {result}")
range(1, 11)generates numbers 1 through 10 — the stop value11is excluded, which is why we write11to get up to10.{i:2}inside the f-string pads single-digit numbers with a space so the columns stay neatly aligned.- Change
number = 7to any value and the full table prints instantly — this is the power of writing flexible, variable-driven code.
Program 6 — Sum, Average, Min, and Max of a List
Given a list of numbers, calculate the total, average, smallest, and largest values. This exact pattern is used in grade reports, sales dashboards, sensor data summaries, and any application that processes a collection of numbers.
marks = [72, 85, 90, 60, 78, 95, 88]
total = sum(marks)
count = len(marks)
average = total / count
lowest = min(marks)
highest = max(marks)
print("Marks :", marks)
print("Total :", total)
print("Count :", count)
print("Average :", round(average, 2))
print("Lowest :", lowest)
print("Highest :", highest)
sum(),len(),min(), andmax()are Python built-in functions that work on any list of numbers — no loop needed.- Python has no built-in
avg()function. The calculation is simplytotal / count. round(average, 2)limits the output to 2 decimal places — cleaner than the full float output.
Program 7 — Count Vowels in a String
Given a sentence, count how many vowels it contains. This program uses a loop, the in membership operator, and a counter — three tools you now know well, combined into one practical text-processing program.
sentence = "Python programming is fun and easy to learn"
vowels = "aeiou"
count = 0
for char in sentence.lower(): # .lower() handles uppercase letters too
if char in vowels:
count += 1
print("Sentence :", sentence)
print("Vowels found:", count)
sentence.lower()converts everything to lowercase so capital vowels like"A"or"E"are counted correctly — not case-sensitive.char in vowelschecks if the current character is one of the five vowel characters in the string"aeiou".count += 1adds one every time a vowel is found. After the loop,countholds the total.
Program 8 — Reverse a String and Check for Palindromes
Reversing a string flips it so the last character becomes first. A palindrome is a word or phrase that reads the same forwards and backwards. Python makes both tasks a single line using slicing — and this logic appears in coding interviews worldwide.
word = "Programming"
reversed_word = word[::-1] # slice with step -1 reverses anything
print("Original :", word)
print("Reversed :", reversed_word)
# Check multiple words for palindrome
test_words = ["radar", "python", "level", "hello", "madam"]
for w in test_words:
if w == w[::-1]:
print(w, "→ Palindrome")
else:
print(w, "→ Not a palindrome")
word[::-1]— the step-1means "go backwards one character at a time from the end." This reverses any string or list in one expression.w == w[::-1]compares the word to its own reverse — if they match, it is a palindrome.- This is a genuine coding interview question that is solved in just 3 lines of logic using what you already know.
Program 9 — Remove Duplicates from a List
Duplicate data is one of the most common data quality problems — repeated form submissions, duplicate email addresses, or repeated entries in a log. Removing duplicates is a one-step operation in Python using sets.
emails = [
"user@mail.com",
"admin@site.com",
"user@mail.com",
"guest@mail.com",
"admin@site.com"
]
print("Original :", emails)
print("Count :", len(emails))
# Set removes duplicates automatically, list() converts back
unique_emails = list(set(emails))
print("Unique :", unique_emails)
print("New count :", len(unique_emails))
set(emails)automatically eliminates the two duplicate email addresses — sets cannot hold duplicates by design.list(...)converts it back so you can sort, index, or loop through it normally.- The pattern
list(set(data))is one of the most used data-cleaning one-liners in all of Python.
Program 10 — Grade Calculator
Given a student's score, assign the correct letter grade. This is a real-world use of if/elif/else — the same logic used in school management systems, learning platforms, and HR performance tools.
students = [
("Priya", 92),
("Kiran", 75),
("Arjun", 60),
("Sneha", 85),
("Rahul", 45),
("Meera", 100)
]
print(f"{'Name':<10} {'Score':<8} Grade")
print("-" * 28)
for name, score in students:
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
elif score >= 45:
grade = "D"
else:
grade = "F"
print(f"{name:<10} {score:<8} {grade}")
- Each student is stored as a tuple
(name, score)inside a list — the nested collection pattern from Lessons 10 and 11. - The loop unpacks each tuple directly into
nameandscoreusing tuple unpacking — no indexing needed. {name:<10}left-aligns the name in a field 10 characters wide, keeping the output columns neat and professional.
Program 11 — Word Frequency Counter
Count how many times each word appears in a sentence, then find the most frequent one. This pattern is used in search engines, SEO analysis, spam filters, and natural language processing tools.
sentence = "learn python learn coding learn programming with python"
words = sentence.split()
print("Total words:", len(words))
# Count each word using a dictionary
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print("Word counts:", word_count)
# Find the most frequent word
top_word = max(word_count, key=word_count.get)
top_count = word_count[top_word]
print(f"Most used : '{top_word}' ({top_count} times)")
sentence.split()breaks the sentence into a list of words at every space character.- The dictionary loop adds
1when a word is seen for the first time, and increments the count on every repeat. max(word_count, key=word_count.get)finds the key with the highest value — a compact one-liner for finding the most frequent item in any dictionary.
Program 12 — FizzBuzz
FizzBuzz is one of the most famous beginner coding challenges — asked in real developer interviews worldwide. The rules: print numbers 1 to 20, but replace multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both 3 and 5 with "FizzBuzz".
for i in range(1, 21):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz") # divisible by BOTH 3 and 5 — check this FIRST
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
- The
FizzBuzzcheck must come first — if you check% 3first, the number 15 would print "Fizz" instead of "FizzBuzz" because it matches both. Order of conditions is critical. - This uses only a loop, the modulus operator, and
if/elif/else— three things from earlier lessons, combined with careful thinking about condition order. - FizzBuzz is asked in developer interviews because it tests logical thinking and condition ordering — now you know it cold.
All 12 Programs — Summary
| Program | Key Concepts | Real-World Use |
|---|---|---|
| Swap Two Numbers | Tuple unpacking | Sorting algorithms |
| Odd or Even | Modulus, loop, conditionals | Form validation, game logic |
| Simple Calculator | if / elif / else, division safety | Menu-driven apps |
| Largest of Three | Compound conditions, max() | Ranking, scoring systems |
| Multiplication Table | for loop, range(), f-strings | Report generation |
| Sum / Avg / Min / Max | sum(), len(), min(), max(), round() | Dashboards, grade reports |
| Count Vowels | Loop, in operator, counter | Text analysis, NLP |
| Reverse / Palindrome | Slicing [::-1] | Coding interviews |
| Remove Duplicates | list(set()) | Data cleaning pipelines |
| Grade Calculator | Tuples, loop, if/elif unpacking | School management systems |
| Word Frequency | split(), dictionary, max(key) | SEO analysis, spam filters |
| FizzBuzz | Modulus, condition order | Developer interviews worldwide |
Practice
Write the one-line Python statement to swap variables a and b.
Which operator is used to check if a number is odd or even?
What slice syntax reverses a string in Python?
In FizzBuzz, what should be printed for the number 15?
Write the one-line expression to remove duplicates from a list called data and convert it back to a list.
Quick Quiz
Which of these words is a palindrome?
In FizzBuzz, what is printed for the number 9?
What is the correct expression to calculate the average of a list called marks?
In the calculator program, what happens when num2 = 0 and the operator is "/"?
Which string method breaks a sentence into a list of individual words?