Python Basics
Python is easy
Basic Syntax
Section titled “Basic Syntax”This covers the fundamental rules and structure of Python code - how to write statements, use variables, and basic operations.
# Comments start with # - they're ignored by Pythonprint("Hello, World!") # Basic output function
# Variables don't need type declaration - Python figures it outx = 5 # Integer variablename = "Alice" # String variable
# Multiple assignment - assign multiple variables at oncea, b, c = 1, 2, 3 # a=1, b=2, c=3
# Basic arithmetic follows PEMDAS rulesresult = 10 + 5 * 2 # Multiplication first: 5*2=10, then 10+10=20
# Indentation matters! Use 4 spaces for code blocksif x > 3: print("x is greater than 3") # This is indentedKey Points:
- Python uses indentation (spaces) to define code blocks instead of braces {}
- Variables are dynamically typed (no need to declare types)
- Statements don’t need semicolons at the end
- Comments help document your code
Data Types
Section titled “Data Types”Data types define what kind of data variables can hold. Python has several built-in types for different purposes.
# Numeric typesinteger = 42 # Whole numbersfloat_num = 3.14 # Decimal numberscomplex_num = 2 + 3j # Complex numbers (real + imaginary part)
# Boolean - represents True or Falseis_true = Trueis_false = False
# Strings - text datatext = "Hello World"multi_line = """This is amulti-line string""" # Triple quotes for multi-line
# Type conversion - changing between typesstr_num = str(123) # Convert number to string: "123"int_num = int("456") # Convert string to integer: 456float_num = float("3.14") # Convert string to float: 3.14
# Check typesprint(type(integer)) # <class 'int'>print(type(text)) # <class 'str'>Key Points:
- int: Whole numbers (positive, negative, zero)
- float: Decimal numbers
- str: Text data, immutable (can’t change individual characters)
- bool: True or False values
- Use type conversion functions to change between types
Control Flow
Section titled “Control Flow”Control flow determines the order in which code executes. It includes conditionals (if/else) and loops (for/while).
Conditional Statements
Section titled “Conditional Statements”age = 18
# if-elif-else chain - only one block executesif age < 13: print("Child") # Runs if age < 13elif age < 20: print("Teenager") # Runs if 13 <= age < 20else: print("Adult") # Runs if age >= 20
# Ternary operator - shorthand for simple if-elsestatus = "Adult" if age >= 18 else "Minor"# Equivalent to:if age >= 18: status = "Adult"else: status = "Minor"# For loop - iterate a specific number of timesfor i in range(5): # range(5) generates 0,1,2,3,4 print(i) # Prints 0,1,2,3,4
# While loop - repeat while condition is Truecount = 0while count < 5: print(count) # Prints 0,1,2,3,4 count += 1 # Increment counter
# Loop control statementsfor i in range(10): if i == 3: continue # Skip rest of this iteration, go to next number if i == 7: break # Exit loop completely print(i) # Prints 0,1,2,4,5,6Key Points:
- if/elif/else: Make decisions based on conditions
- for loops: Iterate over sequences (lists, ranges, etc.)
- while loops: Repeat while condition is true
- break: Exit loop immediately
- continue: Skip to next iteration
Functions
Section titled “Functions”Functions are reusable blocks of code that perform specific tasks. They help organize code and avoid repetition.
# Basic function definition and calldef greet(name): # Define function with parameter return f"Hello, {name}!" # Return a value
result = greet("Alice") # Call function with argumentprint(result) # "Hello, Alice!"
# Function with default parametersdef power(base, exponent=2): # exponent defaults to 2 if not provided return base ** exponent
print(power(3)) # 3^2 = 9 (uses default exponent)print(power(3, 3)) # 3^3 = 27 (uses provided exponent)
# Variable arguments - accept any number of argumentsdef sum_all(*args): # *args collects all arguments as tuple return sum(args)
print(sum_all(1, 2, 3, 4)) # 10
# Keyword arguments - accept named argumentsdef person_info(**kwargs): # **kwargs collects named arguments as dictionary for key, value in kwargs.items(): print(f"{key}: {value}")
person_info(name="Alice", age=30, city="NY") # name: Alice, age: 30, city: NY
# Lambda functions - small anonymous functionssquare = lambda x: x * x # Equivalent to def square(x): return x*xprint(square(5)) # 25Key Points:
- def: Keyword to define functions
- Parameters: Variables in function definition
- Arguments: Values passed to function
- return: Sends result back to caller
- *args: For variable number of arguments
- **kwargs: For variable number of keyword arguments
- lambda: For small, one-line functions
Data Structures
Section titled “Data Structures”Data structures organize and store data efficiently. Python has several built-in structures for different needs.
Lists (Mutable Sequences)
Section titled “Lists (Mutable Sequences)”- Lists:
Ordered,mutable,allows duplicates
# Creating lists - ordered, changeable collectionsfruits = ["apple", "banana", "cherry"]numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]
# List operationsfruits.append("orange") # Add to end: ["apple", "banana", "cherry", "orange"]fruits.insert(1, "blueberry") # Insert at index 1fruits.remove("banana") # Remove specific valuelast_fruit = fruits.pop() # Remove and return last item
# List comprehension - concise way to create listssquares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]even_squares = [x**2 for x in range(10) if x % 2 == 0] # Squares of even numbers onlyTuples (Immutable Sequences)
Section titled “Tuples (Immutable Sequences)”- Tuples:
Ordered,immutable,allows duplicates
# Tuples - ordered, unchangeable collectionscoordinates = (10, 20)point = 30, 40 # Parentheses optional for tuples
# Unpacking - assign tuple elements to variablesx, y = coordinates # x=10, y=20
# Tuples are immutable (can't change after creation)# coordinates[0] = 15 # This would cause ERROR!Dictionaries (Key-Value Pairs)
Section titled “Dictionaries (Key-Value Pairs)”- Dictionaries:
Unordered,key-valuepairs,keysmust beunique
# Dictionaries - unordered collections of key-value pairsperson = { "name": "Alice", "age": 30, "city": "New York"}
# Dictionary operationsperson["email"] = "alice@email.com" # Add new key-value pairage = person.get("age", "Unknown") # Safe get - returns "Unknown" if key doesn't exist
# Dictionary comprehensionsquares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Sets (Unique Elements)
Section titled “Sets (Unique Elements)”- Sets:
Unordered,uniqueelements only
# Sets - unordered collections of unique elementsunique_numbers = {1, 2, 3, 3, 4} # Duplicates removed: {1, 2, 3, 4}
# Set operationsset_a = {1, 2, 3}set_b = {3, 4, 5}union = set_a | set_b # All unique elements: {1, 2, 3, 4, 5}intersection = set_a & set_b # Common elements: {3}difference = set_a - set_b # In A but not B: {1, 2}Key Points:
- Lists: Ordered, mutable, allows duplicates
- Tuples: Ordered, immutable, allows duplicates
- Dictionaries: Unordered, key-value pairs, keys must be unique
- Sets: Unordered, unique elements only
- Use comprehensions for concise creation of these structures
Object-Oriented Programming (OOP)
Section titled “Object-Oriented Programming (OOP)”OOP organizes code into objects that contain both data (attributes) and behavior (methods). It helps model real-world concepts.
class Dog: # Class attribute - shared by all instances species = "Canis familiaris"
# Constructor - called when creating new instance def __init__(self, name, age): # Instance attributes - unique to each object self.name = name self.age = age
# Instance method - functions that belong to objects def bark(self): return f"{self.name} says woof!"
# Special method - defines string representation def __str__(self): return f"{self.name} is {self.age} years old"
# Inheritance - creating specialized classesclass Bulldog(Dog): # Bulldog inherits from Dog def bark(self): # Override parent method return f"{self.name} says gruff woof!"
# Using classesmy_dog = Dog("Rex", 5) # Create instance (object)print(my_dog.bark()) # Call method: "Rex says woof!"print(my_dog) # Uses __str__: "Rex is 5 years old"
my_bulldog = Bulldog("Spike", 3)print(my_bulldog.bark()) # Uses overridden method: "Spike says gruff woof!"Key Points:
- Class: Blueprint for creating objects
- Object: Instance of a class
- Attributes: Variables that belong to objects
- Methods: Functions that belong to objects
- Inheritance: Creating new classes based on existing ones
- self: Reference to the current instance
File Handling
Section titled “File Handling”File handling allows your program to read from and write to files on your computer, enabling data persistence.
# Reading files - 'r' mode for readingwith open("file.txt", "r") as file: # 'with' automatically closes file content = file.read() # Read entire file as string # OR read line by line: # lines = file.readlines() # Returns list of lines
# Writing files - 'w' mode (overwrites existing content)with open("output.txt", "w") as file: file.write("Hello, World!\n") # Write string to file file.write("Second line\n")
# Appending to files - 'a' mode (adds to end)with open("output.txt", "a") as file: file.write("This line is appended\n")
# Reading line by line (memory efficient for large files)with open("large_file.txt", "r") as file: for line in file: # Read one line at a time print(line.strip()) # strip() removes newline charactersKey Points:
- open(): Function to open files
- Modes: ‘r’ (read), ‘w’ (write), ‘a’ (append)
- with statement: Ensures file is properly closed
- read(): Read entire file content
- readlines(): Read all lines into a list
- write(): Write strings to file
Error Handling
Section titled “Error Handling”Error handling prevents your program from crashing when unexpected situations occur. It makes your code more robust.
# Basic try-except blocktry: # Code that might cause an error number = int(input("Enter a number: ")) result = 10 / number print(f"10 divided by {number} is {result}")
except ValueError: # Handle specific error (non-number input) print("That's not a valid number!")
except ZeroDivisionError: # Handle division by zero print("You can't divide by zero!")
except Exception as e: # Catch any other unexpected errors print(f"An unexpected error occurred: {e}")
else: # Runs if no errors occurred print("Division completed successfully!")
finally: # Always runs, regardless of errors print("Execution completed.")
# Raising custom errorsdef validate_age(age): if age < 0: raise ValueError("Age cannot be negative!") if age > 150: raise ValueError("Age seems unrealistic!") return True
try: validate_age(-5)except ValueError as e: print(f"Validation error: {e}")Key Points:
- try: Code that might cause errors
- except: Handle specific types of errors
- else: Run if no errors occurred
- finally: Always execute (cleanup code)
- raise: Create custom errors
- Exception: Base class for all errors
Modules
Section titled “Modules”Modules are Python files containing reusable code. They help organize code into logical units and promote code reuse.
# Import entire moduleimport mathprint(math.sqrt(25)) # Use module_name.function_name
# Import specific functionsfrom math import sqrt, piprint(sqrt(25)) # Use function directlyprint(pi) # Use variable directly
# Import with aliasimport numpy as npimport pandas as pd
# Create your own module# Save this as my_module.py:"""# my_module.pydef greet(name): return f"Hello, {name}!"
def add(a, b): return a + b"""
# Then use it:import my_moduleprint(my_module.greet("Alice"))print(my_module.add(5, 3))
# Check what's in a moduleimport mathprint(dir(math)) # List all available functions/attributesKey Points:
- import: Bring entire module into your code
- from…import: Bring specific parts
- as: Create aliases for shorter names
- Modules promote code organization and reuse
- Python has extensive standard library modules
Useful Libraries
Section titled “Useful Libraries”Python’s power comes from its extensive ecosystem of libraries. Here are essential ones for different tasks.
Data Science Libraries
Section titled “Data Science Libraries”# NumPy - numerical computingimport numpy as nparray = np.array([1, 2, 3, 4, 5])print(array * 2) # [2, 4, 6, 8, 10] - vectorized operations
# Pandas - data manipulationimport pandas as pddata = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['NY', 'LA', 'Chicago']})print(data.head()) # Display first few rows
# Matplotlib - data visualizationimport matplotlib.pyplot as pltx = [1, 2, 3, 4, 5]y = [2, 4, 6, 8, 10]plt.plot(x, y)plt.xlabel('X axis')plt.ylabel('Y axis')plt.title('Simple Plot')# plt.show() # Uncomment to display plotWeb and API Libraries
Section titled “Web and API Libraries”# Requests - HTTP requestsimport requestsresponse = requests.get('https://api.github.com')print(response.status_code) # 200 means success# print(response.json()) # If response is JSON data
# Flask - web framework (simple example)from flask import Flaskapp = Flask(__name__)
@app.route('/')def home(): return 'Hello, World!'
# if __name__ == '__main__':# app.run(debug=True)Utility Libraries
Section titled “Utility Libraries”# datetime - date and time operationsfrom datetime import datetime, timedeltanow = datetime.now()print(now.strftime("%Y-%m-%d %H:%M:%S")) # Format datetomorrow = now + timedelta(days=1) # Add 1 day
# json - JSON data handlingimport jsondata = {'name': 'Alice', 'age': 30}json_string = json.dumps(data) # Convert to JSON stringparsed_data = json.loads(json_string) # Convert back to dictionary
# os - operating system interfaceimport oscurrent_dir = os.getcwd() # Get current directoryfiles = os.listdir('.') # List files in current directoryKey Points:
- NumPy: Efficient numerical computations
- Pandas: Data analysis and manipulation
- Matplotlib: Data visualization
- Requests: HTTP requests for APIs
- Flask/Django: Web development
- Install libraries using:
pip install library_name