Table of Contents
Basic Script Structure
- A Python file ends with
.py - Run top‑to‑bottom
- Indentation uses spaces (PEP 8 recommends 4 spaces)
# This is a comment
def main():
print("Hello")
if __name__ == "__main__":
main()Comments
- Single line:
# comment - Inline comment:
code # comment
Variables and Basic Types
- Assignment:
name = value - No declaration keyword; type is inferred.
Common literals:
- Integers:
0,1,-5,10 - Floats:
0.0,3.14,-2.5,1e3 - Strings:
"hello",'world' - Booleans:
True,False - None:
None
Multiple assignment:
x, y = 1, 2
a = b = 0Check type:
type(42) # <class 'int'>
type("hi") # <class 'str'>Arithmetic Operators
- Addition:
a + b - Subtraction:
a - b - Multiplication:
a * b - Division (float):
a / b - Floor division:
a // b - Modulo (remainder):
a % b - Power:
a ** b
Augmented assignment:
x += 1 # x = x + 1
x -= 2 # x = x - 2
x *= 3
x /= 4Comparison and Logical Operators
Comparison (result is True or False):
- Equal:
a == b - Not equal:
a != b - Less than:
a < b - Greater than:
a > b - Less or equal:
a <= b - Greater or equal:
a >= b
Logical:
andornot
age = 20
is_adult = age >= 18 and age < 65Identity / membership (common usage):
is,is notin,not in
x is None
"py" in "python"Strings
Create:
text = "Hello"
other = 'World'Concatenation and repetition:
"Hello" + " " + "World"
"ha" * 3 # "hahaha"Indexing and slicing:
s = "python"
s[0] # 'p'
s[-1] # 'n'
s[1:4] # 'yth'
s[:3] # 'pyt'
s[3:] # 'hon'Basic string methods (pattern):
s.lower()
s.upper()
s.strip()
s.split(",")
",".join(["a", "b"])Input and Output
Input from user (always str):
name = input("Enter your name: ")Convert input:
age = int(input("Enter age: "))
price = float(input("Enter price: "))Printing:
print("Hello")
print("Name:", name, "Age:", age)
print(f"Name: {name}, Age: {age}")
print("a", "b", sep="-", end="!\n")if / elif / else
Basic structure:
if condition:
# block
...
elif other_condition:
...
else:
...Example:
age = 18
if age < 18:
print("Minor")
elif age == 18:
print("Just adult")
else:
print("Adult")One‑line conditional expression:
status = "adult" if age >= 18 else "minor"while Loops
Structure:
while condition:
# repeated block
...Example with counter:
count = 0
while count < 5:
print(count)
count += 1for Loops
Loop over a sequence:
for char in "abc":
print(char)
for item in [1, 2, 3]:
print(item)Ranges:
range(stop) # 0 .. stop-1
range(start, stop)
range(start, stop, step)
for i in range(5): # 0..4
print(i)
for i in range(1, 6, 2): # 1,3,5
print(i)break and continue
for i in range(10):
if i == 5:
break # exit loop
if i % 2 == 0:
continue # skip to next iteration
print(i)Lists
Create:
numbers = [1, 2, 3]
mixed = [1, "a", True]
empty = []Index and slice:
numbers[0] # first
numbers[-1] # last
numbers[1:3] # sliceModify:
numbers.append(4)
numbers.insert(1, 10)
numbers.remove(2)
popped = numbers.pop() # last elementIterate:
for n in numbers:
print(n)Check membership:
if 3 in numbers:
print("found")Tuples
Create (immutable sequences):
coords = (10, 20)
single = (5,) # note commaIndex:
coords[0]Tuple unpacking:
x, y = coordsDictionaries
Create:
person = {
"name": "Alice",
"age": 30
}Access and modify:
person["name"]
person["age"] = 31
person["city"] = "Paris"Safe get:
person.get("country", "Unknown")Iterate:
for key in person:
print(key, person[key])
for key, value in person.items():
print(key, value)Sets
Create:
items = {1, 2, 3}
empty_set = set()Basic operations:
items.add(4)
items.remove(2)
3 in items # membership
a = {1, 2, 3}
b = {3, 4}
a | b # union
a & b # intersection
a - b # differenceFunctions
Define and call:
def greet(name):
print("Hello", name)
greet("Alice")Return values:
def add(a, b):
return a + b
result = add(2, 3)Default parameters:
def power(base, exp=2):
return base ** exp
power(3) # 9
power(3, 3) # 27Imports and Modules
Basic import:
import math
x = math.sqrt(16)Import specific names:
from math import sqrt, pi
r = sqrt(9)Alias:
import numpy as npWorking with Files (Text)
Basic pattern:
with open("data.txt", "r", encoding="utf-8") as f:
text = f.read()
with open("out.txt", "w", encoding="utf-8") as f:
f.write("Hello\n")
Common modes: "r" (read), "w" (write, overwrite), "a" (append).
Exceptions (try / except)
Basic structure:
try:
x = int(input("Enter number: "))
except ValueError:
print("Not a valid integer")Multiple excepts and finally:
try:
with open("file.txt") as f:
data = f.read()
except FileNotFoundError:
print("File not found")
except PermissionError:
print("No permission")
finally:
print("Done")Raise an exception:
raise ValueError("Invalid value")Simple Classes (OOP Syntax)
Define a class:
class Person:
def __init__(self, name, age):
self.name = name # attribute
self.age = age
def greet(self):
print(f"Hi, I'm {self.name}")
p = Person("Alice", 30)
p.greet()Inheritance:
class Employee(Person):
def __init__(self, name, age, role):
super().__init__(name, age)
self.role = roleCommon Built‑in Functions (Syntax Shape)
Some useful built‑ins (names only, detailed meaning in other chapters):
len(obj)print(...)input(prompt)int(x),float(x),str(x),bool(x)list(iterable),tuple(iterable),set(iterable),dict(...)sum(iterable)min(iterable),max(iterable)sorted(iterable)range(...)enumerate(iterable)zip(iter1, iter2, ...)
Example patterns:
for index, value in enumerate(["a", "b"]):
print(index, value)
for a, b in zip([1, 2], [3, 4]):
print(a, b)Basic Boolean and None Checks
if value is None:
...
if value: # truthy check
...
else:
...List Comprehensions (Syntax Form)
squares = [x * x for x in range(5)]
evens = [x for x in range(10) if x % 2 == 0]Quick Style Reminders (Syntax‑Related)
- Indentation: 4 spaces, no tabs mixed with spaces.
- Block headers end with
::if,elif,else,for,while,def,class,try,except,finally,with. - Strings: prefer quotes in pairs
"..."or'...'. - Variable and function names:
lowercase_with_underscores.