π£ 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
| Type | Example | Used for |
|---|---|---|
str | "hello" | Text β always in quotes |
int | 42 | Whole numbers |
float | 3.14 | Decimal numbers |
bool | True / False | Yes/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
π‘ Python checks conditions top to bottom and runs only the first one that is True. Order matters!
Comparison operators
| Operator | Meaning | Example β Result |
|---|---|---|
== | equal to | 5 == 5 β True |
!= | not equal | 5 != 3 β True |
> / < | greater / less than | 7 > 10 β False |
>= / <= | greater/less or equal | 5 >= 5 β True |
and | both must be True | age > 18 and marks > 50 |
or | either can be True | day == "Sat" or day == "Sun" |
not | flips True/False | not 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
π‘ 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 = count - 1
β¦then go back and check again β©
β οΈ 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 loop | while 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" |
| Risk | Very safe β ends automatically | Can 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
return result
a = b =
π‘ 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
| Term | Meaning |
|---|---|
| Parameter | The placeholder in the definition β name |
| Argument | The real value you pass when calling β "Priya" |
| Return value | What comes back out β if there's no return, you get None |
| Scope | Variables 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"]
π‘ Slicing rule: fruits[1:3] = start at index 1, stop before index 3 β 2 items.
List operations you'll use constantly
| Code | What 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 fruits | Membership 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
π‘ 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 by | Position: marks[0] | Name: student["age"] |
| Good for | A sequence of similar things | Labeled facts about one thing |
| Example | All students' marks | One student's profile |
| Loop | for 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"
Everyday string tools
| Code | Result |
|---|---|
"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 =
π‘ Rule of thumb: wrap in try/except anything that depends on the outside world β user input, files, network, databases.
Common errors students meet first
| Error | Usual cause |
|---|---|
SyntaxError | Typo β missing :, unclosed quote or bracket |
IndentationError | Wrong spacing β Python uses indentation for blocks! |
NameError | Using a variable before creating it (or a typo in its name) |
TypeError | Mixing types: "age: " + 21 (str + int β) |
IndexError | fruits[10] when the list has 4 items |
KeyError | Dictionary key that doesn't exist |
ValueError | int("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:
π‘ 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
| Code | Output / 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 comment | Python 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!
π‘ 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
π‘ 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? | β | β | β never | keys: β |
| Best for | sequences | fixed records | uniqueness | lookups |
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
π‘ 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
| Goal | One-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
π‘ 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
| Tool | Example | Result |
|---|---|---|
lambda | double = lambda x: x * 2 | double(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!
π‘ 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())
π‘ with closes the file automatically, even if an error happens inside. Always use with β never bare open().
File modes
| Mode | Meaning | If file exists | If it doesn't |
|---|---|---|---|
"r" | read | opens it | π₯ FileNotFoundError |
"w" | write | β ERASES it | creates it |
"a" | append | adds to the end | creates 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
import β¦
π‘ 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
| Package | Superpower |
|---|---|
requests | Call web APIs in 2 lines |
pandas | Excel-like data tables in code |
fastapi | Build web APIs (powers real backends!) |
pymongo | Talk 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
show(self)
π‘ 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.
| Term | Meaning |
|---|---|
| class | The blueprint / template |
| object / instance | One real thing built from it |
| attribute | Data attached to an object β ravi.marks |
| method | A 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)
π‘ 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
| Function | Converts | Typical use |
|---|---|---|
json.dumps(d) | dict β string | send to an API |
json.loads(s) | string β dict | parse an API response |
json.dump(d, f) | dict β file | save config/settings |
json.load(f) | file β dict | read 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
| Pattern | Code |
|---|---|
| Swap two variables | a, b = b, a β no temp variable! |
| Conditional in one line | status = "Pass" if marks >= 50 else "Fail" |
| Membership test | if name in students: |
| Default dict value | marks.get(name, 0) |
| Count anything | from collections import Counter; Counter(words) |
| Sum / max / min / sort | sum(marks), max(marks), sorted(marks) |
| f-string debugging | print(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
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!")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")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
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))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")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) # 91Pick 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
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.3Read 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!")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}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()}")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.