1. Python Basics
Python is a powerful and versatile programming language known for its simplicity and readability. Whether you’re a beginner or an experienced developer, mastering Python’s core concepts will help you efficiently write maintainable and scalable code.
1. Introduction to Python
Installation and Setup
Download Python from python.org. After installation, verify by typing:
python --version
Python Syntax
Python uses indentation to define blocks of code instead of braces or keywords. This makes the code more readable.
# A simple Python programname = "Python"print(f"Hello, {name}!")
2. Variables and Data Types
Variable Declaration
Variables in Python are dynamically typed. No need to declare types explicitly.
x = 5 # inty = 3.14 # floatname = "Alice" # str
Numeric Data Types
Python supports int
, float
, and complex
.
a = 10 # Integerb = 2.5 # Floatc = 1 + 2j # Complex number
Strings and String Operations
Strings are immutable sequences of characters. They support indexing, slicing, and various methods.
s = "Hello, World"print(s[0]) # 'H'print(s[1:5]) # 'ello'print(s.lower()) # 'hello, world'print(s.split(',')) # ['Hello', ' World']
Lists, Tuples, Sets, and Dictionaries
- Lists: Mutable, ordered sequences.
- Tuples: Immutable, ordered sequences.
- Sets: Unordered collections of unique elements.
- Dictionaries: Key-value pairs.
# Listmy_list = [1, 2, 3, 4]
# Tuplemy_tuple = (1, 2, 3)
# Setmy_set = {1, 2, 3, 4}
# Dictionarymy_dict = {'name': 'Alice', 'age': 25}
3. Control Flow
Conditional Statements
Python uses if
, elif
, and else
for conditional logic.
x = 10if x > 0: print("Positive")elif x == 0: print("Zero")else: print("Negative")
Loops
for
and while
loops allow iteration over sequences and conditional repetition.
# For loopfor i in range(5): print(i)
# While loopi = 0while i < 5: print(i) i += 1
Comprehensions
List, set, and dictionary comprehensions are a concise way to create collections.
# List comprehensionsquares = [x**2 for x in range(10)]
# Set comprehensionunique = {x % 3 for x in range(10)}
# Dictionary comprehensionsquare_dict = {x: x**2 for x in range(5)}
4. Functions and Scope
Function Declaration
Functions are defined using def
. They can take positional and keyword arguments.
def greet(name="World"): return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!print(greet()) # Output: Hello, World!
Lambda Functions
Anonymous functions can be created using lambda
.
add = lambda a, b: a + bprint(add(2, 3)) # Output: 5
Variable Scope
Python uses LEGB (Local, Enclosing, Global, Built-in) rule for scope resolution.
x = 10 # Global
def outer(): x = 5 # Enclosing
def inner(): nonlocal x x = 3 # Modify enclosing variable print(x) # Output: 3
inner() print(x) # Output: 3
5. Modules and Packages
Importing Modules
Python has a rich standard library. You can import modules using import
.
import math
print(math.sqrt(16)) # Output: 4.0
Writing Your Own Modules
Create a .py
file and import it in other scripts.
# In my_module.pydef say_hello(): print("Hello!")
# In another scriptfrom my_module import say_hellosay_hello()
Using pip
to Manage Packages
Use pip
to install and manage third-party packages.
pip install requests
6. Object-Oriented Programming
Classes and Objects
Classes are blueprints for creating objects.
class Dog: def __init__(self, name, breed): self.name = name self.breed = breed
def bark(self): return f"{self.name} says Woof!"
dog = Dog("Buddy", "Golden Retriever")print(dog.bark()) # Output: Buddy says Woof!
Inheritance and Polymorphism
Inheritance allows creating subclasses that inherit from a base class.
class Animal: def speak(self): raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal): def speak(self): return "Woof!"
class Cat(Animal): def speak(self): return "Meow!"
animals = [Dog(), Cat()]for animal in animals: print(animal.speak())
Magic Methods
Special methods like __init__
, __str__
, and __len__
can modify object behavior.
class Book: def __init__(self, title, author): self.title = title self.author = author
def __str__(self): return f"{self.title} by {self.author}"
book = Book("1984", "George Orwell")print(book) # Output: 1984 by George Orwell
7. Error Handling and Exceptions
try, except, finally
Handle errors using try
, except
, and finally
blocks.
try: result = 10 / 0except ZeroDivisionError as e: print("Error:", e)finally: print("This runs no matter what.")
Raising Exceptions
You can manually raise exceptions using raise
.
def check_age(age): if age < 0: raise ValueError("Age cannot be negative")
Custom Exceptions
You can create custom exception classes.
class MyCustomError(Exception): pass
raise MyCustomError("An error occurred!")
8. File I/O
Reading and Writing Files
Use open()
to handle file operations.
# Writing to a filewith open("test.txt", "w") as file: file.write("Hello, World!")
# Reading from a filewith open("test.txt", "r") as file: content = file.read() print(content)
Working with JSON and CSV Files
Pandas or the csv
and json
modules allow you to work with structured files.
import json
# JSONdata = {'name': 'Alice', 'age': 25}with open('data.json', 'w') as f: json.dump(data, f)
# Reading JSONwith open('data.json', 'r') as f: data = json.load(f)
9. Print in python
9.1 format()
method
In Python, the format()
method is used to format strings by inserting values into placeholders defined in the string. The placeholders are marked by curly braces {}
. Here’s how to use it:
1. Basic Usage
name = "Alice"age = 30formatted_string = "My name is {} and I am {} years old.".format(name, age)print(formatted_string)
Output:
My name is Alice and I am 30 years old.
2. Placeholder Indexing
You can use positional or keyword arguments to specify where to insert values.
Positional Arguments
formatted_string = "My name is {0} and I am {1} years old.".format("Bob", 25)print(formatted_string)
Output:
My name is Bob and I am 25 years old.
Keyword Arguments
formatted_string = "My name is {name} and I am {age} years old.".format(name="Charlie", age=35)print(formatted_string)
Output:
My name is Charlie and I am 35 years old.
3. Formatting Numbers
You can also format numbers, such as specifying decimal places.
pi = 3.14159formatted_pi = "Pi is approximately {:.2f}".format(pi)print(formatted_pi)
Output:
Pi is approximately 3.14
:.2f
: Formats the number to 2 decimal places.
4. Aligning Text
You can specify text alignment using the following syntax:
{:<}
: Left-align{:>}
: Right-align{:^}
: Center-align
formatted_text = "{:<10} | {:>10}".format("Left", "Right")print(formatted_text)
Output:
Left | Right
5. Using format()
with Dictionaries
You can also pass a dictionary to the format()
method using the **
unpacking operator.
person = {"name": "Diana", "age": 40}formatted_string = "My name is {name} and I am {age} years old.".format(**person)print(formatted_string)
Output:
My name is Diana and I am 40 years old.
The format()
method is versatile and useful for building readable and dynamic strings in Python.
10. Advanced Topics
Generators and Iterators
Generators are functions that yield values lazily, i.e., one at a time.
def count_up_to(max_value): counter = 1 while counter <= max_value
: yield counter counter += 1
for number in count_up_to(5): print(number)
Decorators
Decorators modify the behavior of a function or method.
def decorator(func): def wrapper(): print("Before the function runs") func() print("After the function runs") return wrapper
@decoratordef say_hello(): print("Hello!")
say_hello()
Context Managers
The with
statement simplifies resource management.
with open('test.txt', 'r') as file: data = file.read()
10. Working with Libraries
NumPy, Pandas, and Matplotlib
- NumPy: Efficient array operations.
- Pandas: Data manipulation with DataFrames.
- Matplotlib: Plotting and visualization.
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt
# NumPy arrayarr = np.array([1, 2, 3])
# Pandas DataFramedf = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
# Plottingplt.plot([1, 2, 3], [4, 5, 6])plt.show()
Flask and Django for Web Development
Python can be used to create web applications using frameworks like Flask and Django.
pip install flask
Key Takeaways
- Simplicity: Python is known for clean, readable code and powerful abstractions.
- Versatility: From web development (Flask, Django) to data science (Pandas, NumPy), Python is widely used.
- Object-Oriented and Functional Programming: Python supports multiple paradigms.
- Community and Libraries: Python’s vast ecosystem of libraries makes it ideal for rapid development.
- Interpreted and Dynamic: Python is dynamically typed and interpreted, making it suitable for quick scripting as well as large-scale systems.
By mastering these advanced Python topics, you’ll be equipped to build complex applications, perform efficient data analysis, and optimize your Python code for performance.