course of python
-By RAHUL CHUABE
## 1. Introduction to Python
### 1.1 History and Features
- **History**: Python was created by Guido van Rossum and first released in 1991. It emphasizes code readability with its use of significant indentation.
- **Features**:
— **Easy Syntax**: Python syntax is clean and easy to learn.
— **Interpreted Language**: Python code is executed line by line.
— **Dynamically Typed**: Variables do not need an explicit declaration to reserve memory space.
— **Object-Oriented**: Supports OOP principles like inheritance, encapsulation, and polymorphism.
— **Extensive Standard Library**: Provides numerous modules and packages for various tasks.
### 1.2 Setting Up Python
- **Installation**: Download Python from the [official site](https://www.python.org/downloads/).
- **IDE Installation**: Popular choices include PyCharm, Visual Studio Code (VSCode), and Jupyter Notebook.
### 1.3 First Python Program
```python
print(“Hello, World!”)
```
- **Explanation**: This simple program uses the `print()` function to output the string “Hello, World!” to the console.
## 2. Basic Concepts
### 2.1 Variables and Data Types
- **Numeric Types**:
```python
a = 10 # int
b = 20.5 # float
c = 1 + 2j # complex
```
- **Text Type**:
```python
text = “Python”
```
- **Sequence Types**:
```python
lst = [1, 2, 3] # list
tpl = (1, 2, 3) # tuple
rng = range(5) # range
```
- **Mapping Type**:
```python
d = {‘key’: ‘value’} # dictionary
```
- **Set Types**:
```python
s = {1, 2, 3} # set
fs = frozenset([1, 2, 3]) # frozenset
```
- **Boolean Type**:
```python
flag = True
```
### 2.2 Operators
- **Arithmetic Operators**:
```python
addition = 5 + 3 # 8
subtraction = 5–3 # 2
multiplication = 5 * 3 # 15
division = 5 / 2 # 2.5
modulus = 5 % 2 # 1
exponentiation = 2 ** 3 # 8
```
- **Comparison Operators**:
```python
x = 10
y = 20
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= y) # False
print(x <= y) # True
```
- **Logical Operators**:
```python
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
```
- **Assignment Operators**:
```python
x = 10
x += 5 # x = x + 5, so x is now 15
x -= 3 # x = x — 3, so x is now 12
x *= 2 # x = x * 2, so x is now 24
x /= 4 # x = x / 4, so x is now 6.0
```
### 2.3 Control Flow
- **If-Else Statements**:
```python
age = 18
if age >= 18:
print(“Adult”)
else:
print(“Minor”)
```
- **For Loops**:
```python
for i in range(5):
print(i)
```
- **While Loops**:
```python
count = 0
while count < 5:
print(count)
count += 1
```
## 3. Functions
### 3.1 Defining Functions
```python
def greet(name):
return f”Hello, {name}!”
print(greet(“Alice”))
```
- **Explanation**: The function `greet()` takes one argument `name` and returns a greeting string.
### 3.2 Arguments and Return Values
- **Positional and Keyword Arguments**:
```python
def add(a, b):
return a + b
print(add(5, 3)) # Positional arguments
print(add(a=5, b=3)) # Keyword arguments
```
- **Default Arguments**:
```python
def power(base, exponent=2):
return base ** exponent
print(power(4)) # Uses default exponent 2
print(power(4, 3)) # Uses provided exponent 3
```
- **Variable-Length Arguments**:
```python
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4)) # Output: 10
```
### 3.3 Lambda Functions
```python
square = lambda x: x ** 2
print(square(5)) # Output: 25
```
- **Explanation**: Lambda functions are small anonymous functions defined with the `lambda` keyword.
### 3.4 Scope and Lifetime
- **Local and Global Variables**:
```python
x = 10 # Global variable
def func():
y = 5 # Local variable
print(x, y)
func()
print(x)
# print(y) # Error: y is not defined outside the function
```
## 4. Data Structures
### 4.1 Lists
- **Creation and Manipulation**:
```python
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
my_list[1] = 10 # [1, 10, 3, 4]
print(my_list)
```
- **Methods**:
```python
my_list = [1, 2, 3]
my_list.append(4)
my_list.remove(2) # [1, 3, 4]
```
### 4.2 Tuples
- **Immutability**:
```python
my_tuple = (1, 2, 3)
print(my_tuple[1]) # Output: 2
# my_tuple[1] = 10 # Error: tuple object does not support item assignment
```
### 4.3 Sets
- **Operations**:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2 # {1, 2, 3, 4, 5}
intersection = set1 & set2 # {3}
difference = set1 — set2 # {1, 2}
print(union, intersection, difference)
```
### 4.4 Dictionaries
- **Key-Value Pairs**:
```python
my_dict = {‘name’: ‘Alice’, ‘age’: 25}
print(my_dict[‘name’]) # Output: Alice
my_dict[‘age’] = 26
```
- **Methods**:
```python
my_dict = {‘name’: ‘Alice’, ‘age’: 25}
my_dict.keys() # dict_keys([‘name’, ‘age’])
my_dict.values() # dict_values([‘Alice’, 25])
```
## 5. Modules and Packages
### 5.1 Importing Modules
```python
import math
print(math.sqrt(16)) # Output: 4.0
```
### 5.2 Creating Your Own Modules
- **Example Module** (`mymodule.py`):
```python
def hello():
return “Hello from mymodule!”
```
- **Using the Module**:
```python
import mymodule
print(mymodule.hello())
```
### 5.3 Using `__init__.py` for Packages
- **Creating a Package**:
— Create a directory `mypackage/` with an `__init__.py` file.
— Add modules inside the package.
- **Importing from a Package**:
```python
from mypackage import mymodule
print(mymodule.hello())
```
## 6. File Handling
### 6.1 Reading and Writing Files
- **Writing to a File**:
```python
with open(‘file.txt’, ‘w’) as file:
file.write(“Hello, File!”)
```
- **Reading from a File**:
```python
with open(‘file.txt’, ‘r’) as file:
content = file.read()
print(content) # Output: Hello, File
!
```
### 6.2 Working with Different File Formats
- **CSV Files**:
```python
import csv
with open(‘data.csv’, ‘w’, newline=’’) as file:
writer = csv.writer(file)
writer.writerow([‘Name’, ‘Age’])
writer.writerow([‘Alice’, 30])
with open(‘data.csv’, ‘r’) as file:
reader = csv.reader(file)
for row in reader:
print(row)
```
- **JSON Files**:
```python
import json
data = {‘name’: ‘Alice’, ‘age’: 30}
with open(‘data.json’, ‘w’) as file:
json.dump(data, file)
with open(‘data.json’, ‘r’) as file:
content = json.load(file)
print(content)
```
## 7. Error Handling and Exceptions
### 7.1 Try, Except, Finally
```python
try:
result = 10 / 0
except ZeroDivisionError:
print(“Cannot divide by zero”)
finally:
print(“Execution completed”)
```
### 7.2 Custom Exceptions
- **Creating Custom Exceptions**:
```python
class CustomError(Exception):
pass
def check_value(x):
if x < 0:
raise CustomError(“Negative value is not allowed”)
try:
check_value(-1)
except CustomError as e:
print(e)
```
## 8. Object-Oriented Programming (OOP)
### 8.1 Classes and Objects
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f”Hello, my name is {self.name} and I am {self.age} years old.”
person = Person(“Alice”, 30)
print(person.greet())
```
### 8.2 Inheritance
```python
class Animal:
def speak(self):
return “Animal speaks”
class Dog(Animal):
def bark(self):
return “Woof!”
dog = Dog()
print(dog.speak()) # Inherited method
print(dog.bark()) # Child class method
```
### 8.3 Encapsulation
```python
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
```
### 8.4 Polymorphism
```python
class Bird:
def fly(self):
return “Flying in the sky”
class Penguin(Bird):
def fly(self):
return “Cannot fly, but can swim”
def make_it_fly(bird):
print(bird.fly())
sparrow = Bird()
penguin = Penguin()
make_it_fly(sparrow) # Flying in the sky
make_it_fly(penguin) # Cannot fly, but can swim
```
## 9. Advanced Topics
### 9.1 Decorators
```python
def decorator_function(original_function):
def wrapper_function():
print(“Wrapper executed”)
return original_function()
return wrapper_function
@decorator_function
def display():
return “Display function”
print(display())
```
### 9.2 Generators and Iterators
- **Generators**:
```python
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
for number in count_up_to(5):
print(number)
```
### 9.3 Context Managers
```python
class FileHandler:
def __enter__(self):
self.file = open(‘file.txt’, ‘w’)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
with FileHandler() as file:
file.write(“Hello, Context Manager!”)
```
### 9.4 Regular Expressions
```python
import re
pattern = r’\d+’
text = ‘There are 12 apples and 34 oranges.’
matches = re.findall(pattern, text)
print(matches) # Output: [‘12’, ‘34’]
```
## 10. Libraries and Frameworks
### 10.1 Popular Libraries
- **NumPy**: For numerical operations.
```python
import numpy as np
arr = np.array([1, 2, 3])
print(arr.mean()) # Output: 2.0
```
- **Pandas**: For data manipulation and analysis.
```python
import pandas as pd
data = {‘Name’: [‘Alice’, ‘Bob’], ‘Age’: [25, 30]}
df = pd.DataFrame(data)
print(df)
```
- **Matplotlib**: For plotting.
```python
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
```
- **Requests**: For making HTTP requests.
```python
import requests
response = requests.get(‘https://api.github.com')
print(response.json())
```
### 10.2 Web Frameworks
- **Flask**: A micro web framework.
```python
from flask import Flask
app = Flask(__name__)
@app.route(‘/’)
def home():
return “Hello, Flask!”
if __name__ == ‘__main__’:
app.run()
```
- **Django**: A full-fledged web framework.
— Create a project: `django-admin startproject myproject`
— Create an app: `python manage.py startapp myapp`
— Define models, views, and templates in the app.
### 10.3 Data Science and Machine Learning
- **Scikit-Learn**: For machine learning.
```python
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
data = load_iris()
kmeans = KMeans(n_clusters=3)
kmeans.fit(data.data)
print(kmeans.labels_)
```
- **TensorFlow/Keras**: For deep learning.
```python
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential()
model.add(Dense(10, input_dim=8, activation=’relu’))
model.add(Dense(1, activation=’sigmoid’))
model.compile(optimizer=’adam’, loss=’binary_crossentropy’)
```
## 11. Testing and Debugging
### 11.1 Unit Testing with `unittest`
```python
import unittest
def add(a, b):
return a + b
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
self.assertNotEqual(add(1, 2), 4)
if __name__ == ‘__main__’:
unittest.main()
```
### 11.2 Debugging Techniques
- **Using `pdb`**:
```python
import pdb
def divide(a, b):
pdb.set_trace()
return a / b
divide(10, 0)
```
- **IDE Debuggers**: Most IDEs come with built-in debuggers to set breakpoints, inspect variables, and step through code.
## 12. Best Practices and Design Patterns
### 12.1 Code Readability and Style
- **PEP 8 Guidelines**: Follow Python’s style guide to ensure readability.
— Use 4 spaces for indentation.
— Limit lines to 79 characters.
— Use descriptive variable names.
### 12.2 Common Design Patterns
- **Singleton**:
```python
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
```
- **Factory**:
```python
class Dog:
def speak(self):
return “Woof!”
class Cat:
def speak(self):
return “Meow!”
def get_animal(animal_type):
if animal_type == ‘dog’:
return Dog()
elif animal_type == ‘cat’:
return Cat()
```
- **Observer**:
```python
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
class Observer:
def update(self, message):
print(f”Received message: {message}”)
subject = Subject()
observer = Observer()
subject.attach(observer)
subject.notify(“Hello Observers!”)
```
## 13. Projects and Applications
### 13.1 Building Real-world Projects
- **Web Application**: Use Flask or Django to build a web application.
- **Data Analysis**: Use Pandas and Matplotlib to analyze and visualize data.
- **Automation Scripts**: Automate repetitive tasks using Python scripts.
## 14. Resources and Further Learning
### 14.1 Recommended Books and Tutorials
- **Books**:
— *”Python Crash Course”* by Eric Matthes
— *”Automate the Boring Stuff with Python”* by Al Sweigart
### 14.2 Online Courses and Communities
- **Courses**:
— Coursera, edX, Udacity
- **Communities**:
— Stack Overflow, Reddit’s r/learnpython
### 14.3 Contributing to Open Source Projects
- **Find Projects**: GitHub is a great place to find open-source Python projects.
- **Contribute**: Read the contributing guidelines of a project, submit pull requests, and participate in discussions.
This detailed explanation should cover the core topics of Python, providing you with a solid foundation for learning and using Python effectively.