StudyHub
🐍 Python
← Coding Notes
Language notes · Beginner to confident

Python notes for beginners

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 all Great for: AI, data, automation, school CS Run with: python hello.py 9 chapters · 20+ examples
01

What Python is & how to run it

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).
Python hello.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

TypeHoldsExampleConvert with
intWhole numbers7, -42int("7")
floatDecimals3.14float("3.14")
strText in quotes"hello"str(99)
boolTrue or FalseTruebool(0) → False
NoneType"nothing yet"None
Python types.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.
03

Operators

Maths, comparisons and combining conditions

OperatorMeaningExampleResult
+ - *Add, subtract, multiply7 * 321
/Divide — always a decimal7 / 23.5
//Integer division, drops the fraction7 // 23
%Remainder7 % 21
**Power2 ** 532
== !=Equal, not equal5 != 3True
> < >= <=Comparisons7 > 3True
and or notCombine conditionsa and bTrue if both true
Python gst.py
price = 499
qty = 2
gst = 0.18

subtotal = price * qty
tax = subtotal * gst
total = subtotal + tax

print(f"Subtotal: {subtotal}")
print(f"Total   : {round(total, 2)}")

# comparisons give True / False
print(total > 1000)               # False
print(0 <= 5 < 100)               # True - Python chains comparisons

# logical operators
member = True
print(total > 800 or member)      # True
04

Conditions & loops

Making decisions, then repeating work

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.

Python decisions.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)
Python loops.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.

Python functions.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

TypeWritten asChangeableUse it for
list[1, 2, 3]YesAny sequence you will edit
tuple(1, 2, 3)NoFixed values that must not change
set{1, 2, 3}Yes, no duplicatesRemoving repeats, fast lookups
dict{"a": 1}YesLabelled records — key → value
Python collections.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

Python strings.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 immutableword[0] = "b" is an error. Every method returns a new string, so keep the result: name = name.strip().
  • 2
    "5" + "5" gives "55", not 10. Convert first: int("5") + int("5").
  • 3
    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

Terminal how 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.
  • 4
    TypeError — mixing types: "5" + 5. Convert with int() / str().
  • 5
    IndexError — you asked for position 3 of a list that only has 3 items (positions 0, 1, 2).
Python safe_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 thisWrite thisYou get
Show outputprint("hi")hi
Ask for inputinput("Name: ")text
Whole numberint("15")15
Decimalfloat("9.5")9.5
Format textf"{name} is {age}"joined string
Decideif x > 5:runs the block
Either / ora if cond else bone value
Repeat n timesfor i in range(n):0 … n-1
Repeat untilwhile cond:loop
Leave a loopbreakstops it
Skip one roundcontinuenext round
Define a functiondef f(x): return xreusable block
Make a listm = [1, 2, 3]list
Add to a listm.append(4)list grows
Sortsorted(m)new sorted list
Loop with indexfor i, v in enumerate(m):index + value
Make a dictionaryd = {"a": 1}dict
Safe lookupd.get("a", 0)value or fallback
Loop a dictfor k, v in d.items():key + value
Handle an errortry: … except: …no crash
Import a toolimport mathmath.sqrt()

Practice project: marks report card

Python report.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?

Q2 What does range(4) produce?

Q3 Which line converts the text "15" into a number?

Q4 What does a function return if it has no return statement?

Answered 0 of 4 · correct 0

Continue with another language

Same structure, same depth — pick the one you need next.