🐣 Never written code before? You're exactly who this guide is for.

Four habits make this course work without a teacher:

1️⃣ Click every "🎬 Try it" button. They're not decoration β€” watching a loop actually loop teaches more than reading about it ever will.

2️⃣ Read code out loud, top to bottom. Python runs one line at a time, like following a recipe. age = 21 reads as "put 21 into a box called age." If you can say a line in plain words, you understand it.

3️⃣ Take each section's quiz β€” a βœ“ appears in the sidebar when you master it. Wrong answers show explanations; retry until it clicks. Nothing is graded, nobody is watching.

4️⃣ Type things in the β–Ά Live Playground. It runs REAL Python in your browser. Break things on purpose β€” errors are free here, and reading error messages is a skill this course deliberately trains.

πŸ’‘ Sections 1–10 are the heart of Python β€” go in order, one or two per sitting. Sections 11–19 are power-ups you can take slower. Nobody learns this in a day; everybody learns it by clicking around daily.

1 Variables & Data Types

A variable is a labeled box that stores a value. Python figures out the type automatically.

🎬 Try it β€” create the boxes

Click each button to "run" a line of Python and watch the variable box appear on the shelf.

name   = "Ravi"        # str  (text)
age    = 21            # int  (whole number)
gpa    = 8.7           # float (decimal)
passed = True          # bool (True / False)
marks  = [80, 92, 75]  # list (collection)

πŸ’‘ Click a button again and its box just updates to the new value β€” reassigning a variable replaces whatever was there before (the old value is gone). Even marks counts as one value: the whole list lives in a single box.

The 5 core types you'll use every day

TypeExampleUsed for
str"hello"Text β€” always in quotes
int42Whole numbers
float3.14Decimal numbers
boolTrue / FalseYes/No decisions
list[1, 2, 3]Ordered collection of values

πŸ’‘ Check any type with type(x) β€” e.g. type(21) β†’ <class 'int'>

2 If / Elif / Else β€” Decisions

Code takes one path out of many, based on a condition. Like a fork in the road.

🎬 Try it β€” move the slider, watch the path light up

if marks >= 75:
    grade = "Distinction"
elif marks >= 50:
    grade = "Pass"
else:
    grade = "Fail"

marks = 65

start (marks = 65)
↓
marks >= 75 ?
True ↓
grade = "Distinction"
False ↓
marks >= 50 ?
True ↓
grade = "Pass"
False ↓
grade = "Fail"

πŸ’‘ Python checks conditions top to bottom and runs only the first one that is True. Order matters!

Comparison operators

OperatorMeaningExample β†’ Result
==equal to5 == 5 β†’ True
!=not equal5 != 3 β†’ True
> / <greater / less than7 > 10 β†’ False
>= / <=greater/less or equal5 >= 5 β†’ True
andboth must be Trueage > 18 and marks > 50
oreither can be Trueday == "Sat" or day == "Sun"
notflips True/Falsenot passed

⚠️ Classic mistake: = assigns a value, == compares values.

3 For Loops β€” Repeat for Each Item

A for loop visits every item in a collection, one at a time, and runs the same code for each.

🎬 Try it β€” step through the loop

marks = [80, 92, 75, 60, 88]
total = 0
for m in marks:      # m takes each value, one by one
    total = total + m
print(total)          # 395
loop variable m = β€”
total = 0
iteration 0 of 5
Press Next step to run one iteration of the loop.

πŸ’‘ Data flow each iteration: m gets the next item β†’ the loop body runs β†’ repeat until the list is finished.

range() β€” loop a fixed number of times

for i in range(5):     # i = 0, 1, 2, 3, 4  (starts at 0, stops BEFORE 5)
    print("Hello", i)

for i in range(1, 6):   # i = 1, 2, 3, 4, 5
    print(i)

πŸ’‘ range(5) gives 0–4, not 1–5. "Start at 0, stop before the end" is everywhere in Python.

4 While Loops β€” Repeat While True

A while loop keeps running as long as its condition stays True. It checks the condition before every round.

🎬 Try it β€” rocket countdown

count = 5
while count > 0:        # check condition first
    print(count)
    count = count - 1   # ⚠ must change, or loop runs forever!
print("Liftoff! πŸš€")
count > 0 ?
True ↓
print(count)
count = count - 1
…then go back and check again ↩
False ↓
exit loop β†’ "Liftoff! πŸš€"
count = 5
count is 5. Press the button β€” Python will check count > 0 first.

⚠️ If you forget count = count - 1, the condition never becomes False β†’ infinite loop. This is the #1 while-loop bug.

For vs While β€” which one?

for loopwhile loop
Use when…You know what to visit (a list, a range)You know when to stop (a condition)
Example"For each student, print the name""While password is wrong, ask again"
RiskVery safe β€” ends automaticallyCan run forever if condition never turns False

πŸ’‘ break exits any loop immediately; continue skips to the next iteration.

5 Functions β€” Reusable Machines

A function is a machine: data goes in (arguments) β†’ it does its work β†’ a result comes out (return value).

🎬 Try it β€” feed the machine

def add_marks(a, b):        # define: a, b are INPUTS (parameters)
    result = a + b
    return result           # OUTPUT goes back to the caller

total = add_marks(80, 92)   # call it β†’ total becomes 172
a = 80
b = 92
β†’
βš™οΈ add_marks(a, b)
result = a + b
return result
β†’
172

a =   b =

Change a and b, then call the function to see the data flow.

πŸ’‘ Define once, call many times. That's the whole point β€” no copy-pasting the same code.

The 4 pieces of a function

def greet(name):                 # 1️⃣ def + name + parameters
    message = "Hello, " + name    # 2️⃣ body (indented!)
    return message                # 3️⃣ return sends a value back

msg = greet("Priya")               # 4️⃣ call β€” "Priya" flows into name
print(msg)                        # Hello, Priya
TermMeaning
ParameterThe placeholder in the definition β€” name
ArgumentThe real value you pass when calling β€” "Priya"
Return valueWhat comes back out β€” if there's no return, you get None
ScopeVariables created inside a function live only inside it

⚠️ print() shows a value on screen; return hands it back to your code. They are NOT the same thing.

6 Lists β€” Ordered Collections

A list is a row of numbered slots. Positions (indexes) start at 0, and negatives count from the end.

🎬 Try it β€” click an operation, watch the slots

fruits = ["apple", "banana", "mango", "grape"]
Pick an operation above.

πŸ’‘ Slicing rule: fruits[1:3] = start at index 1, stop before index 3 β†’ 2 items.

List operations you'll use constantly

CodeWhat it does
len(fruits)How many items β†’ 4
fruits.append(x)Add x to the end
fruits.insert(1, x)Insert x at position 1 (others shift right)
fruits.remove(x)Delete the first matching x
fruits.sort()Sort in place (A→Z or small→large)
"mango" in fruitsMembership test β†’ True
for f in fruits:Loop over every item (see section 3!)

7 Dictionaries β€” Key β†’ Value Lookup

A dictionary is a lookup table: you don't ask for position #2, you ask for a value by its key β€” like finding a word in a real dictionary.

🎬 Try it β€” look up a key

student = {
    "name":  "Ravi",
    "age":   21,
    "grade": "A",
}
print(student["age"])   # 21
"name"
β†’
"Ravi"
"age"
β†’
21
"grade"
β†’
"A"
Click a lookup. The key lights up, then the value is returned.

πŸ’‘ Keys must be unique. Asking for a key that doesn't exist raises KeyError β€” use student.get("city", "N/A") for a safe default.

List vs Dictionary β€” when to use which?

List [ ]Dictionary { }
Access byPosition: marks[0]Name: student["age"]
Good forA sequence of similar thingsLabeled facts about one thing
ExampleAll students' marksOne student's profile
Loopfor m in marks:for key, value in student.items():

8 Strings & Slicing

A string is a sequence of characters β€” it has indexes just like a list. Blue = counting from the front, pink = from the back.

🎬 Try it β€” slice the word

word = "PYTHON"
Click a slice operation β€” matching characters light up.

Everyday string tools

CodeResult
"python".upper()"PYTHON"
" hi ".strip()"hi" β€” trims spaces
"a,b,c".split(",")["a", "b", "c"] β€” string β†’ list
"-".join(["a","b"])"a-b" β€” list β†’ string
len("python")6
f"Hi {name}, you scored {marks}"f-string β€” variables inside text 🌟

πŸ’‘ f-strings are the modern way to build text: f"Total: {a + b}" even runs the math inside the braces.

9 Error Handling β€” try / except

Instead of crashing, Python can try risky code and catch the failure gracefully.

🎬 Try it β€” safe number conversion

try:
    age = int(user_input)      # risky: what if it's not a number?
    print("Next year you'll be", age + 1)
except ValueError:
    print("That's not a number!")

user_input =

try: age = int(user_input)
works ↓
continue normally 😊
πŸ’₯ ValueError ↓
except block runs πŸ›‘
Type a number like 21, or nonsense like abc, then run it.

πŸ’‘ Rule of thumb: wrap in try/except anything that depends on the outside world β€” user input, files, network, databases.

Common errors students meet first

ErrorUsual cause
SyntaxErrorTypo β€” missing :, unclosed quote or bracket
IndentationErrorWrong spacing β€” Python uses indentation for blocks!
NameErrorUsing a variable before creating it (or a typo in its name)
TypeErrorMixing types: "age: " + 21 (str + int ❌)
IndexErrorfruits[10] when the list has 4 items
KeyErrorDictionary key that doesn't exist
ValueErrorint("abc") β€” right type, wrong value

10 Input & Output

Programs talk with print() (data out) and input() (data in). The #1 trap: input() ALWAYS returns a string, even if the user types a number.

🎬 Try it β€” the input() string trap

age = input("Your age: ")   # user types 5 β†’ age is "5" (a STRING!)
print(age + 5)               # πŸ’₯ TypeError: str + int

age = int(input("Your age: "))  # βœ… convert first
print(age + 5)                  # 10

user types:

Run both versions and compare what happens.

πŸ’‘ Same idea for decimals: float(input()). Whatever comes from the keyboard, a file, or a network is text until YOU convert it.

print() tricks worth knowing

CodeOutput / effect
print("a", "b", 42)a b 42 β€” commas add spaces, mix types freely
print("a", "b", sep="-")a-b β€” custom separator
print("loading", end="...")stays on the same line (no newline)
print(f"{name} is {age}")f-string β€” the everyday workhorse
# this is a commentPython ignores it β€” write WHY, not what

11 Tuples & Sets

Two more containers: a tuple is a list that can never change πŸ”’, and a set is a bag that refuses duplicates 🚫.

🎬 Tuple β€” locked after creation

point = (10, 20)          # round brackets = tuple
x, y = point               # unpacking: x=10, y=20 ✨
point[0] = 99              # πŸ’₯ TypeError!
Reading is fine. Changing is forbidden. Try all three.

πŸ’‘ Use a tuple for things that should never change: coordinates, RGB colors, (day, month, year). The lock is a feature, not a limitation.

🎬 Set β€” duplicates bounce off

visitors = set()
visitors.add("ravi")
visitors.add("ravi")     # ignored β€” already there!
print(len(visitors))     # 1
Add names β€” then add the same name twice and watch it get rejected.

πŸ’‘ Instant use case: unique_visitors = set(visitor_list) β€” de-duplicate any list in one line. Membership tests (x in my_set) are also lightning fast.

The 4 containers side by side

list [ ]tuple ( )set { }dict {k: v}
Ordered?βœ…βœ…βŒβœ… (by insertion)
Changeable?βœ…βŒ lockedβœ…βœ…
Duplicates?βœ…βœ…βŒ neverkeys: ❌
Best forsequencesfixed recordsuniquenesslookups

12 List Comprehensions

A one-line factory: take each item β†’ keep it if it passes the filter β†’ transform it β†’ collect the results. Pythonic superpower.

🎬 Try it β€” watch numbers go through the pipeline

numbers = [1, 2, 3, 4, 5, 6]

# the loop way (4 lines):
result = []
for x in numbers:
    if x % 2 == 0:
        result.append(x * x)

# the comprehension way (1 line β€” SAME thing):
result = [x * x for x in numbers if x % 2 == 0]
#         ⬆ transform   ⬆ source      ⬆ filter
x = β€”
x % 2 == 0 ? β€”
result = []
Step through β€” odd numbers get filtered out, even ones get squared and collected.

πŸ’‘ Read it aloud: "x squared, for each x in numbers, if x is even." If a comprehension gets hard to read aloud, use a normal loop instead.

Comprehension recipes

GoalOne-liner
Transform all[n.upper() for n in names]
Filter only[m for m in marks if m >= 50]
Both[m*2 for m in marks if m > 0]
Dict comprehension{name: len(name) for name in names}
From a string[c for c in "python" if c in "aeiou"] β†’ ['o']

13 Lambda & Sorting

A lambda is a tiny unnamed one-line function β€” mostly used to tell sorted() what to sort by.

🎬 Try it β€” sort students by different keys

students = [("Ravi", 80), ("Priya", 92), ("Amit", 45)]

sorted(students, key=lambda s: s[1])                # by marks ↑
sorted(students, key=lambda s: s[1], reverse=True)  # by marks ↓ (toppers first)
sorted(students, key=lambda s: s[0])                # by name A→Z
Original: [("Ravi", 80), ("Priya", 92), ("Amit", 45)]

πŸ’‘ Read lambda s: s[1] as: "given a student s, sort using s[1] (the marks)". That's all a lambda is β€” a mini function without a name.

lambda + friends

ToolExampleResult
lambdadouble = lambda x: x * 2double(5) β†’ 10
max(..., key=)max(students, key=lambda s: s[1])("Priya", 92) β€” the topper
map()list(map(str.upper, names))all names uppercased
filter()list(filter(lambda m: m >= 50, marks))only passing marks

πŸ’‘ Honest advice: for map/filter, most Pythonistas prefer list comprehensions (section 12). But key=lambda in sorting is used everywhere β€” master that one.

14 Scope β€” Where Variables Live

Variables live inside rooms. Code inside a function can look outward to the global room β€” but the outside can never look into a function.

🎬 Try it β€” who can see whom?

x = 10                 # GLOBAL β€” everyone can read it
def calc():
    y = 5              # LOCAL β€” exists only inside calc()
    print(x + y)       # works: local y + global x
calc()                 # 15
print(y)               # πŸ’₯ NameError β€” y died when calc() ended!
GLOBAL scope (the whole file) x = 10
LOCAL scope β€” inside calc() y = 5
Inside looks out βœ…. Outside cannot look in ❌. Try both.

πŸ’‘ Lookup order = LEGB: Local β†’ Enclosing β†’ Global β†’ Built-in. Python searches the nearest room first, then widens.

Golden rules

1️⃣ Variables created inside a function are born when it's called and destroyed when it returns.

2️⃣ Reading a global from inside a function: fine. Changing one: needs global x β€” and if you find yourself doing that, usually the better design is to pass it in as a parameter and return the new value.

3️⃣ This is why functions are safe to reuse: whatever mess happens inside, stays inside. 🧹

15 File Handling

Scripts become useful when they remember things after they end β€” by reading and writing files on disk.

🎬 Try it β€” a simulated notes.txt on disk

with open("notes.txt", "w") as f:   # "w" = write (⚠ erases existing!)
    f.write("Buy milk\n")

with open("notes.txt", "a") as f:   # "a" = append (adds to end)
    f.write("Pay fees\n")

with open("notes.txt", "r") as f:   # "r" = read
    for line in f:
        print(line.strip())
πŸ’Ύ notes.txt (on disk)
β€” file does not exist yet β€”
Write, append, read β€” then see what a second "w" does to your data…

πŸ’‘ with closes the file automatically, even if an error happens inside. Always use with β€” never bare open().

File modes

ModeMeaningIf file existsIf it doesn't
"r"readopens itπŸ’₯ FileNotFoundError
"w"write⚠ ERASES itcreates it
"a"appendadds to the endcreates it

πŸ’‘ Wrap file reads in try/except FileNotFoundError (section 9) β€” files are "outside world" and can always be missing.

16 Modules & Imports

Don't reinvent the wheel β€” import ready-made toolboxes. Python ships with 200+ built-in modules, and pip unlocks 500,000 more.

🎬 Try it β€” call the standard library

πŸ“œ my_script.py
import …
β†’
πŸ“ math
🎲 random
πŸ• datetime
Each call reaches into a different toolbox. The dice is genuinely random β€” click it twice!

πŸ’‘ Three import styles: import math β†’ math.sqrt(x)  Β·  from math import sqrt β†’ sqrt(x)  Β·  avoid from math import * (pollutes your namespace).

Beyond built-ins: pip

# in the terminal (not in Python!):
pip install requests
PackageSuperpower
requestsCall web APIs in 2 lines
pandasExcel-like data tables in code
fastapiBuild web APIs (powers real backends!)
pymongoTalk to MongoDB databases

πŸ’‘ Your own files are modules too! If you have helpers.py, then import helpers works from any script in the same folder.

17 Classes & Objects (OOP)

A class is a blueprint πŸ“‹. An object is a real thing built from it 🏠. One blueprint β†’ many objects, each with its own data.

🎬 Try it β€” build students from the blueprint

class Student:
    def __init__(self, name, marks):   # runs automatically at creation
        self.name = name                # self = "THIS particular student"
        self.marks = marks
    def show(self):
        return f"{self.name} scored {self.marks}"

ravi  = Student("Ravi", 80)    # build object #1
priya = Student("Priya", 92)   # build object #2 β€” separate data!
print(ravi.show())            # Ravi scored 80
πŸ“‹ class Student
__init__(self, name, marks)
show(self)
β†’
Create both objects β€” notice each card keeps its OWN name and marks.

πŸ’‘ self just means "this particular object". When you call ravi.show(), Python secretly passes ravi in as self.

Why bother with classes?

Without classes: parallel lists that can drift apart β€” names[3], marks[3], grades[3]… 😰

With classes: data + the functions that work on it, bundled together. A Student carries its own marks and knows how to display itself.

TermMeaning
classThe blueprint / template
object / instanceOne real thing built from it
attributeData attached to an object β€” ravi.marks
methodA function attached to an object β€” ravi.show()
__init__The constructor β€” sets up a new object

πŸ’‘ You've been using objects all along! "hi".upper(), fruits.append() β€” strings and lists are objects with methods.

18 JSON β€” How Programs Exchange Data

JSON is a dictionary written as text β€” the universal language of APIs, config files, and web apps. Python ↔ JSON is a two-line conversion.

🎬 Try it β€” convert back and forth

import json
text = json.dumps(student)   # dict β†’ text  (dump to string)
data = json.loads(text)      # text β†’ dict  (load from string)
🐍 Python dict (lives in memory)
student = {
  "name": "Ravi",
  "marks": [80, 92],
  "passed": True
}
⇄
πŸ“„ JSON text (can be saved / sent anywhere)
'{"name": "Ravi",
  "marks": [80, 92],
  "passed": true}'
Spot the tiny differences: Python's True becomes JSON's true, and JSON always uses double quotes.

πŸ’‘ Every web API you'll ever call returns JSON. requests.get(url).json() β†’ instantly a Python dict β†’ use everything from section 7!

The 4 json functions

FunctionConvertsTypical use
json.dumps(d)dict β†’ stringsend to an API
json.loads(s)string β†’ dictparse an API response
json.dump(d, f)dict β†’ filesave config/settings
json.load(f)file β†’ dictread config/settings

πŸ’‘ Memory hook: the s in dumps/loads = string. Without s = file.

19 Pro Patterns β€” Write Python Like a Pythonista

Small idioms that separate "I know Python syntax" from "I write clean Python".

Looping like a pro

# need the position too? β†’ enumerate (NOT range(len(...)))
for i, name in enumerate(students, start=1):
    print(f"{i}. {name}")          # 1. Ravi  2. Priya  3. Amit

# two lists in parallel? β†’ zip
for name, mark in zip(students, marks):
    print(f"{name}: {mark}")

# loop a dictionary? β†’ .items()
for key, value in student.items():
    print(key, "β†’", value)

Everyday one-liners

PatternCode
Swap two variablesa, b = b, a β€” no temp variable!
Conditional in one linestatus = "Pass" if marks >= 50 else "Fail"
Membership testif name in students:
Default dict valuemarks.get(name, 0)
Count anythingfrom collections import Counter; Counter(words)
Sum / max / min / sortsum(marks), max(marks), sorted(marks)
f-string debuggingprint(f"{total=}") β†’ prints total=395

The script skeleton every .py file should have

"""What this script does β€” one line."""
import json                          # 1. imports at the top

def main():                          # 2. real work inside functions
    ...

if __name__ == "__main__":           # 3. the "main guard"
    main()

πŸ’‘ The main guard means: "run main() only when this file is executed directly β€” not when it's imported by another script." Every professional Python file has it.

20 Practice Exercises

Reading β‰  learning. Solve these in a real Python file β€” peek at a solution only after trying. Each one maps to a section above.

🟒 Warm-up

1. Hello, you variables Β· f-strings

Ask for the user's name and birth year, then print "Hi Ravi, you turn 25 in 2026!"

Show solution
name = input("Name: ")
year = int(input("Birth year: "))
print(f"Hi {name}, you turn {2026 - year} in 2026!")
2. Even or odd if/else Β· %

Read a number and print whether it's even or odd.

Show solution
n = int(input("Number: "))
if n % 2 == 0:
    print("Even")
else:
    print("Odd")
3. Sum of 1 to 100 for Β· range

Use a loop to add up 1+2+…+100. (Answer: 5050)

Show solution
total = 0
for i in range(1, 101):
    total += i          # shorthand for total = total + i
print(total)            # 5050 β€” or cheat: sum(range(1, 101))

🟑 Building strength

4. Grade function functions Β· elif

Write get_grade(marks) β†’ "Distinction" (β‰₯75), "Pass" (β‰₯50), else "Fail". Test with 3 values.

Show solution
def get_grade(marks):
    if marks >= 75: return "Distinction"
    if marks >= 50: return "Pass"
    return "Fail"

for m in [90, 60, 30]:
    print(m, "β†’", get_grade(m))
5. Vowel counter strings Β· for Β· in

Count the vowels in "programming is beautiful". (Answer: 9)

Show solution
text = "programming is beautiful"
count = 0
for ch in text:
    if ch in "aeiou":
        count += 1
print(count)   # 9 β€” one-liner: sum(1 for c in text if c in "aeiou")
6. Biggest without max() loops Β· comparison

Find the largest number in [34, 78, 12, 91, 45] without using max().

Show solution
nums = [34, 78, 12, 91, 45]
biggest = nums[0]           # start with the first
for n in nums:
    if n > biggest:
        biggest = n
print(biggest)             # 91
7. Guess the number while Β· random Β· break

Pick a random 1–10, let the user guess until correct, say "higher"/"lower" each time.

Show solution
import random
secret = random.randint(1, 10)
while True:
    guess = int(input("Guess: "))
    if guess == secret:
        print("Correct! πŸŽ‰")
        break
    print("Higher!" if guess < secret else "Lower!")

πŸ”΄ Level up

8. Class report dict Β· loop Β· f-string

Given {"Ravi": 80, "Priya": 92, "Amit": 45}, print each student's grade (reuse exercise 4!) and the class average.

Show solution
marks = {"Ravi": 80, "Priya": 92, "Amit": 45}
for name, m in marks.items():
    print(f"{name}: {m} β†’ {get_grade(m)}")
avg = sum(marks.values()) / len(marks)
print(f"Class average: {avg:.1f}")   # 72.3
9. Crash-proof calculator try/except Β· functions

Read two numbers and divide them. Handle BOTH bad input ("abc") and division by zero β€” the program must never crash.

Show solution
try:
    a = float(input("a: "))
    b = float(input("b: "))
    print(f"{a} / {b} = {a / b}")
except ValueError:
    print("Please enter numbers only!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
10. Word frequency dict Β· split Β· get

Count how often each word appears in "the cat and the dog and the bird".

Show solution
text = "the cat and the dog and the bird"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)   # {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}
11. Persistent to-do list files Β· loops Β· with

A script that appends whatever the user types to todo.txt, then prints all saved tasks numbered.

Show solution
task = input("New task: ")
with open("todo.txt", "a") as f:
    f.write(task + "\n")

with open("todo.txt") as f:          # "r" is the default mode
    for i, line in enumerate(f, 1):
        print(f"{i}. {line.strip()}")
12. Student class OOP Β· methods

Build a Student class with name + a list of marks, an average() method, and a grade() method that uses the average. Create two students and print their report cards.

Show solution
class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks
    def average(self):
        return sum(self.marks) / len(self.marks)
    def grade(self):
        avg = self.average()
        if avg >= 75: return "Distinction"
        if avg >= 50: return "Pass"
        return "Fail"

for s in [Student("Ravi", [80, 75, 88]), Student("Amit", [40, 55, 35])]:
    print(f"{s.name}: avg {s.average():.1f} β†’ {s.grade()}")

21 One-Page Mental Model

How every concept connects β€” the big picture of a Python program.

# 1. STORE data in variables
students = ["Ravi", "Priya", "Amit"]        # list
marks    = {"Ravi": 80, "Priya": 92, "Amit": 45}   # dict

# 2. WRAP logic in a function (define once…)
def get_grade(score):
    if score >= 75:          # 3. DECIDE with if/elif/else
        return "Distinction"
    elif score >= 50:
        return "Pass"
    return "Fail"

# 4. REPEAT with a loop (…call many times)
for name in students:
    score = marks[name]                       # dict lookup
    print(f"{name}: {score} β†’ {get_grade(score)}")  # f-string

# Output:
# Ravi: 80 β†’ Distinction
# Priya: 92 β†’ Distinction
# Amit: 45 β†’ Fail

Every Python program is just these moves combined: store data β†’ make decisions β†’ repeat work β†’ wrap it in functions β†’ handle failures. Master these 5 and everything else (files, APIs, classes) is built on top.

πŸ”“ See course prices