Introduction to Python #
Python is a high-level, interpreted programming language renowned for its simplicity, readability, and versatility. Created by Guido van Rossum and first released in 1991, Python has evolved into one of the most popular programming languages in the world, powering everything from web applications and data analysis to artificial intelligence and scientific computing.
What makes Python particularly appealing is its philosophy of code readability and simplicity. The language enforces clean, readable code through its use of indentation and straightforward syntax, making it an excellent choice for beginners while remaining powerful enough for advanced applications.
Core Python Concepts #
Syntax and Structure #
Python uses indentation to define code blocks, a unique approach that enforces clean, readable code. Unlike languages that use curly braces, Python’s indentation is syntactically significant:
# This is a single-line comment
def greet_user(name):
"""This is a docstring - Python's way of documenting functions"""
greeting = f"Hello, {name}!"
print(greeting)
return greeting
greet_user("World") # Outputs: Hello, World!Variables and Data Types #
Python is dynamically typed, meaning you don’t need to declare variable types explicitly. The interpreter determines the type at runtime:
Variable Declaration:
# Simple assignment
message = "Hello, Python!"
count = 42
price = 19.99
is_active = TruePython’s Built-in Data Types:
- Numeric Types:
integer_num = 42
float_num = 3.14159
complex_num = 3 + 4j # Complex numbers- Strings:
single_quote = 'Hello'
double_quote = "World"
triple_quote = """Multi-line
string"""
# F-strings (Python 3.6+)
name = "Alice"
greeting = f"Hello, {name}!" # Hello, Alice!- Boolean:
is_valid = True
is_complete = False- None Type:
empty_value = None # Represents absence of value- Collections:
Lists - Ordered, mutable sequences:
fruits = ['apple', 'banana', 'orange']
fruits.append('grape') # Add item
fruits[0] = 'mango' # Modify itemTuples - Ordered, immutable sequences:
coordinates = (10, 20, 30)
# coordinates[0] = 5 # This would raise an errorDictionaries - Key-value pairs:
person = {
'name': 'John',
'age': 30,
'city': 'New York'
}
print(person['name']) # John
person['email'] = 'john@example.com' # Add new keySets - Unordered collections of unique elements:
unique_numbers = {1, 2, 3, 4, 5}
unique_numbers.add(6)
unique_numbers.add(1) # No effect, 1 already existsFunctions #
Python supports multiple ways to define functions:
Basic Function:
def add(a, b):
return a + b
result = add(5, 3) # 8Default Parameters:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!Variable Arguments:
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 15Keyword Arguments:
def create_profile(**kwargs):
return kwargs
profile = create_profile(name="Alice", age=30, city="NYC")Lambda Functions:
square = lambda x: x ** 2
multiply = lambda x, y: x * y
print(square(5)) # 25
print(multiply(3, 4)) # 12Control Flow #
Conditional Statements:
temperature = 25
if temperature > 30:
print("It's hot!")
elif temperature > 20:
print("It's warm")
else:
print("It's cool")
# Ternary operator
status = "Adult" if age >= 18 else "Minor"Loops:
# For loop
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Iterate over list
colors = ['red', 'green', 'blue']
for color in colors:
print(color)
# While loop
count = 0
while count < 5:
print(count)
count += 1
# List comprehension
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Dictionary comprehension
squared_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Object-Oriented Programming #
Python fully supports object-oriented programming with classes and inheritance:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
print(f"{self.name} barks")
def fetch(self):
print(f"{self.name} is fetching")
dog = Dog("Rex", "German Shepherd")
dog.speak() # Rex barks
dog.fetch() # Rex is fetchingProperties and Encapsulation:
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:
raise ValueError("Radius cannot be negative")
self._radius = value
@property
def area(self):
return 3.14159 * self._radius ** 2
circle = Circle(5)
print(circle.area) # 78.53975
circle.radius = 10
print(circle.area) # 314.159Advanced Python Features #
Decorators #
Decorators are a powerful feature that allows you to modify function behavior:
def timer_decorator(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_decorator
def slow_function():
import time
time.sleep(1)
return "Done"
slow_function() # slow_function took 1.0001 secondsGenerators #
Generators allow you to create iterators efficiently:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci(10):
print(num) # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34Generator Expressions:
# Memory efficient - generates values on demand
squares_gen = (x**2 for x in range(1000000))Context Managers #
Context managers handle resource management safely:
# File handling with context manager
with open('file.txt', 'r') as file:
content = file.read()
# File is automatically closed
# Custom context manager
class DatabaseConnection:
def __enter__(self):
print("Opening connection")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Closing connection")
with DatabaseConnection() as db:
print("Using database")List Comprehensions and Functional Programming #
Python supports functional programming paradigms:
numbers = [1, 2, 3, 4, 5]
# Map
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]
# Filter
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
# Reduce
from functools import reduce
sum_all = reduce(lambda x, y: x + y, numbers) # 15
# List comprehension (more Pythonic)
squared = [x**2 for x in numbers]
evens = [x for x in numbers if x % 2 == 0]Type Hints (Python 3.5+) #
Type hints improve code readability and enable better tooling:
def greet(name: str) -> str:
return f"Hello, {name}!"
def calculate_total(prices: list[float]) -> float:
return sum(prices)
# Variable type hints
age: int = 30
scores: list[int] = [95, 87, 92]
user_data: dict[str, any] = {'name': 'Alice', 'age': 30}Async/Await (Asynchronous Programming) #
Python supports asynchronous programming for concurrent operations:
import asyncio
async def fetch_data(url):
print(f"Fetching {url}")
await asyncio.sleep(1) # Simulate network delay
return f"Data from {url}"
async def main():
tasks = [
fetch_data("https://api1.com"),
fetch_data("https://api2.com"),
fetch_data("https://api3.com")
]
results = await asyncio.gather(*tasks)
print(results)
# Run the async function
asyncio.run(main())Popular Python Libraries and Frameworks #
Data Science and Machine Learning #
- NumPy - Numerical computing with powerful array operations
- Pandas - Data manipulation and analysis
- Matplotlib & Seaborn - Data visualization
- Scikit-learn - Machine learning algorithms
- TensorFlow & PyTorch - Deep learning frameworks
Web Development #
- Django - Full-featured web framework
- Flask - Lightweight web framework
- FastAPI - Modern, fast web framework for building APIs
Automation and Scripting #
- Requests - HTTP library for API calls
- Beautiful Soup - Web scraping
- Selenium - Browser automation
File Handling #
# Writing to file
with open('output.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("Python is awesome!")
# Reading from file
with open('output.txt', 'r') as file:
content = file.read()
print(content)
# Reading line by line
with open('output.txt', 'r') as file:
for line in file:
print(line.strip())
# Working with JSON
import json
data = {'name': 'Alice', 'age': 30}
# Write JSON
with open('data.json', 'w') as file:
json.dump(data, file)
# Read JSON
with open('data.json', 'r') as file:
loaded_data = json.load(file)Error Handling #
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No errors occurred")
finally:
print("This always executes")
# Custom exceptions
class ValidationError(Exception):
pass
def validate_age(age):
if age < 0:
raise ValidationError("Age cannot be negative")
return agePackage Management #
Python uses pip for package management:
# Install package
pip install requests
# Install specific version
pip install requests==2.28.0
# Install from requirements file
pip install -r requirements.txt
# List installed packages
pip list
# Create requirements file
pip freeze > requirements.txtVirtual Environments #
Virtual environments isolate project dependencies:
# Create virtual environment
python -m venv myenv
# Activate (Windows)
myenv\Scripts\activate
# Activate (Unix/Mac)
source myenv/bin/activate
# Deactivate
deactivateBest Practices #
- Follow PEP 8 - Python’s style guide for readable code
- Use meaningful variable names that describe their purpose
- Write docstrings for functions and classes
- Keep functions small and focused on a single task
- Use list comprehensions for simple transformations
- Handle exceptions appropriately with try-except blocks
- Use virtual environments for project isolation
- Leverage built-in functions and standard library
- Write tests using pytest or unittest
- Use type hints for better code documentation
Common Python Idioms #
# Swap variables
a, b = b, a
# Multiple assignment
x, y, z = 1, 2, 3
# Unpacking
first, *middle, last = [1, 2, 3, 4, 5]
# Enumerate
for index, value in enumerate(['a', 'b', 'c']):
print(f"{index}: {value}")
# Zip
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# Dictionary get with default
config = {'host': 'localhost'}
port = config.get('port', 8080) # Returns 8080 if 'port' not in config
# String joining
words = ['Python', 'is', 'awesome']
sentence = ' '.join(words) # "Python is awesome"Conclusion #
Python’s combination of simplicity, versatility, and powerful features makes it an excellent language for beginners and experienced developers alike. Whether you’re building web applications, analyzing data, automating tasks, or developing machine learning models, Python provides the tools and ecosystem to bring your ideas to life.
The language continues to evolve with regular updates, introducing new features and improvements. By mastering the fundamentals covered in this guide and staying current with modern Python practices, you’ll be well-equipped to tackle any programming challenge that comes your way.
Happy coding!