Python reads almost like English, which is why it is the most recommended
first language in the world — and the language behind AI, data science and most school
computer papers. Nine short chapters take you from your first print() to writing your own functions.
Difficulty: Easiest of allGreat for: AI, data, automation, school CSRun with:python hello.py9 chapters · 20+ examples
Five minutes of setup, then you never need a browser again
Python is a general-purpose, interpreted language: your file is read and executed
line by line, so you can test an idea instantly. It was created by Guido van Rossum in 1991 and is
now the standard language for AI, data analysis and teaching.
Setting up
1
Install Python from python.org (tick Add Python to PATH on Windows).
2
Install VS Code and its Python extension — that gives you highlighting, hints and a run button.
3
Save your file with a .py ending, for example hello.py.
4
Run it in the terminal with python hello.py (or python3 on Mac and Linux).
Pythonhello.py
# comments start with a hash
print("Hello, Study Hub!") # shows text
print(2 + 3) # shows 5
print("Hi", "there") # shows Hi there
02
Variables & data types
Named boxes that hold your data
You create a variable simply by giving a value a name. No keyword, no type declaration — Python
works it out for you.
name"Ayush"str — text
marks87int — whole number
percent87.5float — decimal
passedTruebool — yes / no
The types you need first
Type
Holds
Example
Convert with
int
Whole numbers
7, -42
int("7")
float
Decimals
3.14
float("3.14")
str
Text in quotes
"hello"
str(99)
bool
True or False
True
bool(0) → False
NoneType
"nothing yet"
None
—
Pythontypes.py
student = "Ayush" # str
marks = 87 # int
percent = 87.5 # float
passed = True # bool
print(type(marks)) # <class 'int'>
# input() ALWAYS returns text - convert it before doing maths
age = int(input("Your age: "))
print("Next year:", age + 1)
# f-strings are the neatest way to build text
print(f"{student} scored {marks} ({percent}%)")
Naming rules
1
Letters, digits and underscores only, and it must not start with a digit: marks2 ✓, 2marks ✗.
2
Case matters — Marks and marks are different variables.
3
Reserved words are off limits: if, else, for, class, def, import, return, True.
4
Use words that say what the value means: total_marks beats x.
if chooses a path, for repeats a known number of times, and
while repeats until something changes. Everything you ever write is built from these
three.
Pythondecisions.py
marks = 78
# checked in order - the first match wins
if marks >= 90:
grade = "A+"
elif marks >= 75:
grade = "A"
elif marks >= 33:
grade = "B"
else:
grade = "F"
print(grade) # A
# one-line version
label = "Pass" if marks >= 33 else "Fail"
print(label)
Pythonloops.py
# for - when you know the count
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
# for - walk through a collection
for subject in ["Maths", "Science"]:
print("I study", subject)
# while - until something changes
count = 1
while count <= 3:
print("Round", count)
count += 1 # without this it never ends
# break stops, continue skips one round
for n in range(1, 11):
if n == 8:
break
if n % 2 == 0:
continue
print(n, "is odd")
1
Every if, elif, else, for and while line ends with a colon :.
2
The indented block underneath is what runs. Wrong indentation is the most common beginner error in Python.
3
range(5) gives 0,1,2,3,4 — the end value is never included.
4
A while loop whose condition never becomes false runs forever. Press Ctrl + C if it happens.
05
Functions
Write it once, use it everywhere
def defines a reusable block. You give it values (arguments), it does
the work, and return hands a result back.
Pythonfunctions.py
def greet(name):
return f"Hello, {name}!"
print(greet("Ayush"))
# several parameters
def average(a, b):
return (a + b) / 2
print(average(80, 90)) # 85.0
# default values make an argument optional
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25
print(power(2, 10)) # 1024
# a function with no return gives back None
def notice():
print("Fees due on 10th")
notice()
Scope — where variables live
1
A variable created inside a function is local and disappears when the function ends.
2
Variables created outside are global — read them freely, but pass values in and return results rather than editing them inside functions.
3
One function, one job, a name that says what it does. If you need the word "and" to describe it, split it into two.
06
Lists, tuples, sets & dictionaries
One variable holding many values
Type
Written as
Changeable
Use it for
list
[1, 2, 3]
Yes
Any sequence you will edit
tuple
(1, 2, 3)
No
Fixed values that must not change
set
{1, 2, 3}
Yes, no duplicates
Removing repeats, fast lookups
dict
{"a": 1}
Yes
Labelled records — key → value
Pythoncollections.py
marks = [78, 91, 66]
marks.append(88) # add to the end
print(marks[0], marks[-1]) # 78 88 (0 = first, -1 = last)
print(len(marks), sum(marks)) # 4 323
print(marks[0:2]) # [78, 91] - stop not included
student = {"name": "Ayush", "marks": {"Maths": 78, "Science": 91}}
print(student["name"])
print(student["marks"]["Science"]) # 91
student["city"] = "Shimla" # add a key
print(student.get("phone", "none")) # safe lookup, never crashes
for subject, score in student["marks"].items():
print(f"{subject}: {score}")
# a list of dictionaries is the most useful shape you will ever learn
class_marks = [
{"name": "Ayush", "marks": [78, 91, 66]},
{"name": "Riya", "marks": [92, 88, 95]},
]
for s in class_marks:
avg = sum(s["marks"]) / len(s["marks"])
print(f'{s["name"]}: {avg:.1f}')
07
Strings
Names, answers and messages — it is all text
Pythonstrings.py
name = " Ayush Danthta "
print(name.strip()) # remove spaces from both ends
print(name.strip().lower()) # ayush danthta
print(name.strip().upper()) # AYUSH DANTHTA
print(name.strip().title()) # Ayush Danthta
print(len("Study")) # 5
email = "study.hub09@gmail.com"
print("@" in email) # True
print(email.replace("gmail", "yahoo"))
print(email.split("@")) # ['study.hub09', 'gmail.com']
word = "PROGRAMMING"
print(word[0]) # P
print(word[0:7]) # PROGRAM
print(word[::-1]) # GNIMMARGORP
# f-strings format numbers neatly
marks, total = 264, 300
print(f"{marks}/{total} = {marks / total * 100:.1f}%")
1
Strings are immutable — word[0] = "b" is an error. Every method returns a new string, so keep the result: name = name.strip().
Use f-strings (f"{name} scored {marks}") instead of gluing bits together with +.
08
Errors & common beginner mistakes
Read the last line of the message — it names the problem
Terminalhow to read a traceback
Traceback (most recent call last):
File "marks.py", line 4, in <module>
print(total / count)
ZeroDivisionError: division by zero
# read it bottom to top:
# 1. ZeroDivisionError -> what went wrong
# 2. print(total / count) -> the line that caused it
# 3. line 4 -> where to look in your file
The five errors you will meet this week
1
SyntaxError — a missing colon, bracket or quote. The program never starts. Check the line it points at, and the line above it.
2
IndentationError — Python is strict about spacing. Use 4 spaces consistently; never mix tabs and spaces.
3
NameError — you used a variable before creating it, or you misspelled it. Python reads top to bottom.
IndexError — you asked for position 3 of a list that only has 3 items (positions 0, 1, 2).
Pythonsafe_input.py
# stop a crash before it happens
while True:
raw = input("Your age: ").strip()
try:
age = int(raw)
break
except ValueError:
print(f'"{raw}" is not a number. Try again.')
print("Next year you will be", age + 1)
09
Python cheat sheet
Keep this open while you practise
Do this
Write this
You get
Show output
print("hi")
hi
Ask for input
input("Name: ")
text
Whole number
int("15")
15
Decimal
float("9.5")
9.5
Format text
f"{name} is {age}"
joined string
Decide
if x > 5:
runs the block
Either / or
a if cond else b
one value
Repeat n times
for i in range(n):
0 … n-1
Repeat until
while cond:
loop
Leave a loop
break
stops it
Skip one round
continue
next round
Define a function
def f(x): return x
reusable block
Make a list
m = [1, 2, 3]
list
Add to a list
m.append(4)
list grows
Sort
sorted(m)
new sorted list
Loop with index
for i, v in enumerate(m):
index + value
Make a dictionary
d = {"a": 1}
dict
Safe lookup
d.get("a", 0)
value or fallback
Loop a dict
for k, v in d.items():
key + value
Handle an error
try: … except: …
no crash
Import a tool
import math
math.sqrt()
Practice project: marks report card
Pythonreport.py
students = [
{"name": "Ayush", "marks": [78, 91, 66]},
{"name": "Riya", "marks": [92, 88, 95]},
{"name": "Karan", "marks": [45, 52, 60]},
]
def average(nums):
return sum(nums) / len(nums) if nums else 0
def grade_of(avg):
if avg >= 85: return "A"
if avg >= 70: return "B"
if avg >= 50: return "C"
return "D"
print("=" * 34)
for s in students:
avg = average(s["marks"])
print(f'{s["name"]:<6} {avg:6.1f} grade {grade_of(avg)}')
print("=" * 34)
✓
Test yourself
Four quick questions on Python basics
Q1 What does 7 % 2 give?
Why:% is the remainder. 2 × 3 = 6, so 1 is left over. 7 // 2 would give 3.
Q2 What does range(4) produce?
Why:range starts at 0 and stops before the value you give it, so you get exactly 4 numbers.
Q3 Which line converts the text "15" into a number?
Why:int() parses text into a whole number, float() into a decimal. "15" + 0 raises a TypeError.
Q4 What does a function return if it has no return statement?
Why: Python gives back None — the value that means "nothing". Printing it shows the word None.
Answered 0 of 4 · correct 0
Continue with another language
Same structure, same depth — pick the one you need next.