Python Course
Basic Programs in Python
This lesson is your first hands-on coding session. You have learned variables, data types, operators, conditionals, loops, strings, lists, tuples, dictionaries, sets, and type casting. Now you will put it all together by writing real, complete Python programs. Each program in this lesson solves a practical problem using the concepts you already know.
1. Why Write Complete Programs?
Learning individual concepts is important, but writing complete programs is what turns you into a real programmer. A complete program takes an input, processes it using logic, and produces a meaningful output. Every program in this lesson is short, simple, and built entirely from what you already know — no new syntax, just new thinking.
After this lesson you will be confident combining multiple concepts together, which is exactly what all future lessons build on.
2. Program 1 — Swap Two Numbers
Swapping means exchanging the values of two variables. For example, if a = 10 and b = 20, after swapping, a should be 20 and b should be 10. Python makes this extremely clean with a single line.
# Two variables with values
a = 10
b = 20
print("Before swap: a =", a, "| b =", b)
# Python lets you swap in one line — no temporary variable needed
a, b = b, a
print("After swap : a =", a, "| b =", b)
After swap : a = 20 | b = 10
What just happened?
a, b = b, a— Python evaluates the right side first (b, a=20, 10), then assigns the values to the left side at the same time.- In other languages this requires a temporary third variable. Python does it in one clean line.
- This technique is called tuple unpacking — something you learned in Lesson 11.
3. Program 2 — Check Odd or Even
A number is even if it divides by 2 with no remainder. A number is odd if there is a remainder of 1. The modulus operator % gives us the remainder, making this check very simple.
# Check odd or even for a few numbers
numbers = [4, 7, 12, 19, 0, 33]
for num in numbers:
if num % 2 == 0:
print(num, "→ Even")
else:
print(num, "→ Odd")
7 → Odd
12 → Even
19 → Odd
0 → Even
33 → Odd
What just happened?
num % 2gives the remainder when dividing by 2. If it equals0, the number is even. If it equals1, it is odd.0 % 2is0— so zero is considered even, which is mathematically correct.- The loop runs through all 6 numbers and prints a result for each one — this is the loop + conditional pattern you will use constantly.
4. Program 3 — Simple Calculator
A calculator takes two numbers and an operator, then performs the correct operation. This program uses if / elif / else to decide which operation to run — a very common real-world pattern for handling user choices.
# Two numbers and an operator
num1 = 20
num2 = 4
operator = "/" # try: "+", "-", "*", "/", "%"
# Perform the right operation based on the operator
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)
What just happened?
- The program checks the
operatorvariable usingif/elif/elseand runs only the matching block. - Division has an extra check for
num2 == 0— dividing by zero crashes a program, so we handle it gracefully with a message. - Change
operatorto"+","-", or"*"and run again — the program handles all cases cleanly.
5. Program 4 — Find the Largest of Three Numbers
Given three numbers, find which one is the biggest. This is solved with nested conditions — checking each number against the others. It is one of the most classic beginner programs and teaches you to think through all possible combinations.
# Three numbers to compare
a = 45
b = 78
c = 33
# Check all three — find the largest
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 also has a built-in shortcut for this
print("Using max():", max(a, b, c))
Using max(): 78
What just happened?
- The first
ifchecks ifais greater than or equal to bothbandc. If not, it checksb. If neither,cmust be the largest. - Python's built-in
max()function does the same thing in one word — knowing the manual approach first helps you understand whatmax()is doing internally. - Try changing the values of
a,b, andcto test all three possible outcomes.
6. Program 5 — Print a Multiplication Table
A multiplication table prints every multiple of a number from 1 to 10. This is a perfect loop exercise — the loop runs 10 times and multiplies the number by the current count each time.
# Print the multiplication table for this number
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}")
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
What just happened?
range(1, 11)produces the numbers 1 through 10 — remember, the stop value is excluded, so11gives us up to10.{i:2}in the f-string is a formatting trick — it pads single-digit numbers with a space so the table aligns neatly.- Change
number = 7to any number and the table updates instantly — this is the power of writing flexible code.
7. Program 6 — Sum, Average, Min, and Max of a List
Given a list of numbers, calculate the total, average, smallest, and largest values. This is one of the most common data processing tasks in real programs — used in sales totals, grade reports, sensor readings, and more.
# A list of student marks
marks = [72, 85, 90, 60, 78, 95, 88]
# Built-in functions do the heavy lifting
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 :", average)
print("Lowest :", lowest)
print("Highest :", highest)
Total : 568
Count : 7
Average : 81.14285714285714
Lowest : 60
Highest : 95
What just happened?
sum(),len(),min(), andmax()are Python built-in functions that work on any list of numbers — no loop needed.- Average is calculated manually as
total / count— Python does not have a directavg()function, but this one-liner is all you need. - This exact pattern is used in grade management systems, dashboards, and data analysis scripts every day.
8. Program 7 — Count Vowels in a String
Given a sentence, count how many vowels (a, e, i, o, u) it contains. This program uses a loop, membership testing with in, and a counter — all concepts from earlier lessons.
# The sentence to check
sentence = "Python programming is fun and easy to learn"
vowels = "aeiou" # the 5 vowels we check against
count = 0 # start the counter at zero
# Loop through every character in the sentence
for char in sentence.lower(): # .lower() handles uppercase letters too
if char in vowels:
count += 1 # add 1 every time a vowel is found
print("Sentence :", sentence)
print("Vowels found:", count)
Vowels found: 13
What just happened?
sentence.lower()converts the entire sentence to lowercase so that uppercase vowels like"A"or"E"are also counted correctly.char in vowelschecks if the current character is one of the five vowel characters — using theinoperator you learned in earlier lessons.count += 1adds one to the counter each time a vowel is found. After the loop finishes,countholds the total.
9. Program 8 — Reverse a String
Reversing a string means flipping it so the last character comes first. This is used in palindrome checks, text processing, and coding interviews. Python makes reversing a string incredibly simple using slicing.
# The original word or sentence
word = "Programming"
# Slice with step -1 to reverse
reversed_word = word[::-1]
print("Original :", word)
print("Reversed :", reversed_word)
# Practical use: check if a word is a palindrome
# A palindrome reads the same forwards and backwards
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")
Reversed : gnimmargorP
radar → Palindrome ✓
python → Not a palindrome
level → Palindrome ✓
hello → Not a palindrome
madam → Palindrome ✓
What just happened?
word[::-1]— the slice::-1means "start from the end, go backwards one step at a time." This reverses any string or list in one line.- A palindrome is a word that equals itself when reversed —
w == w[::-1]checks this in one simple comparison. - The loop checks 5 words and labels each one correctly — this is a real coding interview question solved in just 3 lines of logic.
10. Program 9 — Remove Duplicates from a List
Duplicate data is a very common problem in real programs — for example, a user submitting the same form twice, or a list of tags with repeated entries. Removing duplicates is a one-step operation using sets, which you learned in Lesson 13.
# A list with duplicate items
emails = [
"user@mail.com",
"admin@site.com",
"user@mail.com",
"guest@mail.com",
"admin@site.com"
]
print("Original :", emails)
print("Count :", len(emails))
# Convert to set (removes duplicates), then back to list
unique_emails = list(set(emails))
print("Unique :", unique_emails)
print("New count :", len(unique_emails))
Count : 5
Unique : ['admin@site.com', 'guest@mail.com', 'user@mail.com']
New count : 3
What just happened?
set(emails)automatically removed the duplicate email addresses — sets cannot hold duplicates.list(...)converts it back to a list so you can work with it normally (sort, index, loop).- This two-step pattern —
list(set(data))— is one of the most used one-liners in Python for data cleaning.
11. Program 10 — Grade Calculator
Given a student's score, this program assigns the correct letter grade using a series of conditions. This is a classic real-world use of if/elif/else — the same logic used in school management systems and learning platforms.
# A list of students with their scores
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}")
----------------------------
Priya 92 A
Kiran 75 B
Arjun 60 C
Sneha 85 B
Rahul 45 D
Meera 100 A
What just happened?
- Each student is stored as a tuple
(name, score)inside the list — this is the nested tuple pattern from Lesson 11. - The loop unpacks each tuple into
nameandscoreusing tuple unpacking, then runs theif/elif/elsechain to assign a grade. {name:<10}in the f-string left-aligns the name in a field 10 characters wide — this keeps the output in neat columns.
12. Program 11 — Count Words in a Sentence
Given a sentence, count the total number of words and find which word appears the most. This uses string splitting and a dictionary to count occurrences — a pattern you saw in Lesson 12.
# A sample sentence
sentence = "learn python learn coding learn programming with python"
# Split into words
words = sentence.split()
print("Total words:", len(words))
# Count how many times each word appears
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 word that appears the most
top_word = max(word_count, key=word_count.get)
top_count = word_count[top_word]
print(f"Most used : '{top_word}' ({top_count} times)")
Word counts: {'learn': 3, 'python': 2, 'coding': 1, 'programming': 1, 'with': 1}
Most used : 'learn' (3 times)
What just happened?
sentence.split()breaks the sentence into a list of individual words at every space.- The dictionary loop counts each word — adding
1if the word is new, or incrementing if it already exists. max(word_count, key=word_count.get)finds the key with the highest value — this is a clean one-liner for finding the most frequent item in any dictionary.
13. Program 12 — FizzBuzz
FizzBuzz is one of the most famous beginner programming challenges — used in coding interviews worldwide. The rule is simple: print numbers from 1 to 20, but replace multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz".
for i in range(1, 21):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz") # divisible by both 3 and 5
elif i % 3 == 0:
print("Fizz") # divisible by 3 only
elif i % 5 == 0:
print("Buzz") # divisible by 5 only
else:
print(i) # not divisible by either
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
What just happened?
- The
FizzBuzzcheck (% 3 == 0 and % 5 == 0) must come first — if you check% 3first,15would print "Fizz" instead of "FizzBuzz". Order of conditions matters. - This program uses only a loop, the modulus operator, and
if/elif/else— three things you already know well. - FizzBuzz is asked in real developer interviews because it tests logical thinking and understanding of conditions — knowing it gives you an edge.
14. Lesson Summary
Here is every program covered in this lesson and the key concepts each one practised.
| Program | Key Concepts Used | Real-World Use |
|---|---|---|
| Swap two numbers | Tuple unpacking | Sorting algorithms |
| Odd or Even | Modulus, loop, conditionals | Form validation |
| Simple Calculator | if / elif / else | Any menu-driven app |
| Largest of Three | Nested conditions, max() | Ranking, scoring |
| Multiplication Table | for loop, range(), f-strings | Report generation |
| Sum / Avg / Min / Max | sum(), len(), min(), max() | Grade reports, dashboards |
| Count Vowels | Loop, in operator, counter | Text analysis |
| Reverse / Palindrome | Slicing [::-1] | Coding interviews |
| Remove Duplicates | list(set()) | Data cleaning |
| Grade Calculator | Tuples, loop, if/elif | School management systems |
| Word Count | split(), dictionary, max() | SEO, spam filters |
| FizzBuzz | Modulus, loop, condition order | Coding interviews worldwide |
🧪 Practice Questions
Answer based on what you learned in this lesson.
1. Write the one-line Python statement to swap variables a and b.
2. Which operator is used to check if a number is odd or even?
3. What slice syntax reverses a string in Python?
4. In FizzBuzz, what should be printed for the number 15?
5. Write the one-line expression to remove duplicates from a list called data and convert it back to a list.
🎯 Quiz — Test Your Understanding
Q1. Which of these words is a palindrome?
Q2. In FizzBuzz, what is printed for the number 9?
Q3. What is the correct expression to calculate the average of a list called marks?
Q4. In the simple calculator program, what happens when num2 = 0 and operator is "/"?
Q5. Which string method is used to break a sentence into a list of individual words?