Syntax: variable_name = value
Variables store data and are used to reference values in your program.
x = 10 # Integer assignment
name = "Alice" # String assignment
is_active = True # Boolean assignment
print(x, name, is_active) # Output: 10 Alice True
Syntax: int
, float
, str
, bool
, None
Data types represent the type of data a variable can hold.
x = 10 # int
y = 3.14 # float
name = "Alice" # str
is_active = True # bool
result = None # NoneType
print(type(x), type(y), type(name), type(is_active), type(result)) # Output:
Syntax: int(value)
, float(value)
, str(value)
, bool(value)
Type conversion allows you to convert one data type to another.
x = "10" # String
y = int(x) # Convert string to integer
print(y, type(y)) # Output: 10
z = 3.14 # Float
w = str(z) # Convert float to string
print(w, type(w)) # Output: 3.14
a = 0 # Integer
b = bool(a) # Convert integer to boolean
print(b) # Output: False
Syntax: # single-line comment
| """ multi-line comment """
Comments are used to explain code and are ignored by the interpreter.
# This is a single-line comment
x = 10 # Assigning 10 to variable x
""" This is a multi-line comment
that spans multiple lines.
It is ignored by Python. """
print(x) # Output: 10
Syntax: print()
, input()
Basic input/output functions allow you to display information and accept user input.
# print(): Displays output to the console
print("Hello, World!") # Output: Hello, World!
# input(): Accepts user input as a string
name = input("Enter your name: ")
print("Hello, " + name) # Output: Hello,
Syntax: variable_name = value
Variables store values that can be used later. Python is dynamically typed, so you don’t need to declare the type.
# Assign a number to a variable
x = 10
# Print the variable value
print(x)
Syntax: +, -, *, /, %, **, //
Used for basic mathematical operations like addition, subtraction, etc.
a = 10
b = 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a % b) # Modulus (remainder)
print(a ** b) # Exponentiation (power)
print(a // b) # Floor division
Syntax: ==, !=, >, <, >=, <=
Compare values and return True
or False
.
a = 5
b = 3
print(a == b) # Equal to
print(a != b) # Not equal to
print(a > b) # Greater than
print(a < b) # Less than
print(a >= b) # Greater than or equal to
print(a <= b) # Less than or equal to
Syntax: and, or, not
Used to combine conditional statements.
x = True
y = False
print(x and y) # Returns True if both are True
print(x or y) # Returns True if at least one is True
print(not x) # Reverses the result
Syntax: =, +=, -=, *=, /=, %=, //=, **=
Used to assign and update values of variables.
a = 5
a += 2 # a = a + 2
print(a)
a *= 3 # a = a * 3
print(a)
a -= 1 # a = a - 1
print(a)
Syntax: &, |, ^, ~, <<, >>
Operate on binary representations of integers.
a = 5 # 0101 in binary
b = 3 # 0011 in binary
print(a & b) # Bitwise AND => 0001 => 1
print(a | b) # Bitwise OR => 0111 => 7
print(a ^ b) # Bitwise XOR => 0110 => 6
print(~a) # Bitwise NOT => flips all bits => -6
print(a << 1) # Left shift => 1010 => 10
print(a >> 1) # Right shift => 0010 => 2
Syntax: is, is not
Check whether two variables refer to the same object in memory.
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True, same object
print(a is c) # False, same content but different objects
print(a is not c) # True
Syntax: in, not in
Check for presence of a value in a sequence (like list, string, etc.).
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("orange" not in fruits) # True
Syntax: type(value)
Python supports various data types like integers, floats, strings, booleans, etc.
a = 5
b = 3.14
c = "Python"
d = True
print(type(a))
print(type(b))
print(type(c))
print(type(d))
Syntax: if condition: ... elif condition: ... else: ...
Conditional statements let you execute code based on logical conditions.
x = 20
if x > 10:
print("Greater than 10")
elif x == 10:
print("Equal to 10")
else:
print("Less than 10")
Syntax: if condition: ...
| elif condition: ...
| else: ...
Conditional statements allow you to execute blocks of code based on specific conditions.
x = 10
if x > 5:
print("x is greater than 5") # Output: x is greater than 5
if x < 5:
print("x is less than 5")
else:
print("x is 5 or greater") # Output: x is 5 or greater
if x == 10:
print("x is 10") # Output: x is 10
elif x == 5:
print("x is 5")
else:
print("x is neither 10 nor 5")
Syntax: for item in iterable: ...
| while condition: ...
Loops allow you to execute a block of code multiple times.
# For Loop (iterates over a sequence like a list)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit) # Output: apple, banana, cherry
# While Loop (runs as long as the condition is True)
count = 0
while count < 3:
print(count) # Output: 0, 1, 2
count += 1
Syntax: break
| continue
| pass
Loop control statements alter the behavior of loops.
# break: Exits the loop completely
for i in range(5):
if i == 3:
break # Exits the loop when i equals 3
print(i) # Output: 0, 1, 2
# continue: Skips the current iteration and moves to the next
for i in range(5):
if i == 3:
continue # Skips printing 3
print(i) # Output: 0, 1, 2, 4
# pass: Placeholder that does nothing (useful as a placeholder in empty functions or loops)
for i in range(3):
if i == 2:
pass # Does nothing, but can be used to add functionality later
print(i) # Output: 0, 1, 2
Syntax: while condition:
The while
loop repeats as long as the condition is True
.
count = 0
while count < 3:
print("Counting:", count)
count += 1
Syntax: filter(function, iterable)
Filters elements from iterable based on condition.
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
Syntax: def function_name(parameters):
Functions are defined using the def
keyword followed by the function name and parameters. The body of the function is indented.
def greet(name):
print(f"Hello, {name}")
greet("Alice")
Syntax: def function(arg1, arg2, ...)
Functions can take various types of arguments: positional, keyword, default, and variable-length arguments using *args
and **kwargs
.
# Positional Arguments
def greet(name, age):
print(f"Name: {name}, Age: {age}")
greet("Alice", 30)
# Keyword Arguments
def greet(name, age):
print(f"Name: {name}, Age: {age}")
greet(age=30, name="Alice")
# Default Arguments
def greet(name, age=30):
print(f"Name: {name}, Age: {age}")
greet("Alice") # Default age used
# *args
def greet(*args):
for arg in args:
print(arg)
greet("Alice", "Bob", "Charlie")
# **kwargs
def greet(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
greet(name="Alice", age=30)
Syntax: return value
The return
statement is used to send back a result from a function.
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Syntax: lambda arguments: expression
A lambda function is a small anonymous function defined using the lambda
keyword. It's often used for short operations.
add = lambda a, b: a + b
print(add(5, 3))
square = lambda x: x * x
print(square(4))
Syntax: global
, local
, nonlocal
In Python, variables can have different scopes: local, global, and nonlocal. global
refers to variables outside any function, local
is within a function, and nonlocal
refers to variables in the nearest enclosing scope (not global).
x = 10 # Global variable
def local_example():
x = 5 # Local variable
print(x)
def global_example():
global x
x = 15
def nonlocal_example():
x = 5
def inner():
nonlocal x
x = 10
inner()
print(x)
local_example() # Output: 5
global_example() # Changes global x
print(x) # Output: 15
nonlocal_example() # Output: 10
Syntax: def function_name(parameters):
Functions group reusable code. You define them using def
.
def greet(name):
# Print a personalized greeting
print("Hello, " + name + "!")
greet("Alice")
Syntax: lambda arguments: expression
Anonymous function useful for short operations.
add = lambda x, y: x + y
print(add(3, 4))
Syntax: map(function, iterable)
Applies a function to every item in an iterable.
numbers = [1, 2, 3]
result = list(map(lambda x: x*2, numbers))
print(result)
Syntax: list = [element1, element2, ...]
| list = list()
A list is an ordered collection of elements. Lists are mutable (can be changed).
my_list = [1, 2, 3, 4]
print(my_list) # Output: [1, 2, 3, 4]
my_list.append(5) # Add element to the end
print(my_list) # Output: [1, 2, 3, 4, 5]
my_list[0] = 10 # Modify element
print(my_list) # Output: [10, 2, 3, 4, 5]
Syntax: tuple = (element1, element2, ...)
| tuple = tuple()
A tuple is similar to a list, but it is immutable (cannot be changed after creation).
my_tuple = (1, 2, 3, 4)
print(my_tuple) # Output: (1, 2, 3, 4)
# Tuples are immutable, so the following will raise an error:
# my_tuple[0] = 10 # TypeError: 'tuple' object does not support item assignment
Syntax: set = {element1, element2, ...}
| set = set()
A set is an unordered collection of unique elements. It cannot contain duplicate values.
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}
my_set.add(5) # Add element
print(my_set) # Output: {1, 2, 3, 4, 5}
my_set.add(3) # Duplicate value will be ignored
print(my_set) # Output: {1, 2, 3, 4, 5}
Syntax: dict = {'key1': 'value1', 'key2': 'value2', ...}
| dict = dict()
A dictionary is an unordered collection of key-value pairs. Keys are unique.
my_dict = {'name': 'Alice', 'age': 30}
print(my_dict) # Output: {'name': 'Alice', 'age': 30}
my_dict['age'] = 31 # Modify value
print(my_dict) # Output: {'name': 'Alice', 'age': 31}
my_dict['city'] = 'New York' # Add new key-value pair
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York'}
Syntax: str = "string"
| str = str()
A string is a sequence of characters enclosed in quotes. Strings are immutable.
my_string = "Hello, World!"
print(my_string) # Output: Hello, World!
# String concatenation
new_string = "Hello, " + "Alice!"
print(new_string) # Output: Hello, Alice!
# String slicing
print(my_string[0:5]) # Output: Hello
print(my_string[-6:]) # Output: World!
Syntax: list[start:stop:step]
Extract a portion of a list using slice notation.
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:5:2])
Comprehensions are concise ways to build new collections.
Syntax: [expression for item in iterable]
Syntax: [x for x in iterable]
Creates a new list by applying an expression to each item in an iterable.
squares = [x*x for x in range(5)]
print(squares)
# List
squares = [x*x for x in range(3)]
print(squares)
# Dict
squared_dict = {x: x*x for x in range(2)}
print(squared_dict)
# Set
unique = {x % 2 for x in [1, 2, 3, 4]}
print(unique)
Syntax: my_dict = {"key": "value"}
Dictionaries store key-value pairs. Keys must be unique.
person = {"name": "Bob", "age": 25}
print(person["name"]) # Access value by key
Syntax: class ClassName: ...
Classes are blueprints for creating objects. They group data and behavior.
Classes define the structure and behavior (methods) for objects. The self
keyword refers to the instance itself.
class Person:
def greet(self):
print("Hello!")
p = Person() # Create an object of the class
p.greet() # Call the method
Syntax: def __init__(self, ...):
The __init__
method is called automatically when an object is created. It is used to initialize attributes.
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello, " + self.name)
p = Person("Alice")
p.greet()
Syntax: class Child(Parent):
Inheritance allows a class to derive attributes and methods from another class. Use super()
to access the parent class.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
super().speak() # Call parent method
print("Dog barks")
d = Dog()
d.speak()
Syntax: self.var, self._var, self.__var
Python doesn't enforce strict access restrictions, but by convention:
self.var
is publicself._var
is protectedself.__var
is private
class Car:
def __init__(self):
self.brand = "Toyota" # Public
self._engine = "V6" # Protected
self.__secret_code = "1234" # Private
car = Car()
print(car.brand) # Accessible
print(car._engine) # Accessible but discouraged
print(car._Car__secret_code) # Name mangled access to private
Syntax: Use same method name in different classes
Polymorphism allows different classes to use methods with the same name, enabling interchangeable code.
class Bird:
def sound(self):
print("Chirp")
class Cat:
def sound(self):
print("Meow")
for animal in [Bird(), Cat()]:
animal.sound()
Syntax: __str__, __len__, __add__, etc.
Magic methods let you define how objects behave with built-in functions or operators.
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book title: {self.title}"
b = Book("Python 101")
print(str(b))
Syntax: try: ... except: ... else: ... finally: ...
This block handles errors gracefully. try
runs the code. except
catches errors. else
runs if no error occurs. finally
always runs (cleanup code).
try:
x = 10 / 2 # No error here
except ZeroDivisionError:
print("Division by zero!")
else:
print("Division successful")
finally:
print("Finished block")
Syntax: raise ExceptionType("message")
The raise
statement allows you to trigger exceptions manually when invalid input or state is detected.
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
print(f"Age is {age}")
set_age(25)
# set_age(-5) # Uncomment to see exception
Common types: ValueError
, TypeError
, IndexError
, ZeroDivisionError
, etc.
These are standard exceptions raised when something goes wrong. Catch them individually or as a group.
try:
numbers = [1, 2, 3]
print(numbers[5]) # IndexError
except IndexError:
print("Invalid index!")
try:
int("abc") # ValueError
except ValueError:
print("Cannot convert to int!")
try:
5 + "string" # TypeError
except TypeError:
print("Type mismatch!")
Syntax: x if condition else y
Shorthand for if-else in a single line.
age = 18
result = "Adult" if age >= 18 else "Minor"
print(result)
Syntax: enumerate(iterable)
Returns index and value while looping through an iterable.
for index, value in enumerate(["a", "b", "c"]):
print(index, value)
Syntax: @decorator_name
Decorators wrap a function to modify or enhance its behavior.
def my_decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@my_decorator
def greet():
print("Hello")
greet()
Syntax: yield value
Generators yield values lazily one at a time without storing them all in memory.
Generators produce items one at a time using yield
. They're memory-efficient for large sequences.
def gen():
yield 1
yield 2
yield 3
for i in gen():
print(i)
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for number in count_up_to(3):
print(number)
Syntax: import module_name
| from module_name import function_name
You can import an entire module or specific functions/variables from a module.
import math
print(math.sqrt(16)) # Use full module name
from math import sqrt
print(sqrt(16)) # Directly use function without module name
Syntax: Create a Python file (e.g., module_name.py
) and use import module_name
A module is simply a Python file with functions, classes, or variables. You can create and import your custom modules.
# In mymodule.py
def greet(name):
print(f"Hello, {name}")
# In main.py
import mymodule
mymodule.greet("Alice")
Syntax: __init__.py
A package is a collection of modules. The __init__.py
file makes a directory a package and is often empty, or it may execute package-level code.
# Directory structure:
# mypackage/
# __init__.py
# module1.py
# In __init__.py (empty or with initialization code)
# In module1.py
def hello():
print("Hello from module1")
# In main.py
import mypackage.module1
mypackage.module1.hello()
Syntax: import module_name
Python has a rich standard library with modules like math
, os
, sys
, datetime
, etc.
import math
print(math.pi) # Math library
import os
print(os.getcwd()) # OS library: Get current working directory
import sys
print(sys.version) # Python version
from datetime import datetime
print(datetime.now()) # Get current datetime
Syntax: open(filename, mode)
The open()
function is used to open a file. It returns a file object. You must specify the file name and mode (like read, write).
file = open("example.txt", "r")
print(file)
file.close()
Syntax: "r"
= read, "w"
= write, "a"
= append, "r+"
= read/write, "b"
= binary mode
Use file modes to determine the operation: "w"
overwrites, "a"
appends, "r"
reads, "r+"
updates.
open("file.txt", "r") # Read mode
open("file.txt", "w") # Write mode
open("file.txt", "a") # Append mode
open("file.txt", "r+") # Read & Write
open("file.txt", "rb") # Binary read mode
Functions: read()
, readline()
, readlines()
read()
gets all content. readline()
reads one line. readlines()
gives a list of all lines.
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Functions: write()
, writelines()
write()
writes strings. writelines()
takes a list of strings.
file = open("example.txt", "w")
file.write("Hello World\n")
file.writelines(["Line 1\n", "Line 2\n"])
file.close()
Syntax: file.close()
Always close files after use to free system resources.
file = open("example.txt", "r")
data = file.read()
file.close()
Syntax: with open(...) as file:
with
automatically closes the file. It's the safest and cleanest way to handle files.
with open("example.txt", "r") as file:
print(file.read())
Syntax: multiprocessing.Process(target=...)
Multiprocessing allows parallel execution using separate memory space for each process.
import multiprocessing
def worker():
print("Process running")
p = multiprocessing.Process(target=worker)
p.start()
p.join()
Syntax: threading.Thread(target=...)
Multithreading runs multiple tasks concurrently in the same process space.
import threading
def show():
print("Thread running")
t = threading.Thread(target=show)
t.start()
t.join()
Syntax: Functions inside functions retaining access to enclosing variables.
A closure is a nested function that remembers values from its enclosing scope.
def outer(msg):
def inner():
print("Message:", msg)
return inner
greet = outer("Hello Closure")
greet()
Syntax: iter(obj)
and next(iterator)
An iterator allows iteration over elements using next()
and is created using iter()
.
numbers = [1, 2, 3]
it = iter(numbers) # Create iterator
print(next(it))
print(next(it))
print(next(it))
Syntax: re.search(), re.match(), re.findall()
Regular expressions are used to match string patterns using the re
module.
import re
pattern = r"\d+" # Matches one or more digits
result = re.findall(pattern, "The year is 2025 and the month is 04")
print(result)
Syntax: json.loads(json_string)
, json.dumps(dict_obj)
The json
module handles JSON serialization and deserialization.
import json
data = '{"name": "Alice", "age": 30}' # JSON string
python_obj = json.loads(data) # Convert to Python dict
print(python_obj["name"])
# Convert back to JSON string
json_str = json.dumps(python_obj)
print(json_str)
Syntax: csv.reader(file)
, csv.writer(file)
The csv
module is used to read and write CSV files.
import csv
# Writing to a CSV file
with open("sample.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", "30"])
# Reading the CSV file
with open("sample.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Syntax: import numpy as np
, import pandas as pd
NumPy
is used for numerical arrays and math operations. Pandas
is used for data manipulation with DataFrames.
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)
import pandas as pd
data = {"Name": ["Alice", "Bob"], "Age": [30, 25]}
df = pd.DataFrame(data)
print(df)
Syntax: requests.get(), requests.post()
The requests
library allows you to send HTTP/HTTPS requests easily.
import requests
response = requests.get("https://api.github.com") # Send a GET request
print(response.status_code) # Print HTTP status code
print(response.json()) # Print JSON content if any
Syntax: BeautifulSoup(html, 'html.parser')
BeautifulSoup
from bs4
is used to extract data from HTML pages.
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
title = soup.title.text # Get the page title
print(title)
Syntax: class MySpider(scrapy.Spider)
Scrapy
is a powerful web crawling framework. You define spiders as classes.
import scrapy
class MySpider(scrapy.Spider):
name = "example"
start_urls = ['https://example.com']
def parse(self, response):
title = response.xpath('//title/text()').get()
print(title)
Syntax: @app.route("/")
, Flask(__name__)
Flask
is a lightweight framework for building web applications quickly.
from flask import Flask
app = Flask(__name__)
@app.route("/") # Define route for the home page
def home():
return "Hello, Flask!"
if __name__ == "__main__":
app.run(debug=True)
Syntax: django-admin startproject
, def view(request)
Django
is a high-level framework for building secure and scalable web apps with ORM, admin, templates, and more.
# In terminal:
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
# In myapp/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
# In myproject/urls.py
from django.urls import path
from myapp.views import home
urlpatterns = [
path("", home),
]
Syntax: import pdb; pdb.set_trace()
or breakpoint()
Use the built-in pdb
module or breakpoint()
function to pause execution and inspect variables step by step.
def add(a, b):
breakpoint() # Pause execution here
return a + b
result = add(2, 3)
print(result)
Syntax: import unittest
, class TestName(unittest.TestCase)
unittest
is the built-in Python module for writing test cases to verify code functionality.
import unittest
def add(x, y):
return x + y
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
Syntax: def test_func(): assert ...
pytest
is a third-party framework used for writing simple and scalable test cases using assert statements.
def multiply(x, y):
return x * y
def test_multiply():
assert multiply(2, 3) == 6
Syntax: logging.debug(), logging.info(), logging.warning()
The logging
module provides a flexible way to report messages during development and production.
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("Debugging info") # For development debug
logging.info("Informational message") # General app status
logging.warning("Warning message") # Indicate something unexpected
logging.error("Error message") # Report an error
Syntax: python -m venv env_name
| source env_name/bin/activate
| pip install package
Use venv
to create isolated Python environments for separate projects, preventing package conflicts.
# Create a virtual environment
python -m venv myenv
# Activate the virtual environment (Linux/Mac)
source myenv/bin/activate
# On Windows
myenv\Scripts\activate
# Install packages inside the environment
pip install requests
Syntax: Use triple quotes to document functions/classes, and access using help()
or .__doc__
Docstrings describe what your function/class/module does. They help others understand your code.
def greet(name):
"""
This function greets the person passed in as a parameter.
"""
print(f"Hello, {name}!")
help(greet)
print(greet.__doc__)
Syntax: def func(arg: type) -> return_type
Type hints (annotations) help indicate what types of arguments and return values a function expects. They're useful for IDEs and type checkers like mypy.
def add(x: int, y: int) -> int:
return x + y
print(add(3, 5))