MASTER YOUR
CODE

// The most versatile programming language.

PYTHON IS THE LANGUAGE OF POSSIBILITY.

From web development to data science, machine learning to automation, Python powers the modern world. It's readable, powerful, and has the largest ecosystem of libraries of any programming language.

WHY PYTHON?

Python emphasizes code readability with its clean syntax. It runs everywhere, has massive community support, and lets you build anything from simple scripts to complex AI systems.

BECOME A PYTHONISTA.

Learn fundamentals, object-oriented programming, file handling, APIs, and best practices. Join millions of developers who choose Python as their primary language.

BEGIN YOUR JOURNEY →

// The Path to Mastery

12 lessons. Complete Python control.

LESSON 01

Introduction to Python

Learn Python basics, installation, and write your first program.

Beginner
LESSON 02

Variables & Data Types

Store and manipulate data with variables, strings, numbers, and booleans.

Beginner
LESSON 03

Control Flow

Make decisions with if/else statements and automate with loops.

Beginner
LESSON 04

Functions

Write reusable code blocks with parameters and return values.

Beginner
LESSON 05

Lists & Tuples

Work with ordered collections and manipulate sequences of data.

Beginner
LESSON 06

Dictionaries & Sets

Store key-value pairs and work with collections of unique items.

Intermediate
LESSON 07

File I/O

Read from and write to files, handle CSV and JSON data.

Intermediate
LESSON 08

Object-Oriented Programming

Create classes, objects, and build reusable components with OOP.

Intermediate
LESSON 09

Error Handling

Handle exceptions gracefully and debug your Python programs.

Intermediate
LESSON 10

Modules & Packages

Organize code across files and import functionality from libraries.

Intermediate
LESSON 11

Working with APIs

Fetch data from web services and work with JSON responses.

Advanced
LESSON 12

Best Practices

Write clean, Pythonic code following PEP 8 and best practices.

Advanced

// Why Python

Python was created by Guido van Rossum in 1991 with a philosophy emphasizing code readability. Today, it's the most popular programming language for beginners and experts alike.

Python's versatility is unmatched. Need a web server? Use Flask or Django. Data analysis? Pandas and NumPy have you covered. Machine learning? TensorFlow and PyTorch are industry standards. Automation? Python scripts everything.

The Python Package Index (PyPI) hosts over 350,000 packages. Whatever you want to build, someone has likely already solved the hard problems.

The future of programming is Python. Own it.

// Tools & References

📖 Official Docs

Python Documentation

docs.python.org

📦 PyPI

Python Package Index

pypi.org

🐍 PEPs

Python Enhancement Proposals

peps.python.org

🛠️ IDLE

Python's Built-in IDE

idle docs

🐳 VirtualEnvs

Environment Management

venv docs

⚡ PIP

Package Installer

pip.pypa.io

// Introduction to Python

×

What is Python?

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991. Its design philosophy emphasizes code readability and simplicity.

Why Python?

  • Readable: Clean, English-like syntax
  • Versatile: Web, data science, AI, automation
  • Portable: Runs on Windows, Mac, Linux
  • Community: Massive ecosystem of packages
  • Interpreted: No compilation needed
PYTHON'S PHILOSOPHY: "There should be one—and preferably only one—obvious way to do it." This makes Python code consistent and readable.

Installing Python

$ python3 --version Python 3.11.4

Running Python

$ python3 Python 3.11.4 (main, Mar 10 2024) [GCC 11.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello, World!") Hello, World!

Your First Python Script

# hello.py print("Hello, World!") # Run with: python3 hello.py

Python Philosophy - The Zen

>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. ...

Indentation in Python

Python uses indentation to define code blocks, not braces or keywords:

if 5 > 2: print("Five is greater than two!")

Quiz

1. Python was created by _____ in 1991.

Hint: Dutch programmer

2. Python is a _____ language.

Hint: Not compiled

3. To print, use the _____ function.

Hint: Built-in function

4. Python uses _____ to define code blocks.

Hint: Whitespace

5. The command to run Python is _____.

Hint: In terminal

6. import _____ shows Python philosophy.

Hint: Easter egg

7. Python emphasizes code _____.

Hint: Easy to read

8. PEP stands for Python _____ Proposal.

Hint: Improvement

Show Answers

Answers

  1. Guido van Rossum
  2. interpreted
  3. print
  4. indentation
  5. python3
  6. this
  7. readability
  8. Enhancement

// Variables & Data Types

×

Variables

Variables are containers for storing data values. In Python, you don't need to declare variable types.

# Creating variables name = "Alice" age = 25 height = 5.8 is_student = True print(name) print(age)

Data Types

Strings (str)

name = "Python" message = 'Hello' multi_line = """This is a multi-line string"""

Numbers

integer = 42 floating = 3.14

Booleans (bool)

is_active = True is_deleted = False

Type Checking

x = 10 print(type(x)) # y = "Hello" print(type(y)) #

Type Conversion

# String to int x = "10" y = int(x) # Int to string z = 42 s = str(z) # String to float f = float("3.14") # To boolean bool("non-empty") # True bool("") # False

Variable Naming Rules

  • Start with letter or underscore
  • Can contain letters, numbers, underscores
  • Case-sensitive (age ≠ Age)
  • Cannot be Python keywords

Multiple Assignment

# Multiple variables at once a, b, c = 1, 2, 3 # Same value to multiple variables x = y = z = 0

Quiz

1. Variables store _____ values.

Hint: Information

2. Strings use _____ quotes.

Hint: \

3. The type() function returns the _____.

Hint: Type of variable

4. int() converts to _____.

Hint: Whole number

5. Boolean values are _____ and False.

Hint: Capital T

6. Variables cannot be Python _____.

Hint: Reserved words

7. float() converts to _____ number.

Hint: With decimal

8. Python is _____ typed.

Hint: No declaration needed

Show Answers

Answers

  1. data
  2. double or single
  3. data type
  4. integer
  5. True
  6. keywords
  7. decimal
  8. dynamically

// Control Flow

×

Conditional Statements

Use if, elif, and else to make decisions in your code.

age = 18 if age >= 18: print("You are an adult") elif age >= 13: print("You are a teenager") else: print("You are a child")

Comparison Operators

  • == Equal
  • != Not equal
  • > Greater than
  • < Less than
  • >= Greater than or equal
  • <= Less than or equal

Logical Operators

# and, or, not age = 25 has_license = True if age >= 18 and has_license: print("You can drive") if age < 18 or not has_license: print("You cannot drive")

For Loops

# Loop through a range for i in range(5): print(i) # 0, 1, 2, 3, 4 # Loop through a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

While Loops

count = 0 while count < 5: print(count) count += 1 # With break while True: response = input("Enter 'quit' to exit: ") if response == "quit": break

Loop Control

  • break - Exit the loop
  • continue - Skip to next iteration
  • pass - Do nothing (placeholder)

Match Statement (Python 3.10+)

status = "active" match status: case "active": print("System is active") case "inactive": print("System is inactive") case _: print("Unknown status")

Quiz

1. Use _____ for decisions in code.

Hint: Conditional

2. == means _____ comparison.

Hint: Equal to

3. _____ continues to next iteration.

Hint: Skip

4. range(5) produces _____ numbers.

Hint: Five numbers

5. while True needs _____ to exit.

Hint: Exit condition

6. elif is short for else _____ .

Hint: Else if

7. pass is a _____ statement.

Hint: Do nothing

8. or returns True if _____ is True.

Hint: At least one

Show Answers

Answers

  1. if
  2. equality
  3. continue
  4. 0 to 4
  5. break
  6. if
  7. placeholder
  8. any

// Functions

×

Defining Functions

Functions are reusable blocks of code that perform a specific task.

def greet(): print("Hello!") greet() # Call the function

Parameters and Arguments

# Function with parameter def greet(name): print(f"Hello, {name}!") greet("Alice") # Hello, Alice! # Multiple parameters def add(a, b): return a + b result = add(5, 3) print(result) # 8

Default Parameters

def greet(name="World"): print(f"Hello, {name}!") greet() # Hello, World! greet("Alice") # Hello, Alice!

Return Values

def get_full_name(first, last): return f"{first} {last}" name = get_full_name("John", "Doe") print(name) # John Doe # Return multiple values (as tuple) def get_stats(numbers): return min(numbers), max(numbers) minimum, maximum = get_stats([1, 2, 3])

Args and Kwargs

# *args - variable positional arguments def sum_all(*args): total = 0 for num in args: total += num return total print(sum_all(1, 2, 3, 4)) # 10 # **kwargs - variable keyword arguments def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Alice", age=25)

Lambda Functions

Small anonymous functions:

# Lambda function square = lambda x: x ** 2 print(square(5)) # 25 # With map numbers = [1, 2, 3] squared = list(map(lambda x: x**2, numbers)) # With filter evens = list(filter(lambda x: x % 2 == 0, numbers))

Quiz

1. Use _____ to define a function.

Hint: Keyword

2. return sends a _____ back.

Hint: Result

3. Parameters with defaults go at the _____.

Hint: Last

4. *args handles variable _____ arguments.

Hint: Non-keyword

5. **kwargs handles variable _____ arguments.

Hint: Named

6. Lambda functions are _____.

Hint: No name

7. map() applies function to each _____ in iterable.

Hint: Item

8. filter() keeps elements matching _____.

Hint: True condition

Show Answers

Answers

  1. def
  2. value
  3. end
  4. positional
  5. keyword
  6. anonymous
  7. element
  8. condition

// Lists & Tuples

×

Lists

Lists are ordered, mutable collections that can hold items of any type.

# Creating a list fruits = ["apple", "banana", "cherry"] numbers = [1, 2, 3, 4, 5] mixed = ["hello", 42, 3.14] # Empty list empty = []

Accessing Elements

fruits = ["apple", "banana", "cherry", "date"] print(fruits[0]) # apple (first) print(fruits[-1]) # date (last) print(fruits[1:3]) # ['banana', 'cherry']

Modifying Lists

fruits = ["apple", "banana"] fruits.append("cherry") # Add to end fruits.insert(1, "orange") # Insert at index fruits.extend(["grape", "melon"]) # Add multiple fruits[0] = "mango" # Change element fruits.remove("banana") # Remove by value popped = fruits.pop() # Remove and return last

List Operations

numbers = [3, 1, 4, 1, 5] print(len(numbers)) # 5 print(sorted(numbers)) # [1, 1, 3, 4, 5] print(numbers.count(1)) # 2 print(numbers.index(4)) # 2 for fruit in fruits: print(fruit)

Tuples

Tuples are ordered, immutable collections.

# Creating tuples coordinates = (10, 20) point = (1, 2, 3) # Accessing (same as lists) print(coordinates[0]) # 10 # Unpacking x, y = coordinates print(f"X: {x}, Y: {y}")

Tuple Methods

point = (1, 2, 3) print(len(point)) # 3 print(point.count(2)) # 1 print(point.index(3)) # 2

List Comprehensions

# Create list from range squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16] # With condition evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]

Quiz

1. Lists are _____ (can be changed).

Hint: Changeable

2. Tuples are _____ (cannot be changed).

Hint: Unchangeable

3. Use _____ to add to end of list.

Hint: Add method

4. index() returns the _____ of element.

Hint: Location

5. pop() removes and _____ the last element.

Hint: Sends back

6. List comprehensions use square _____.

Hint: []

7. Negative index accesses from the _____.

Hint: Last

8. count() returns number of _____.

Hint: How many

Show Answers

Answers

  1. mutable
  2. immutable
  3. append
  4. position
  5. returns
  6. brackets
  7. end
  8. occurrences

// Dictionaries & Sets

×

Dictionaries

Dictionaries store key-value pairs. They're unordered, mutable, and indexed by keys.

# Creating a dictionary person = { "name": "Alice", "age": 25, "city": "New York" } # Empty dictionary empty_dict = {}

Accessing & Modifying

person = {"name": "Alice", "age": 25} # Access value by key print(person["name"]) # Alice print(person.get("age")) # 25 # Get with default print(person.get("country", "USA")) # USA # Add or update person["email"] = "alice@example.com" person["age"] = 26 # Delete del person["city"] email = person.pop("email")

Dictionary Methods

person = {"name": "Alice", "age": 25} print(person.keys()) # dict_keys(['name', 'age']) print(person.values()) # dict_values(['Alice', 25]) print(person.items()) # dict_items([('name', 'Alice'), ...]) # Update with another dict person.update({"city": "Boston", "country": "USA"}) # Check if key exists if "name" in person: print("Name exists")

Looping Through Dictionaries

person = {"name": "Alice", "age": 25} # Keys for key in person: print(key) # Key-value pairs for key, value in person.items(): print(f"{key}: {value}")

Sets

Sets are unordered, mutable collections of unique elements.

# Creating a set fruits = {"apple", "banana", "cherry"} # Empty set (not {}) empty_set = set() # From list (duplicates removed) numbers = set([1, 2, 2, 3, 3]) # {1, 2, 3}

Set Operations

a = {1, 2, 3, 4} b = {3, 4, 5, 6} print(a | b) # Union: {1, 2, 3, 4, 5, 6} print(a & b) # Intersection: {3, 4} print(a - b) # Difference: {1, 2} print(a ^ b) # Symmetric diff: {1, 2, 5, 6}

Set Methods

fruits = {"apple", "banana"} fruits.add("cherry") # Add one fruits.update(["date", "elderberry"]) # Add multiple fruits.remove("banana") # Remove (raises error if missing) fruits.discard("grape") # Remove (no error)

Quiz

1. Dictionaries store _____ pairs.

Hint: Keys and values

2. Use get() to safely access _____.

Hint: With default

3. pop() removes and _____ a key-value pair.

Hint: Sends back

4. Sets store only _____ elements.

Hint: No duplicates

5. & (ampersand) performs _____ operation.

Hint: Common elements

6. | performs _____ operation.

Hint: All elements

7. discard() removes without _____ if missing.

Hint: No

8. items exception() returns _____ pairs.

Hint: Tuples

Show Answers

Answers

  1. key-value
  2. keys
  3. returns
  4. unique
  5. intersection
  6. union
  7. error
  8. key-value

// File I/O

×

Reading Files

# Open and read entire file with open("file.txt", "r") as file: content = file.read() print(content) # Read line by line with open("file.txt", "r") as file: for line in file: print(line.strip()) # Read all lines into list with open("file.txt", "r") as file: lines = file.readlines()

Writing Files

# Write (overwrites existing) with open("output.txt", "w") as file: file.write("Hello, World!\n") file.write("Second line") # Append to file with open("output.txt", "a") as file: file.write("\nAppended text")

File Modes

  • r - Read (default)
  • w - Write (overwrites)
  • a - Append
  • r+ - Read and write
  • rb - Read binary
  • wb - Write binary

Working with JSON

import json # Write JSON data = { "name": "Alice", "age": 25, "hobbies": ["reading", "coding"] } with open("data.json", "w") as file: json.dump(data, file, indent=2) # Read JSON with open("data.json", "r") as file: loaded_data = json.load(file) # Convert to/from string json_string = json.dumps(data) parsed = json.loads(json_string)

Working with CSV

import csv # Write CSV with open("data.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerow(["Name", "Age"]) writer.writerow(["Alice", 25]) writer.writerow(["Bob", 30]) # Read CSV with open("data.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row)

Path Handling

from pathlib import Path # Create path object p = Path("folder/file.txt") # Check existence print(p.exists()) # Get parts print(p.stem) # file print(p.suffix) # .txt print(p.parent) # folder # List directory for item in Path(".").iterdir(): print(item)

Quiz

1. Use open() with mode _____ for reading.

Hint: Read mode

2. with statement ensures file is _____.

Hint: Auto-closed

3. mode _____ overwrites the file.

Hint: Write mode

4. JSON stores data as _____.

Hint: Human-readable

5. csv module handles _____ files.

Hint: CSV format

6. Path from pathlib represents _____.

Hint: File/directory

7. strip() removes _____ from strings.

Hint: Newlines, spaces

8. dump() writes _____ to file.

Hint: JSON data

Show Answers

Answers

  1. \
  2. closed
  3. \
  4. text
  5. comma-separated
  6. file paths
  7. whitespace
  8. JSON

// Object-Oriented Programming

×

Classes and Objects

class Dog: # Class attribute species = "Canis familiaris" # Constructor def __init__(self, name, age): self.name = name # Instance attribute self.age = age # Instance method def bark(self): return f"{self.name} says woof!" # String representation def __str__(self): return f"{self.name} is {self.age} years old" # Create object buddy = Dog("Buddy", 3) print(buddy.name) # Buddy print(buddy.bark()) # Buddy says woof! print(str(buddy)) # Buddy is 3 years old

Inheritance

class Animal: def __init__(self, name): self.name = name def speak(self): pass class Cat(Animal): # Inherits from Animal def speak(self): return f"{self.name} says meow!" class Dog(Animal): def speak(self): return f"{self.name} says woof!" cat = Cat("Whiskers") print(cat.speak()) # Whiskers says meow!

Encapsulation

Using private attributes (prefixed with _ or __):

class BankAccount: def __init__(self, balance): self.__balance = balance # Private def deposit(self, amount): if amount > 0: self.__balance += amount return True return False def get_balance(self): return self.__balance account = BankAccount(1000) account.deposit(500) print(account.get_balance()) # 1500

Class Methods & Static Methods

class User: def __init__(self, username): self.username = username # Class method - receives class as first arg @classmethod def from_string(cls, s): return cls(s.split("@")[0]) # Static method - no self or cls @staticmethod def validate_email(email): return "@" in email user = User.from_string("alice@example.com")

Properties

class Temperature: def __init__(self, celsius=0): self.celsius = celsius @property def fahrenheit(self): return (self.celsius * 9/5) + 32 @fahrenheit.setter def fahrenheit(self, value): self.celsius = (value - 32) * 5/9 temp = Temperature(25) print(temp.fahrenheit) # 77.0 temp.fahrenheit = 100 print(temp.celsius) # 37.777...

Quiz

1. __init__ is called when _____ object.

Hint: Instantiation

2. self refers to the _____.

Hint: Current object

3. Inheritance creates a child-_____ relationship.

Hint: Base class

4. __balance uses _____ encapsulation.

Hint: Double underscore

5. @classmethod receives _____ as first argument.

Hint: Class

6. @property creates a _____.

Hint: Computed attribute

7. __str__ defines _____ representation.

Hint: str() output

8. Static methods don

Hint: Instance

Show Answers

Answers

  1. creating
  2. instance
  3. parent
  4. name mangling
  5. cls
  6. getter
  7. string
  8. self

// Error Handling

×

Try-Except Blocks

try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") try: value = int("not a number") except ValueError as e: print(f"Error: {e}")

Multiple Exceptions

try: x = int("abc") y = 10 / 0 except ValueError: print("Invalid number") except ZeroDivisionError: print("Division by zero") except (ValueError, ZeroDivisionError) as e: print(f"Error: {e}")

Else and Finally

try: file = open("data.txt", "r") content = file.read() except FileNotFoundError: print("File not found") else: print("File read successfully") finally: print("This always runs") try: file.close() except: pass

Common Exceptions

  • ValueError - Invalid value
  • TypeError - Wrong type
  • FileNotFoundError - File doesn't exist
  • IndexError - List index out of range
  • KeyError - Dict key not found
  • ZeroDivisionError - Division by zero
  • NameError - Variable not defined

Raising Exceptions

def divide(a, b): if b == 0: raise ValueError("Divisor cannot be zero") return a / b try: divide(10, 0) except ValueError as e: print(e)

Custom Exceptions

class ValidationError(Exception): def __init__(self, message): self.message = message super().__init__(message) def validate_age(age): if age < 0: raise ValidationError("Age cannot be negative") return "Valid"

Quiz

1. Try-except handles _____.

Hint: Errors

2. except catches specific _____ type.

Hint: Exception

3. _____ runs if no exception occurred.

Hint: After try

4. _____ always runs.

Hint: Always executes

5. raise creates an _____.

Hint: Error

6. Custom exceptions inherit from _____.

Hint: Base class

7. ValueError is for invalid _____.

Hint: Wrong value

8. as e stores exception in _____.

Hint: Reference

Show Answers

Answers

  1. exceptions
  2. error
  3. else
  4. finally
  5. exception
  6. Exception
  7. values
  8. variable

// Modules & Packages

×

Importing Modules

# Import entire module import math print(math.sqrt(16)) # 4.0 print(math.pi) # 3.14159... # Import specific items from math import sqrt, pi print(sqrt(16)) # 4.0 # Import with alias import numpy as np # Import everything (not recommended) from math import *

Standard Library Modules

  • os - Operating system interface
  • sys - System parameters
  • datetime - Date/time handling
  • json - JSON handling
  • re - Regular expressions
  • random - Random numbers
  • collections - Specialized containers

Creating Your Own Modules

# mymodule.py def greet(name): return f"Hello, {name}!" CONSTANT = 42 # In another file: import mymodule print(mymodule.greet("Alice")) print(mymodule.CONSTANT)

PIP - Package Installer

$ pip install requests Collecting requests Downloading requests-2.31.0-py3-none-any.whl Installing collected packages: requests
$ pip list Package Version ---------- ------- pip 23.2.1 requests 2.31.0
$ pip freeze > requirements.txt # Save dependencies
$ pip install -r requirements.txt # Install from file

Virtual Environments

$ python3 -m venv myenv # Create environment
$ source myenv/bin/activate # Activate (Linux/Mac)
$ myenv\Scripts\activate # Activate (Windows)
$ deactivate # Deactivate

Working with Packages

# Import from package from package import module from package.module import function # __init__.py makes folder a package

Quiz

1. pip installs _____.

Hint: Libraries

2. Virtual environments keep dependencies _____.

Hint: Separate

3. activate script is in _____ folder.

Hint: Scripts on Windows

4. from module _____ imports specific items.

Hint: Select

5. as creates an _____.

Hint: Nickname

6. requirements.txt lists _____ versions.

Hint: Dependencies

7. freeze saves current _____.

Hint: Installed libs

8. __init__.py makes folder a _____.

Hint: Importable

Show Answers

Answers

  1. packages
  2. isolated
  3. bin
  4. import
  5. alias
  6. package
  7. packages
  8. package

// Working with APIs

×

HTTP Requests

$ pip install requests
import requests # GET request response = requests.get("https://api.example.com/data") print(response.status_code) # 200 print(response.json()) # Parsed JSON # POST request data = {"name": "Alice", "age": 25} response = requests.post("https://api.example.com/users", json=data) # With headers headers = {"Authorization": "Bearer token123"} response = requests.get("https://api.example.com/protected", headers=headers)

REST API Methods

  • GET - Retrieve data
  • POST - Create new resource
  • PUT - Update/replace resource
  • PATCH - Partial update
  • DELETE - Remove resource

Status Codes

  • 200 - OK (success)
  • 201 - Created
  • 400 - Bad Request
  • 401 - Unauthorized
  • 404 - Not Found
  • 500 - Server Error

Working with JSON APIs

import requests # GitHub API example response = requests.get("https://api.github.com/users/octocat") data = response.json() print(data["login"]) # octocat print(data["public_repos"]) # Number of repos print(data["html_url"]) # Profile URL # Handle errors if response.status_code == 200: print("Success!") elif response.status_code == 404: print("Not found")

Query Parameters

import requests # GET with query parameters params = { "q": "python", "sort": "stars", "order": "desc" } response = requests.get("https://api.github.com/search/repositories", params=params) data = response.json() # First result if data["total_count"] > 0: top_repo = data["items"][0] print(top_repo["full_name"]) print(top_repo["stargazers_count"])

Error Handling

import requests try: response = requests.get("https://api.example.com/data", timeout=5) response.raise_for_status() # Raises for 4xx/5xx data = response.json() except requests.Timeout: print("Request timed out") except requests.HTTPError as e: print(f"HTTP error: {e}") except requests.RequestException as e: print(f"Request failed: {e}")

Quiz

1. requests.get() makes _____ requests.

Hint: Retrieve

2. status_code 200 means _____.

Hint: OK

3. JSON method parses response _____.

Hint: Content

4. params argument adds _____ parameters.

Hint: URL parameters

5. raise_for_status() raises for _____ codes.

Hint: 4xx/5xx

6. timeout limits _____ time.

Hint: Seconds

7. POST creates new _____.

Hint: Data

8. Authorization header sends _____.

Hint: Token/password

Show Answers

Answers

  1. GET
  2. success
  3. body
  4. query
  5. error
  6. wait
  7. resources
  8. credentials

// Best Practices

×

Code Style - PEP 8

  • Use 4 spaces per indentation level
  • Maximum line length of 79 characters
  • Use blank lines to separate functions and classes
  • Use lowercase with underscores for function names
  • Use CapWords for class names
  • Use descriptive variable names
# Good def calculate_total(items): total = 0 for item in items: total += item["price"] return total # Bad def calc(i): t = 0 for x in i: t += x["p"] return t

Docstrings

def greet(name): """Return a greeting message for the given name. Args: name: The name of the person to greet. Returns: A string containing the greeting. """ return f"Hello, {name}!" class Dog: """A class representing a dog.""" def bark(self): """Make the dog bark.""" print("Woof!")

Type Hints

def add_numbers(a: int, b: int) -> int: return a + b def get_name(user: dict) -> str: return user.get("name", "") from typing import List, Dict def process_items(items: List[int]) -> Dict[str, int]: return { "sum": sum(items), "count": len(items) }

Testing

import unittest class TestMath(unittest.TestCase): def test_add(self): self.assertEqual(1 + 1, 2) def test_divide(self): self.assertEqual(10 / 2, 5) if __name__ == "__main__": unittest.main()

Virtual Environments

$ python3 -m venv .venv $ source .venv/bin/activate $ pip install -r requirements.txt

Logging

import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) logger.info("Starting application") logger.warning("This is a warning") logger.error("An error occurred")

Working with git

$ git init $ git add . $ git commit -m "Initial commit" $ git log

.gitignore

__pycache__/ *.py[cod] *$py.class *.so .Python .venv/ venv/ .env *.egg-info/ dist/ build/

Quiz

1. PEP 8 is the Python _____.

Hint: Code standards

2. Use _____ spaces per indentation.

Hint: PEP 8

3. Docstrings document _____.

Hint: Code

4. Type hints specify _____ types.

Hint: Expected

5. unittest is Python

Hint: Unit tests

6. _____ environments isolate dependencies.

Hint: venv

7. __pycache__ should be in _____.

Hint: Not tracked

8. logging module provides _____ logging.

Hint: Standard lib

Show Answers

Answers

  1. style guide
  2. 4
  3. functions
  4. variable
  5. testing
  6. virtual
  7. .gitignore
  8. built-in