🐍 Python A to Z: Basics Reference Note
A — Assignment & Variables
Variables hold data values. You don't need to specify types manually.
x = 10 # Integer
name = "Dev" # String
pi = 3.14 # Float
is_ready = True # Boolean
B — Basic Arithmetic Operators
Standard math operations built into Python:
add = 10 + 5 # 15
subtract = 10 - 5 # 5
multiply = 10 * 5 # 50
divide = 10 / 3 # 3.3333...
floor_div = 10 // 3# 3 (integer division)
power = 2 ** 3 # 8 (2 cubed)
modulus = 10 % 3 # 1 (remainder)
C — Comments
Lines ignored by the interpreter—used to explain code.
# This is a single-line comment
"""
This is a multi-line comment
or docstring.
"""
D — Data Types & Conversion (Casting)
Checking and converting between types:
num_str = "100"
num_int = int(num_str) # Convert String to Integer
num_float = float(num_int) # Convert Integer to Float
text = str(250) # Convert Integer to String
print(type(num_int)) # <class 'int'>
E — Else & Conditional Logic (if / elif / else)
Controlling execution based on conditions:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
else:
print("Grade: C")
F — For Loops
Iterating over sequence collections or ranges:
# Loop numbers 0 to 4
for i in range(5):
print(i)
# Loop through list items
items = ["laptop", "mouse", "keyboard"]
for item in items:
print(item)
G — Getting User Input
Reading input directly from the user in the console:
user_name = input("Enter your name: ")
age = int(input("Enter your age: ")) # input() always returns a string
H — Hello World & Printing
Outputting text and formatting strings:
print("Hello, World!")
# String Formatting (f-strings)
age = 22
print(f"I am {age} years old.")
I — Indentation
Python uses whitespace (usually 4 spaces) instead of curly braces {} to define blocks of code:
if True:
print("Indented line") # Correct
# print("Wrong") # SyntaxError if indented incorrectly!
J — Joining Strings
Concatenating strings together:
first = "Python"
second = "Basics"
full = first + " " + second # Using '+'
joined = "-".join(["A", "B", "C"]) # "A-B-C"
K — Keys in Dictionaries
Accessing and manipulating dictionary keys:
student = {"name": "Kamal", "age": 20, "city": "Colombo"}
print(student.keys()) # dict_keys(['name', 'age', 'city'])
print(student.get("age")) # 20
L — Lists
Ordered, mutable (changeable) collections:
numbers = [10, 20, 30, 40]
numbers.append(50) # Add to end
numbers.remove(20) # Remove item
print(numbers[0]) # Access first item (10)
M — Methods for Strings
Common built-in string functions:
text = " python code "
print(text.upper()) # " PYTHON CODE "
print(text.strip()) # "python code" (removes outer spaces)
print(text.replace("code", "notes")) # " python notes "
N — None Keyword
Represents the absence of a value (null value in other languages):
result = None
if result is None:
print("No result calculated yet.")
O — Logical Operators
Combining multiple conditions using and, or, and not:
age = 20
has_license = True
if age >= 18 and has_license:
print("Allowed to drive")
P — Parameter & Arguments in Functions
Creating reusable blocks of code:
# 'a' and 'b' are parameters
def add_two(a, b):
return a + b
# 5 and 10 are arguments
sum_result = add_two(5, 10) # 15
Q — Quick Scope Rules (Local vs Global)
Variables inside functions are local, while outside ones are global:
glob_var = "I am global"
def test_scope():
loc_var = "I am local"
print(glob_var) # Accessible
test_scope()
# print(loc_var) # Error! Cannot access outside function
R — Return Statement
Exiting a function and returning a value:
def multiply(x, y):
return x * y
ans = multiply(4, 3) # ans is assigned 12
S — Sets & Tuples
Tuple: Ordered, immutable (cannot be changed).
()Set: Unordered, contains only unique values.
{}
# Tuple
point = (10, 20)
# Set
unique_nums = {1, 2, 2, 3, 3} # Becomes {1, 2, 3}
T — Truthiness & Falsiness
Values evaluated in conditional checks:
Falsy values:
0,""(empty string),[](empty list),None,FalseTruthy values: Everything else
items = []
if not items:
print("The list is empty!")
U — Unpacking Sequences
Extracting elements into variables directly:
coordinates = (100, 200)
x, y = coordinates # x = 100, y = 200
a, b, *rest = [1, 2, 3, 4, 5] # a=1, b=2, rest=[3, 4, 5]
V — Value Errors & Catching Them
Handling basic runtime mistakes using try...except:
try:
num = int("abc") # Raises ValueError
except ValueError:
print("Could not convert text to a number!")
W — While Loops
Executing code repeatedly as long as a condition is True:
count = 1
while count <= 3:
print(f"Count: {count}")
count += 1
X — Exit Loops (break & continue)
Controlling loop iteration flow:
for num in range(5):
if num == 2:
continue # Skip 2
if num == 4:
break # Stop loop at 4
print(num) # Prints 0, 1, 3
Y — Yielding Lists via Ranges
Creating sequences quickly using range():
numbers_list = list(range(1, 6)) # [1, 2, 3, 4, 5]
even_nums = list(range(2, 11, 2)) # [2, 4, 6, 8, 10]
Z — Zip Function
Pairing elements from multiple lists together:
names = ["Alice", "Bob"]
ages = [22, 25]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")