Python Tutorial
Python Tutorial
Python Tutorial
1. 🔤 Variables
Overview:
● Variables are containers for storing data values. Python dynamically assigns the variable
type based on the value.
Example:
Tip:
2. ➕ Operators
Overview:
Types:
Example:
x = 10
y = 5
result = x + y # Arithmetic: 15
is_equal = (x == y) # Comparison: False
is_greater_and_even = (x > y) and (x % 2 == 0) # Logical: True
Tip:
3. 🛠️ Functions
Overview:
Creating a Function:
def greet(name):
return f"Hello, {name}!"
Calling a Function:
Tip:
Example:
import math
result = math.sqrt(16) # Output: 4.0
Modules:
Creating a Module:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
Using a Module:
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!
Tip:
● 💡 Explore Python’s libraries and use modules to keep your code organized.
5. 📦 Packages
Overview:
Creating a Package:
Structure:
mypackage/
__init__.py
module1.py
module2.py
Tip:
6. 🧩 Methods
Overview:
● Methods are functions associated with objects. They operate on data contained in the
object.
Example:
Tip:
● 💡 Learn common methods for strings, lists, and dictionaries to streamline your
coding.
7. 🛠️ Refactoring
Overview:
● Refactoring improves the structure of existing code without changing its behavior.
Techniques:
● Extract Method: Move repeated code into a function.
● Rename Variable: Use descriptive variable names.
● Simplify Expressions: Break down complex expressions.
Example:
# Before Refactoring
result = (x + y) * z
# After Refactoring
def calculate_sum_and_multiply(x, y, z):
return (x + y) * z
Tip:
8. 🎨 Enum (Enumerations)
Overview:
● Enums are symbolic names for a set of values. They are used to define a fixed set of
constants.
Example:
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
Tip:
Example:
Dictionaries:
Example:
Sets:
Example:
unique_numbers = {1, 2, 3, 4, 5}
Tip:
● 💡 Use tuples for fixed data, dictionaries for key-value mapping, and sets for unique
collections.
Example:
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16]
Filter:
Example:
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
Reduce:
Example:
numbers = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, numbers) # Output: 10
Tip:
Creating a Class:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def drive(self):
return f"The {self.brand} {self.model} is driving."
Tip:
12. 🧰 Exceptions
Overview:
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
Tip:
● Method overloading allows defining multiple methods with the same name but different
parameters.
Example:
class Calculator:
def add(self, a, b, c=None):
if c:
return a + b + c
return a + b
calc = Calculator()
print(calc.add(5, 10)) # Output: 15
print(calc.add(5, 10, 15)) # Output: 30
Tip:
14. 🔄 Iterators
Overview:
Creating an Iterator:
numbers = [1, 2, 3]
iterator = iter(numbers)
print(next(iterator)) # Output: 1
print(next(iterator)) # Output: 2
Tip:
● 💡 Use for loops to iterate over iterables without manually handling iterators.
15. ⚙️ Generators
Overview:
Creating a Generator:
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for number in counter:
print(number)
Tip:
Example:
squares = [x**2 for x in range(10)]
Tip:
Example:
import re
Tip:
18. 🔄 Serialization
Overview:
● Serialization converts an object into a format that can be easily saved or transmitted.
Example:
import json
data = {"name": "Alice", "age": 25}
json_data = json.dumps(data)
loaded_data = json.loads(json_data)
Tip:
● Partial functions allow you to fix some arguments of a function and create a new
function.
Example:
double = partial(multiply, 2)
print(double(5)) # Output: 10
Tip:
20. 🔒 Closures
Overview:
● A closure is a function that remembers values in its enclosing scope even if they are not
present in memory.
Example:
def outer_function(msg):
def inner_function():
print(msg)
return inner_function
greet = outer_function("Hello")
greet() # Output: Hello
Tip:
21. 🎨 Decorators
Overview:
Creating a Decorator:
def my_decorator(func):
def wrapper():
print("Before the function.")
func()
print("After the function.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Tip:
● 💡 Use decorators to add reusable code functionality without modifying the original
function.
🚀
This comprehensive guide brings together essential concepts from Python’s beginner to
advanced levels, providing a solid foundation for mastering the language. Happy coding!