A Comprehensive Guide to Mastering Python 3

Python is a high-level, interpreted, and general-purpose programming language renowned for its clear syntax and readability. Its design philosophy emphasizes code readability with its notable use of significant whitespace.

Table of Contents

2. Complete Python 3 Syntax Rules

Indentation

Python uses indentation (whitespace) to define code blocks. The standard is 4 spaces per indentation level.

if True: print("This is indented") # 4 spaces # print("This will cause an error") # Unindented incorrectly

Naming Conventions

Comments

# This is a single-line comment """ This is a multi-line comment. It spans several lines. """
Note: Code blocks are defined by indentation after a colon (:). Control flow statements like if, for, while, def, and class require a colon and an indented block.

3. Data Types and Data Structures

Numbers

Strings (str)

Immutable sequences of Unicode characters.

name = "Alice" age = 30 # f-string (modern and preferred) message = f"My name is {name} and I am {age} years old." # .format() message = "My name is {} and I am {} years old.".format(name, age)

Lists (list)

Mutable, ordered sequences.

my_list = [1, 2, 3, 'a'] my_list.append('new_item') print(my_list[0]) # Access first element

Tuples (tuple)

Immutable, ordered sequences. Faster than lists.

my_tuple = (1, 2, 3) # or my_tuple = 1, 2, 3

Dictionaries (dict)

Mutable, unordered collections of key-value pairs.

my_dict = {'name': 'Alice', 'age': 30} print(my_dict['name']) # Access by key my_dict['new_key'] = 'value' # Add new key-value pair

Sets (set)

Mutable, unordered collections of unique elements.

my_set = {1, 2, 3} my_set.add(4) print(my_set) # {1, 2, 3, 4}

4. Variables and Scope

A variable is only available from inside the region it is created. This is called scope.

x = "global" # Global scope def my_func(): global x # Now we can change the global 'x' x = "modified global" y = "local" # Local scope my_func() print(x) # Output: modified global # print(y) # This would cause a NameError

5. Control Structures

Conditional Statements

score = 85 if score >= 90: grade = 'A' elif score >= 80: grade = 'B' # This block executes else: grade = 'C' print(grade) # Output: B

Loops

for loop

for i in range(5): # Iterates 0 to 4 print(i) for item in [1, 2, 3]: print(item)

while loop

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

Comprehensions

# List Comprehension squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16] even_squares = [x**2 for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64] # Dict Comprehension square_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

6. Functions

Defining and Calling

def greet(name): # Definition return f"Hello, {name}!" message = greet("Bob") # Call print(message) # Output: Hello, Bob!

Parameters

def greet(name, message="Hi"): # 'message' has a default return f"{message}, {name}!" greet("Alice") # Uses default: "Hi, Alice!"

Variable-length Arguments

def log_values(*args, **kwargs): print("Positional:", args) print("Keyword:", kwargs) log_values(1, 2, 3, name='Alice', age=30) # Output: # Positional: (1, 2, 3) # Keyword: {'name': 'Alice', 'age': 30}

Lambda Expressions

square = lambda x: x ** 2 print(square(5)) # Output: 25 # Often used with sorted, filter, map names = ['Alice', 'bob', 'Charlie'] print(sorted(names, key=lambda x: x.lower())) # Case-insensitive sort

Recursion

def factorial(n): if n == 1: # Base case return 1 else: return n * factorial(n-1) # Recursive call print(factorial(5)) # Output: 120

7. Modules and Packages

Importing

import math # Import entire module from math import sqrt, pi # Import specific items from math import * # Import all (not recommended) import math as m # Import with alias
Standard Library Overview: Python's "batteries-included" philosophy provides rich modules like math, random, os, sys, datetime, json, csv, urllib, requests, and re.

8. File Input/Output

# The modern way: Context Managers (with statement) # Automatically closes the file, even if an error occurs. with open('file.txt', 'r') as file: content = file.read() # file.readlines() reads all lines into a list # for line in file: iterates line by line (memory efficient) with open('output.txt', 'w') as file: file.write("Hello, File!")

9. Exception Handling

try: numerator = 10 denominator = 0 result = numerator / denominator # This will raise a ZeroDivisionError except ZeroDivisionError: print("You can't divide by zero!") except FileNotFoundError as e: print(f"File not found: {e}") except Exception as e: # Catch any other exception print(f"An unexpected error occurred: {e}") else: print("This runs only if no exceptions occurred in the try block.") finally: print("This always runs, useful for cleanup.") # Raising exceptions if denominator == 0: raise ValueError("Denominator cannot be zero!") # Custom exceptions class MyCustomError(Exception): pass raise MyCustomError("This is a custom error message.")

10. Object-Oriented Programming (OOP)

class Dog: # Class Attribute species = "Canis familiaris" # Initializer / Instance Attributes def __init__(self, name, age): self.name = name # Instance attribute self.age = age # Instance Method def description(self): return f"{self.name} is {self.age} years old" # Another Instance Method def speak(self, sound): return f"{self.name} says {sound}" # Create an Object (Instance of Dog) my_dog = Dog("Rex", 5) print(my_dog.description()) # Output: Rex is 5 years old print(my_dog.speak("Woof")) # Output: Rex says Woof

Inheritance

class Terrier(Dog): # Inherits from Dog def speak(self, sound="Grrr"): # Method overriding return super().speak(sound) # Call parent method using super() jack = Terrier("Jack", 3) print(jack.speak()) # Output: Jack says Grrr

11. Advanced Topics

Generators

def countdown(n): print("Starting countdown!") while n > 0: yield n # Pauses here and returns n n -= 1 for num in countdown(5): # The function state is preserved between iterations print(num) # Output: 5, 4, 3, 2, 1

Decorators

def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator # Syntactic sugar for say_hello = my_decorator(say_hello) def say_hello(): print("Hello!") say_hello()

Regular Expressions

import re text = "My phone number is 123-456-7890." pattern = r'\d{3}-\d{3}-\d{4}' # Raw string with pattern match = re.search(pattern, text) if match: print("Phone number found:", match.group()) # Output: 123-456-7890

12. Working with External Libraries and APIs

pip install requests numpy pandas
import requests response = requests.get('https://api.github.com') if response.status_code == 200: data = response.json() # Parse JSON response print(data['current_user_url']) else: print('Failed to get data:', response.status_code)

13. Debugging and Testing

Debugging

import pdb; pdb.set_trace() # Set a breakpoint in your code

Testing with unittest

import unittest def add(a, b): return a + b class TestMathOperations(unittest.TestCase): def test_add(self): self.assertEqual(add(2, 3), 5) self.assertEqual(add(-1, 1), 0) if __name__ == '__main__': unittest.main()

14. Best Practices and PEP 8

Key PEP 8 Points:

  • Use 4 spaces per indentation level
  • Limit lines to 79 characters
  • Use blank lines to separate functions and classes
  • Use spaces around operators and after commas
  • Write descriptive names for variables, functions, and classes
  • Write docstrings for modules, functions, classes, and methods

15. Key Python Tools for Developers

Virtual Environments

python -m venv my_project_env source my_project_env/bin/activate # On macOS/Linux # my_project_env\Scripts\activate # On Windows

16. Overview of Popular Python Applications

Web Development

Data Science & Machine Learning

Automation & Scripting

Python excels at automating repetitive tasks, file management, web scraping, and sending emails.

17. Practical Examples and Exercises

18. Project Suggestions for Progressive Learning

Beginner Projects

Intermediate Projects

Advanced Projects

Happy Coding! Remember, the best way to learn Python is by practicing and building projects. Start with simple programs and gradually work your way up to more complex applications.