0% found this document useful (0 votes)
21 views18 pages

Python Reference Guide

This document is a comprehensive reference guide for Python programming, covering essential topics such as data types, control flow, functions, object-oriented programming, file handling, and common libraries. It includes detailed explanations of various operations, syntax, and best practices. The guide also provides examples for better understanding and practical application of Python concepts.

Uploaded by

yohifim560
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views18 pages

Python Reference Guide

This document is a comprehensive reference guide for Python programming, covering essential topics such as data types, control flow, functions, object-oriented programming, file handling, and common libraries. It includes detailed explanations of various operations, syntax, and best practices. The guide also provides examples for better understanding and practical application of Python concepts.

Uploaded by

yohifim560
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Quick Reference Guide

A comprehensive reference for Python programming covering data types, control flow, functions,
object-oriented programming, file handling, and common libraries.

1. Data Types and Variables


Type Example Description Methods

int 42 Integer numbers bit_length(), to_bytes()

float 3.14 Decimal numbers is_integer(), as_integer_ratio()

str "Hello" Text strings upper(), lower(), split(), join()

bool True/False Boolean values No specific methods

list [1, 2, 3] Ordered, mutable append(), extend(), pop(), sort()

tuple (1, 2, 3) Ordered, immutable count(), index()

dict {'key': 'value'} Key-value pairs keys(), values(), items(), get()

set {1, 2, 3} Unordered unique add(), remove(), union(), intersection()

String Operations
Concatenation: 'Hello' + ' ' + 'World' → 'Hello World'
Repetition: 'Ha' * 3 → 'HaHaHa'
Slicing: text[0:5] → first 5 characters
Formatting: f'Hello {name}' or 'Hello {}'.format(name)
Methods: upper(), lower(), strip(), replace(), split(), join()
Check: 'sub' in 'substring' → True

List Operations
Create: my_list = [1, 2, 3] or list(range(10))
Append: my_list.append(4) → [1, 2, 3, 4]
Extend: my_list.extend([5, 6]) → [1, 2, 3, 4, 5, 6]
Insert: my_list.insert(0, 0) → [0, 1, 2, 3, 4, 5, 6]
Remove: my_list.remove(0) or my_list.pop() or del my_list[0]
Sort: my_list.sort() or sorted(my_list)
Reverse: my_list.reverse() or my_list[::-1]
Comprehension: [x**2 for x in range(10)] → [0, 1, 4, 9, 16, ...]
2. Control Flow

If-Elif-Else Statements
if condition1:
# Execute if condition1 is True
print("Condition 1")
elif condition2:
# Execute if condition1 is False and condition2 is True
print("Condition 2")
else:
# Execute if all conditions are False
print("Default")

Comparison Operators: ==, !=, <, >, <=, >=


Logical Operators: and, or, not
Ternary: result = value_if_true if condition else value_if_false

For Loops
Basic Loop:
for item in iterable:
print(item)

Range:
for i in range(10): # 0 to 9
print(i)
for i in range(5, 10): # 5 to 9
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)

Enumerate:
for index, value in enumerate(my_list):
print(f"Index {index}: {value}")

Zip:
for a, b in zip(list1, list2):
print(f"{a} and {b}")

Dictionary:
for key, value in my_dict.items():
print(f"{key}: {value}")

While Loops
Basic While:
count = 0
while count < 5:
print(count)
count += 1

Break and Continue:


while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break # Exit loop
if user_input == '':
continue # Skip to next iteration
print(f"You entered: {user_input}")
3. Functions

Defining Functions
Basic Function:
def greet(name):
return f"Hello, {name}!"

Default Parameters:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"

Variable Arguments (*args):


def sum_all(*numbers):
return sum(numbers)
result = sum_all(1, 2, 3, 4, 5) # → 15

Keyword Arguments (**kwargs):


def print_info(**info):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="NYC")

Lambda Functions:
square = lambda x: x**2
add = lambda x, y: x + y
multiply = lambda x, y, z: x * y * z

Docstrings:
def calculate_area(length, width):
# Documentation string here
return length * width

Built-in Functions
Function Description Example

len() Length of object len([1,2,3]) → 3

type() Type of object type(5) → &lt;class 'int'&gt;

str() Convert to string str(42) → '42'

int() Convert to integer int('42') → 42

float() Convert to float float('3.14') → 3.14

max() Maximum value max([1,2,3]) → 3

min() Minimum value min([1,2,3]) → 1


sum() Sum of values sum([1,2,3]) → 6

sorted() Return sorted list sorted([3,1,2]) → [1,2,3]

reversed() Reverse iterator list(reversed([1,2,3])) → [3,2,1]

enumerate() Index, value pairs list(enumerate(['a','b'])) → [(0,'a'),(1,'b')]

zip() Combine iterables list(zip([1,2],['a','b'])) → [(1,'a'),(2,'b')]

map() Apply function list(map(str,[1,2,3])) → ['1','2','3']

filter() Filter items list(filter(lambda x:x&gt;2,[1,2,3,4])) → [3,4]


4. Object-Oriented Programming

Classes and Objects


Basic Class:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def greet(self):
return f"Hi, I'm {[Link]}"

# Create object
person1 = Person("Alice", 30)
print([Link]()) # → Hi, I'm Alice

Class Variables vs Instance Variables:


class Dog:
species = "Canis familiaris" # Class variable

def __init__(self, name, breed):


[Link] = name # Instance variable
[Link] = breed # Instance variable

Inheritance:
class Animal:
def __init__(self, name):
[Link] = name

def speak(self):
pass

class Dog(Animal):
def speak(self):
return "Woof!"

class Cat(Animal):
def speak(self):
return "Meow!"

Special Methods:
class Book:
def __init__(self, title, author):
[Link] = title
[Link] = author

def __str__(self):
return f"{[Link]} by {[Link]}"
def __len__(self):
return len([Link])

book = Book("1984", "George Orwell")


print(book) # → 1984 by George Orwell
print(len(book)) # → 4
5. File Handling
Reading Files:
# Read entire file
with open('[Link]', 'r') as f:
content = [Link]()

# Read line by line


with open('[Link]', 'r') as f:
for line in f:
print([Link]())

# Read all lines into list


with open('[Link]', 'r') as f:
lines = [Link]()

Writing Files:
# Write (overwrites existing)
with open('[Link]', 'w') as f:
[Link]('Hello, World!\n')
[Link]('Second line\n')

# Append to file
with open('[Link]', 'a') as f:
[Link]('Appended line\n')

Working with CSV:


import csv

# Read CSV
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row)

# Write CSV
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](['Name', 'Age', 'City'])
[Link](['Alice', 30, 'NYC'])

Working with JSON:


import json

# Read JSON
with open('[Link]', 'r') as f:
data = [Link](f)

# Write JSON
data = {'name': 'Alice', 'age': 30}
with open('[Link]', 'w') as f:
[Link](data, f, indent=4)
File Operations:
import os

[Link]('[Link]') # Check if exists


[Link]('[Link]') # Check if file
[Link]('folder') # Check if directory
[Link]('[Link]') # Get file size
[Link]('[Link]') # Delete file
[Link]('[Link]', '[Link]') # Rename
[Link]('.') # List files in directory
6. Exception Handling
Try-Except Block:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")

Multiple Exceptions:
try:
value = int(input("Enter number: "))
result = 10 / value
except ValueError:
print("Invalid input!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Error: {e}")

Finally Block:
try:
f = open('[Link]', 'r')
content = [Link]()
except FileNotFoundError:
print("File not found!")
finally:
[Link]() # Always executes

Raising Exceptions:
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age too high")
return True

Common Exceptions:

Exception Description

ValueError Invalid value for operation

TypeError Wrong type for operation

KeyError Key not found in dictionary

IndexError Index out of range

FileNotFoundError File doesn't exist

ZeroDivisionError Division by zero

AttributeError Attribute doesn't exist

ImportError Module not found


IOError Input/output error
7. Modules and Packages
Importing Modules:
import math
print([Link]) # → 3.14159...

from math import sqrt, pi


print(sqrt(16)) # → 4.0

import math as m
print([Link](4.2)) # → 5

from math import * # Import all (not recommended)

Creating Your Own Module:


# [Link]
def greet(name):
return f"Hello, {name}"

PI = 3.14159

# [Link]
import mymodule
print([Link]("Alice"))
print([Link])

Standard Library Modules:

Module Purpose Key Functions

os Operating system listdir(), mkdir(), remove()

sys System-specific argv, exit(), path

datetime Date and time [Link](), timedelta()

random Random numbers random(), randint(), choice()

math Mathematical sqrt(), sin(), cos(), pi

json JSON handling load(), dump(), loads(), dumps()

re Regular expressions search(), match(), findall()

pathlib File paths Path(), exists(), mkdir()

collections Data structures Counter, defaultdict, deque

itertools Iterators cycle(), combinations(), permutations()


8. Comprehensions and Generators
List Comprehensions:
# Basic
squares = [x**2 for x in range(10)]
# → [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# → [0, 4, 16, 36, 64]

# Nested
matrix = [[i*j for j in range(3)] for i in range(3)]
# → [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

Dictionary Comprehensions:
squares_dict = {x: x**2 for x in range(5)}
# → {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# From two lists


keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = {k: v for k, v in zip(keys, values)}
# → {'a': 1, 'b': 2, 'c': 3}

Set Comprehensions:
unique_squares = {x**2 for x in [1, 1, 2, 2, 3, 3]}
# → {1, 4, 9}

Generator Expressions:
# Similar to list comprehension but uses () instead of []
gen = (x**2 for x in range(1000000))
# Memory efficient - values generated on demand

Generator Functions:
def countdown(n):
while n > 0:
yield n
n -= 1

for i in countdown(5):
print(i) # → 5, 4, 3, 2, 1

def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

# Get first 10 Fibonacci numbers


fib = fibonacci()
numbers = [next(fib) for _ in range(10)]
# → [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
9. Decorators and Context Managers
Function Decorators:
def timer(func):
import time
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
end = [Link]()
print(f"Took {end-start:.2f}s")
return result
return wrapper

@timer
def slow_function():
import time
[Link](2)

slow_function() # Prints: Took 2.00s

Class Decorators:
def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance

@singleton
class Database:
pass

Context Managers:
# Built-in
with open('[Link]', 'r') as f:
content = [Link]()
# File automatically closed

# Custom context manager


class FileManager:
def __init__(self, filename, mode):
[Link] = filename
[Link] = mode

def __enter__(self):
[Link] = open([Link], [Link])
return [Link]

def __exit__(self, exc_type, exc_val, exc_tb):


[Link]()
with FileManager('[Link]', 'r') as f:
content = [Link]()

# Using contextlib
from contextlib import contextmanager

@contextmanager
def timer():
import time
start = [Link]()
yield
end = [Link]()
print(f"Elapsed: {end-start:.2f}s")

with timer():
# Your code here
pass
10. Best Practices and Tips

Code Style (PEP 8)


• Use 4 spaces for indentation (not tabs)
• Maximum line length: 79 characters
• Use blank lines to separate functions and classes
• Use snake_case for functions and variables
• Use PascalCase for class names
• Use UPPER_CASE for constants
• Add docstrings to all functions, classes, and modules

Performance Tips
• Use list comprehensions instead of loops when possible
• Use generators for large datasets
• Use sets for membership testing (x in set vs x in list)
• Use [Link]() instead of dict[key] to avoid KeyError
• Use 'is' for None comparisons: if x is None
• Use enumerate() instead of range(len())
• Use zip() to iterate over multiple lists
• Use join() for string concatenation: ''.join(list)

Common Pitfalls
Mutable Default Arguments:
# BAD
def append_to(element, list=[]):
[Link](element)
return list

# GOOD
def append_to(element, list=None):
if list is None:
list = []
[Link](element)
return list

Modifying List While Iterating:


# BAD
for item in my_list:
if condition:
my_list.remove(item)

# GOOD
my_list = [item for item in my_list if not condition]

Using == for None:


# BAD: if x == None
# GOOD: if x is None

Useful Resources
• Python Official Documentation: [Link]
• PEP 8 Style Guide: [Link]
• Real Python Tutorials: [Link]
• Python Package Index (PyPI): [Link]
• Stack Overflow: [Link]/questions/tagged/python

You might also like