Python Documentation

A versatile and beginner-friendly programming language for web development, data science, automation, and more

Introduction to Python

Python is a high-level, interpreted, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace.

Python 3 is the current version and is not backward-compatible with Python 2. Python 2 reached end-of-life on January 1, 2020.

Basic Syntax

Python syntax is simple and easy to learn, with a focus on readability.

Hello World

print("Hello, World!")

Comments

# Single line comment

'''
This is a
multi-line
comment
'''

Indentation

Python uses indentation to define code blocks instead of braces or keywords.

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

Variables & Data Types

Variables are containers for storing data values. Python has various data types.

Variable Assignment

x = 5           # Integer
y = "Hello"     # String
z = 3.14       # Float

Multiple Assignment

a, b, c = 1, 2, 3
x = y = z = "Same"

Data Types

Type Example Description
int 42, -5 Integer numbers
float 3.14, -0.5 Floating point numbers
str "Hello", 'World' String (text)
bool True, False Boolean values
list [1, 2, 3] Ordered, mutable collection
tuple (1, 2, 3) Ordered, immutable collection
dict {"name": "John"} Key-value pairs (dictionary)
set {1, 2, 3} Unordered, unique elements
None None Represents absence of value

Type Conversion

x = int("5")      # String to integer
y = float("3.14")  # String to float
z = str(42)       # Integer to string

Operators

Arithmetic Operators

Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
// Floor Division x // y
% Modulus x % y
** Exponentiation x ** y

Comparison Operators

Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical Operators

Operator Name Example
and Logical AND x < 5 and x > 2
or Logical OR x < 5 or x > 10
not Logical NOT not(x == y)

Bitwise Operators

Operator Name Example
& AND x & y
| OR x | y
^ XOR x ^ y
~ NOT ~x
<< Left Shift x << 2
>> Right Shift x >> 2

Control Flow

If-Else Statements

if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

Ternary Operator

result = "Even" if x % 2 == 0 else "Odd"

For Loop

for i in range(5):
    print(i)

for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

While Loop

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

Break and Continue

for i in range(10):
    if i == 5:
        break  # Exit the loop
    if i % 2 == 0:
        continue  # Skip to next iteration
    print(i)

Match-Case (Python 3.10+)

match day:
    case "Monday":
        print("Start of week")
    case "Friday":
        print("Almost weekend")
    case _:
        print("Midweek")

Functions

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

Function Definition

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

Function Call

message = greet("Alice")
print(message)  # Output: Hello, Alice!

Default Parameters

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

print(greet())          # Output: Hello, World!
print(greet("Bob"))      # Output: Hello, Bob!

Variable-Length Arguments

def sum_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

print(sum_numbers(1, 2, 3, 4))  # Output: 10

Keyword Arguments

def describe_person(name, age, city):
    return f"{name} is {age} years old and lives in {city}."

print(describe_person(name="Alice", age=25, city="New York"))

Lambda Functions

square = lambda x: x ** 2
print(square(5))  # Output: 25

Nested Functions

def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

func = outer_function(10)
print(func(5))  # Output: 15

Data Structures

Lists

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

Tuples

coordinates = (10, 20, 30)
x, y, z = coordinates  # Unpacking
# Tuples are immutable (cannot be changed)

Dictionaries

person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

person["name"]        # Access value
person["email"] = "john@example.com"  # Add new key-value
for key, value in person.items():  # Iterate
    print(key, value)

Sets

unique_numbers = {1, 2, 3, 2, 1}  # {1, 2, 3}
unique_numbers.add(4)        # Add element
unique_numbers.remove(2)     # Remove element
common = set1 & set2      # Intersection
union = set1 | set2        # Union

List Comprehensions

squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
matrix = [[i*j for j in range(5)] for i in range(5)]

Object-Oriented Programming

Python supports object-oriented programming with classes and objects.

Classes and Objects

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hello, I'm {self.name} and I'm {self.age} years old."

# Create object
person = Person("Alice", 25)
print(person.greet())

Inheritance

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id
    
    def study(self):
        return "Studying..."

student = Student("Bob", 20, "S12345")
print(student.greet())  # Inherited from Person
print(student.study())   # Student-specific method

Class Methods and Static Methods

class MathUtils:
    def add(self, a, b):
        return a + b
    
    @classmethod
    def from_string(cls, s):
        return cls()  # Factory method
    
    @staticmethod
    def square(x):
        return x ** 2

Property Decorators

class Circle:
    def __init__(self, radius):
        self._radius = radius
    
    @property
    def radius(self):
        return self._radius
    
    @radius.setter
    def radius(self, value):
        if value >= 0:
            self._radius = value
    
    @property
    def area(self):
        return 3.14 * self._radius ** 2

File Handling

Python provides built-in functions for reading and writing files.

Reading Files

with open("file.txt", "r") as file:
    content = file.read()          # Read entire file
    lines = file.readlines()      # Read as list of lines
    for line in file:             # Iterate through lines
        print(line.strip())

Writing Files

with open("file.txt", "w") as file:
    file.write("Hello, World!\n")
    file.writelines(lines)  # Write list of strings

Appending to Files

with open("file.txt", "a") as file:
    file.write("New line\n")

File Modes

Mode Description
"r" Read (default)
"w" Write (overwrites existing file)
"a" Append (adds to end of file)
"r+" Read and write
"b" Binary mode
"+" Update (read and write)

Working with Directories

import os

# Create directory
os.mkdir("new_dir")

# Remove directory
os.rmdir("new_dir")

# List directory contents
files = os.listdir("path")

# Check if file exists
if os.path.exists("file.txt"):
    print("File exists")

Practical Examples

Simple Calculator

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

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b != 0:
        return a / b
    return "Cannot divide by zero!"

Fibonacci Sequence

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=" ")
        a, b = b, a + b

fibonacci(10)  # Prints first 10 Fibonacci numbers

File Word Counter

def count_words(filename):
    with open(filename, "r") as file:
        content = file.read()
        words = content.split()
        return len(words)

word_count = count_words("document.txt")
print(f"Word count: {word_count}")

Web Scraper (using requests and BeautifulSoup)

import requests
from bs4 import BeautifulSoup

url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

# Extract all links
for link in soup.find_all("a"):
    print(link.get("href"))