Complete Python Course

Master the Language of Data Science and AI

1. Introduction to Python

Python is a high-level, interpreted programming language known for its simplicity and readability. Created by Guido van Rossum and first released in 1991, Python emphasizes code readability and allows programmers to express concepts in fewer lines of code.

Why Python?

Python Applications

Try Python:

Click to see Python in action!
🐍 Tip: Python follows the principle "There should be one obvious way to do it" - this makes code more readable and maintainable.

2. Python Basics

Your First Python Program

# This is a comment print("Hello, World!") print("Welcome to Python!") # Variables name = "Alice" age = 25 print(f"My name is {name} and I'm {age} years old")

Python Syntax Rules

Variables and Assignment

# Variable assignment x = 10 y = 20 z = x + y # Multiple assignment a, b, c = 1, 2, 3 # Swapping variables x, y = y, x # Constants (by convention, use UPPERCASE) PI = 3.14159 MAX_SIZE = 100

🏋️ Exercise 1:

Create variables for your name, age, and favorite color. Print a sentence using all three variables.

3. Data Types

Basic Data Types

# Numbers integer = 42 float_num = 3.14 complex_num = 2 + 3j # Strings single_quote = 'Hello' double_quote = "World" multiline = """This is a multiline string""" # Boolean is_true = True is_false = False # None (null value) nothing = None # Check type print(type(integer)) # print(type(float_num)) #

String Operations

name = "Python" # String methods print(name.upper()) # PYTHON print(name.lower()) # python print(name.capitalize()) # Python print(len(name)) # 6 # String formatting age = 25 message = f"I am {age} years old" # f-strings (Python 3.6+) message2 = "I am {} years old".format(age) # .format() message3 = "I am %d years old" % age # % formatting # String slicing text = "Hello, World!" print(text[0]) # H print(text[7:12]) # World print(text[:5]) # Hello print(text[7:]) # World! print(text[-1]) # !

Lists

# Creating lists fruits = ["apple", "banana", "orange"] numbers = [1, 2, 3, 4, 5] mixed = [1, "hello", 3.14, True] # List operations fruits.append("grape") # Add to end fruits.insert(1, "mango") # Insert at index fruits.remove("banana") # Remove by value popped = fruits.pop() # Remove and return last item # List slicing print(numbers[1:4]) # [2, 3, 4] print(numbers[:3]) # [1, 2, 3] print(numbers[2:]) # [3, 4, 5] # List comprehension squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25] evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]

Dictionaries

# Creating dictionaries person = { "name": "Alice", "age": 30, "city": "New York" } # Accessing values print(person["name"]) # Alice print(person.get("age")) # 30 print(person.get("country", "Unknown")) # Unknown (default) # Modifying dictionaries person["age"] = 31 # Update value person["country"] = "USA" # Add new key-value pair del person["city"] # Delete key-value pair # Dictionary methods print(person.keys()) # dict_keys(['name', 'age', 'country']) print(person.values()) # dict_values(['Alice', 31, 'USA']) print(person.items()) # dict_items([('name', 'Alice'), ...])

Tuples and Sets

# Tuples (immutable) coordinates = (10, 20) rgb = (255, 128, 0) single_item = (42,) # Note the comma # Tuple unpacking x, y = coordinates r, g, b = rgb # Sets (unique elements) numbers = {1, 2, 3, 4, 5} unique_letters = set("hello") # {'h', 'e', 'l', 'o'} # Set operations set1 = {1, 2, 3} set2 = {3, 4, 5} print(set1 | set2) # Union: {1, 2, 3, 4, 5} print(set1 & set2) # Intersection: {3} print(set1 - set2) # Difference: {1, 2}

4. Control Flow

Conditional Statements

# If statements age = 18 if age >= 18: print("You are an adult") elif age >= 13: print("You are a teenager") else: print("You are a child") # Ternary operator status = "adult" if age >= 18 else "minor" # Multiple conditions score = 85 if score >= 90 and score <= 100: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F"

Loops

# For loops fruits = ["apple", "banana", "orange"] # Iterate over list for fruit in fruits: print(fruit) # Iterate with index for i, fruit in enumerate(fruits): print(f"{i}: {fruit}") # Range function for i in range(5): # 0, 1, 2, 3, 4 print(i) for i in range(1, 6): # 1, 2, 3, 4, 5 print(i) for i in range(0, 10, 2): # 0, 2, 4, 6, 8 print(i) # While loops count = 0 while count < 5: print(f"Count: {count}") count += 1 # Loop control for i in range(10): if i == 3: continue # Skip this iteration if i == 7: break # Exit loop print(i)

Exception Handling

# Try-except blocks try: number = int(input("Enter a number: ")) result = 10 / number print(f"Result: {result}") except ValueError: print("Invalid input! Please enter a number.") except ZeroDivisionError: print("Cannot divide by zero!") except Exception as e: print(f"An error occurred: {e}") else: print("No errors occurred!") finally: print("This always executes") # Raising exceptions def validate_age(age): if age < 0: raise ValueError("Age cannot be negative") if age > 150: raise ValueError("Age seems unrealistic") return True

5. Functions

Defining Functions

# Basic function def greet(name): return f"Hello, {name}!" # Function with default parameters def greet_with_title(name, title="Mr."): return f"Hello, {title} {name}!" # Function with multiple parameters def calculate_area(length, width): return length * width # Function with variable arguments def sum_all(*args): return sum(args) # Function with keyword arguments def create_profile(**kwargs): profile = {} for key, value in kwargs.items(): profile[key] = value return profile # Using functions print(greet("Alice")) # Hello, Alice! print(greet_with_title("Bob", "Dr.")) # Hello, Dr. Bob! print(calculate_area(5, 3)) # 15 print(sum_all(1, 2, 3, 4, 5)) # 15 print(create_profile(name="Alice", age=30)) # {'name': 'Alice', 'age': 30}

Lambda Functions

# Lambda (anonymous) functions square = lambda x: x ** 2 add = lambda x, y: x + y print(square(5)) # 25 print(add(3, 4)) # 7 # Using lambda with built-in functions numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25] evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4] # Sorting with lambda students = [("Alice", 85), ("Bob", 90), ("Charlie", 78)] students.sort(key=lambda x: x[1]) # Sort by grade print(students) # [('Charlie', 78), ('Alice', 85), ('Bob', 90)]

Decorators

# Simple decorator def my_decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() # Output: # Before function call # Hello! # After function call # Decorator with arguments def timer(func): import time def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"{func.__name__} took {end - start:.4f} seconds") return result return wrapper @timer def slow_function(): import time time.sleep(1) return "Done!"

🏋️ Exercise 2:

Create a function that takes a list of numbers and returns a dictionary with the sum, average, minimum, and maximum values.

6. Object-Oriented Programming

Classes and Objects

# Basic class class Person: # Class variable species = "Homo sapiens" # Constructor def __init__(self, name, age): self.name = name # Instance variable self.age = age # Instance variable # Instance method def introduce(self): return f"Hi, I'm {self.name} and I'm {self.age} years old" # Instance method def have_birthday(self): self.age += 1 return f"Happy birthday! {self.name} is now {self.age}" # Class method @classmethod def get_species(cls): return cls.species # Static method @staticmethod def is_adult(age): return age >= 18 # Creating objects person1 = Person("Alice", 25) person2 = Person("Bob", 17) print(person1.introduce()) # Hi, I'm Alice and I'm 25 years old print(person1.have_birthday()) # Happy birthday! Alice is now 26 print(Person.is_adult(person2.age)) # False

Inheritance

# Parent class class Animal: def __init__(self, name, species): self.name = name self.species = species def make_sound(self): return "Some generic animal sound" def info(self): return f"{self.name} is a {self.species}" # Child class class Dog(Animal): def __init__(self, name, breed): super().__init__(name, "Dog") # Call parent constructor self.breed = breed def make_sound(self): # Override parent method return "Woof!" def fetch(self): return f"{self.name} is fetching the ball!" class Cat(Animal): def __init__(self, name, color): super().__init__(name, "Cat") self.color = color def make_sound(self): return "Meow!" def climb(self): return f"{self.name} is climbing a tree!" # Using inheritance dog = Dog("Buddy", "Golden Retriever") cat = Cat("Whiskers", "Orange") print(dog.info()) # Buddy is a Dog print(dog.make_sound()) # Woof! print(dog.fetch()) # Buddy is fetching the ball! print(cat.info()) # Whiskers is a Cat print(cat.make_sound()) # Meow! print(cat.climb()) # Whiskers is climbing a tree!

Encapsulation and Properties

class BankAccount: def __init__(self, account_number, initial_balance=0): self.account_number = account_number self._balance = initial_balance # Protected attribute self.__pin = None # Private attribute @property def balance(self): return self._balance @balance.setter def balance(self, amount): if amount < 0: raise ValueError("Balance cannot be negative") self._balance = amount def deposit(self, amount): if amount > 0: self._balance += amount return f"Deposited ${amount}. New balance: ${self._balance}" return "Invalid deposit amount" def withdraw(self, amount): if 0 < amount <= self._balance: self._balance -= amount return f"Withdrew ${amount}. New balance: ${self._balance}" return "Insufficient funds or invalid amount" def set_pin(self, pin): if len(str(pin)) == 4: self.__pin = pin return "PIN set successfully" return "PIN must be 4 digits" # Using the class account = BankAccount("123456789", 1000) print(account.deposit(500)) # Deposited $500. New balance: $1500 print(account.withdraw(200)) # Withdrew $200. New balance: $1300 print(account.balance) # 1300

7. Modules and Packages

Importing Modules

# Different ways to import import math import random as rand from datetime import datetime, timedelta from collections import * # Using imported modules print(math.pi) # 3.141592653589793 print(math.sqrt(16)) # 4.0 print(rand.randint(1, 10)) # Random number between 1 and 10 # Date and time now = datetime.now() tomorrow = now + timedelta(days=1) print(f"Today: {now.strftime('%Y-%m-%d')}") print(f"Tomorrow: {tomorrow.strftime('%Y-%m-%d')}") # Collections counter = Counter("hello world") print(counter) # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

Creating Your Own Module

# File: my_math.py def add(a, b): """Add two numbers""" return a + b def multiply(a, b): """Multiply two numbers""" return a * b def factorial(n): """Calculate factorial of n""" if n <= 1: return 1 return n * factorial(n - 1) PI = 3.14159 # File: main.py import my_math result = my_math.add(5, 3) print(f"5 + 3 = {result}") fact = my_math.factorial(5) print(f"5! = {fact}") print(f"PI = {my_math.PI}")

Popular Python Libraries

Essential Libraries:

  • requests: HTTP library for API calls
  • pandas: Data manipulation and analysis
  • numpy: Numerical computing
  • matplotlib: Data visualization
  • flask/django: Web frameworks
  • beautifulsoup4: Web scraping
  • pillow: Image processing
  • sqlite3: Database operations

8. File Handling

Reading and Writing Files

# Writing to a file with open("example.txt", "w") as file: file.write("Hello, World!\n") file.write("This is a test file.\n") # Reading from a file with open("example.txt", "r") as file: content = file.read() print(content) # Reading line by line with open("example.txt", "r") as file: for line in file: print(line.strip()) # strip() removes newline characters # Appending to a file with open("example.txt", "a") as file: file.write("This line is appended.\n") # Reading all lines into a list with open("example.txt", "r") as file: lines = file.readlines() print(lines)

Working with CSV Files

import csv # Writing CSV data = [ ["Name", "Age", "City"], ["Alice", 25, "New York"], ["Bob", 30, "Los Angeles"], ["Charlie", 35, "Chicago"] ] with open("people.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerows(data) # Reading CSV with open("people.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row) # Using DictReader for named columns with open("people.csv", "r") as file: reader = csv.DictReader(file) for row in reader: print(f"{row['Name']} is {row['Age']} years old")

Working with JSON

import json # Python dictionary person = { "name": "Alice", "age": 30, "city": "New York", "hobbies": ["reading", "swimming", "coding"] } # Writing JSON to file with open("person.json", "w") as file: json.dump(person, file, indent=2) # Reading JSON from file with open("person.json", "r") as file: loaded_person = json.load(file) print(loaded_person) # Converting to/from JSON strings json_string = json.dumps(person, indent=2) print(json_string) parsed_data = json.loads(json_string) print(parsed_data["name"]) # Alice

9. Popular Libraries

Requests - HTTP Library

import requests # GET request response = requests.get("https://api.github.com/users/octocat") if response.status_code == 200: data = response.json() print(f"User: {data['name']}") print(f"Public repos: {data['public_repos']}") # POST request data = {"name": "John", "email": "john@example.com"} response = requests.post("https://httpbin.org/post", json=data) print(response.json()) # With headers headers = {"Authorization": "Bearer your-token"} response = requests.get("https://api.example.com/data", headers=headers)

Pandas - Data Analysis

import pandas as pd # Creating a DataFrame data = { "Name": ["Alice", "Bob", "Charlie", "Diana"], "Age": [25, 30, 35, 28], "City": ["New York", "Los Angeles", "Chicago", "Houston"], "Salary": [50000, 60000, 70000, 55000] } df = pd.DataFrame(data) print(df) # Basic operations print(df.head()) # First 5 rows print(df.describe()) # Statistical summary print(df["Age"].mean()) # Average age print(df[df["Age"] > 30]) # Filter rows # Reading from CSV # df = pd.read_csv("data.csv") # Grouping and aggregation grouped = df.groupby("City")["Salary"].mean() print(grouped)

Matplotlib - Data Visualization

import matplotlib.pyplot as plt import numpy as np # Simple line plot x = np.linspace(0, 10, 100) y = np.sin(x) plt.figure(figsize=(10, 6)) plt.plot(x, y, label="sin(x)") plt.xlabel("x") plt.ylabel("y") plt.title("Sine Wave") plt.legend() plt.grid(True) plt.show() # Bar chart categories = ["A", "B", "C", "D"] values = [23, 45, 56, 78] plt.figure(figsize=(8, 6)) plt.bar(categories, values, color=["red", "green", "blue", "orange"]) plt.title("Bar Chart Example") plt.xlabel("Categories") plt.ylabel("Values") plt.show() # Scatter plot x = np.random.randn(100) y = np.random.randn(100) plt.figure(figsize=(8, 6)) plt.scatter(x, y, alpha=0.6) plt.title("Scatter Plot") plt.xlabel("X values") plt.ylabel("Y values") plt.show()

10. Practice Projects

Project 1: To-Do List Manager

class TodoList: def __init__(self): self.tasks = [] def add_task(self, task): self.tasks.append({"task": task, "completed": False}) print(f"Added: {task}") def complete_task(self, index): if 0 <= index < len(self.tasks): self.tasks[index]["completed"] = True print(f"Completed: {self.tasks[index]['task']}") else: print("Invalid task index") def remove_task(self, index): if 0 <= index < len(self.tasks): removed = self.tasks.pop(index) print(f"Removed: {removed['task']}") else: print("Invalid task index") def show_tasks(self): if not self.tasks: print("No tasks in the list") return for i, task in enumerate(self.tasks): status = "✓" if task["completed"] else "○" print(f"{i + 1}. {status} {task['task']}") # Usage todo = TodoList() todo.add_task("Learn Python") todo.add_task("Build a project") todo.add_task("Practice coding") todo.show_tasks() todo.complete_task(0) todo.show_tasks()

Project 2: Simple Calculator

class Calculator: def add(self, a, b): return a + b def subtract(self, a, b): return a - b def multiply(self, a, b): return a * b def divide(self, a, b): if b == 0: return "Error: Division by zero" return a / b def power(self, a, b): return a ** b def sqrt(self, a): if a < 0: return "Error: Cannot calculate square root of negative number" return a ** 0.5 def calculator_app(): calc = Calculator() while True: print("\n--- Calculator ---") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Power") print("6. Square Root") print("7. Exit") choice = input("Choose operation (1-7): ") if choice == "7": print("Goodbye!") break if choice in ["1", "2", "3", "4", "5"]: try: a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) if choice == "1": result = calc.add(a, b) elif choice == "2": result = calc.subtract(a, b) elif choice == "3": result = calc.multiply(a, b) elif choice == "4": result = calc.divide(a, b) elif choice == "5": result = calc.power(a, b) print(f"Result: {result}") except ValueError: print("Invalid input! Please enter numbers only.") elif choice == "6": try: a = float(input("Enter number: ")) result = calc.sqrt(a) print(f"Result: {result}") except ValueError: print("Invalid input! Please enter a number.") else: print("Invalid choice! Please try again.") # Uncomment to run # calculator_app()

🏋️ Project Ideas:

Build these projects to master Python:

  • Password Generator: Generate secure passwords with custom criteria
  • Weather App: Fetch weather data from an API
  • Web Scraper: Extract data from websites
  • Quiz Game: Multiple choice questions with scoring
  • File Organizer: Automatically organize files by type
  • Budget Tracker: Track income and expenses
  • URL Shortener: Create short URLs like bit.ly
  • Data Analyzer: Analyze CSV data with pandas

Next Steps

Advanced Python Topics:

  • Web Development: Django, Flask, FastAPI
  • Data Science: NumPy, Pandas, Matplotlib, Seaborn
  • Machine Learning: Scikit-learn, TensorFlow, PyTorch
  • GUI Development: Tkinter, PyQt, Kivy
  • Testing: unittest, pytest
  • Async Programming: asyncio, aiohttp
  • Database: SQLAlchemy, MongoDB