Basic Programs in Python | Python Course | Dataplexa

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)
Before swap: a = 10 | b = 20 After swap : a = 20 | b = 10
  • Python evaluates b, a on the right side first — giving the pair (20, 10) — then assigns both values simultaneously to a and b.
  • 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")
4 → Even 7 → Odd 12 → Even 19 → Odd 0 → Even 33 → Odd
  • num % 2 is 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)
20 / 4 = 5.0
  • 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 operator to "+", "-", "*", 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))
Largest is: 78 Using max(): 78
  • The first if checks if a is greater than or equal to both others. If not, it checks b. If neither wins, c must be the largest.
  • max() does the same thing in one word — but understanding the manual version first shows you what max() is doing internally.
  • Try setting all three to the same value — the first if handles 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}")
--- Multiplication Table of 7 --- 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
  • range(1, 11) generates numbers 1 through 10 — the stop value 11 is excluded, which is why we write 11 to get up to 10.
  • {i:2} inside the f-string pads single-digit numbers with a space so the columns stay neatly aligned.
  • Change number = 7 to 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)
Marks : [72, 85, 90, 60, 78, 95, 88] Total : 568 Count : 7 Average : 81.14 Lowest : 60 Highest : 95
  • sum(), len(), min(), and max() 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 simply total / 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 : Python programming is fun and easy to learn Vowels found: 13
  • sentence.lower() converts everything to lowercase so capital vowels like "A" or "E" are counted correctly — not case-sensitive.
  • char in vowels checks if the current character is one of the five vowel characters in the string "aeiou".
  • count += 1 adds one every time a vowel is found. After the loop, count holds 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")
Original : Programming Reversed : gnimmargorP radar → Palindrome python → Not a palindrome level → Palindrome hello → Not a palindrome madam → Palindrome
  • word[::-1] — the step -1 means "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))
Original : ['user@mail.com', 'admin@site.com', 'user@mail.com', 'guest@mail.com', 'admin@site.com'] Count : 5 Unique : ['admin@site.com', 'guest@mail.com', 'user@mail.com'] New count : 3
  • 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}")
Name Score Grade ---------------------------- Priya 92 A Kiran 75 B Arjun 60 C Sneha 85 B Rahul 45 D Meera 100 A
  • 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 name and score using 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)")
Total words: 8 Word counts: {'learn': 3, 'python': 2, 'coding': 1, 'programming': 1, 'with': 1} Most used : 'learn' (3 times)
  • sentence.split() breaks the sentence into a list of words at every space character.
  • The dictionary loop adds 1 when 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)
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz
  • The FizzBuzz check must come first — if you check % 3 first, 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

ProgramKey ConceptsReal-World Use
Swap Two NumbersTuple unpackingSorting algorithms
Odd or EvenModulus, loop, conditionalsForm validation, game logic
Simple Calculatorif / elif / else, division safetyMenu-driven apps
Largest of ThreeCompound conditions, max()Ranking, scoring systems
Multiplication Tablefor loop, range(), f-stringsReport generation
Sum / Avg / Min / Maxsum(), len(), min(), max(), round()Dashboards, grade reports
Count VowelsLoop, in operator, counterText analysis, NLP
Reverse / PalindromeSlicing [::-1]Coding interviews
Remove Duplicateslist(set())Data cleaning pipelines
Grade CalculatorTuples, loop, if/elif unpackingSchool management systems
Word Frequencysplit(), dictionary, max(key)SEO analysis, spam filters
FizzBuzzModulus, condition orderDeveloper 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?






NEXT UP
Functions in Python
Learn how to write reusable blocks of code using functions — the building block of every professional Python program. Define once, use everywhere.