Python Quick Reference

Concise guide to Python with practical examples

Python Quick Reference

Python is a versatile, easy-to-learn programming language used for web development, data science, automation, and more.

Installation

python --version
pip install package-name

Variables and Data Types

name = "Alice"        # str
age = 30              # int
price = 19.99         # float
is_active = True      # bool
fruits = ["apple", "banana"]  # list
person = {"name": "Bob", "age": 25}  # dict

Control Structures

if age >= 18:
	print("Adult")
else:
	print("Minor")

for fruit in fruits:
	print(fruit)

i = 0
while i < 3:
	print(i)
	i += 1

Functions

def greet(name):
	return f"Hello, {name}!"

def add(a, b=0):
	return a + b

def sum_all(*args):
	return sum(args)

def show_info(**kwargs):
	for key, value in kwargs.items():
		print(f"{key}: {value}")

List Comprehensions

numbers = [1, 2, 3, 4]
squares = [x**2 for x in numbers]  # [1, 4, 9, 16]
evens = [x for x in numbers if x % 2 == 0]  # [2, 4]

Dictionaries

person = {"name": "Alice", "age": 30}
print(person["name"])
person["email"] = "alice@example.com"
for key, value in person.items():
	print(key, value)

Classes

class Person:
	def __init__(self, name, age):
		self.name = name
		self.age = age

	def introduce(self):
		return f"My name is {self.name}."

class Employee(Person):
	def __init__(self, name, age, position):
		super().__init__(name, age)
		self.position = position

	def introduce(self):
		return f"{super().introduce()} I am a {self.position}."

File Handling

with open("file.txt", "w") as f:
	f.write("Hello, file!\n")

with open("file.txt", "r") as f:
	content = f.read()

Error Handling

try:
	result = 10 / 0
except ZeroDivisionError:
	print("Cannot divide by zero!")
finally:
	print("Done.")
  • requests for HTTP requests
  • pandas for data analysis
  • numpy for numerical computing
import requests
response = requests.get("https://api.github.com")
print(response.status_code)

Best Practices

  1. Follow PEP 8 style guide.
  2. Use descriptive variable names.
  3. Write docstrings for functions.
  4. Use virtual environments (venv).
  5. Manage dependencies with requirements.txt.