Short Notes On Python
Short Notes On Python
Python Overview
What is Python?
Python is a high-level, interpreted programming language known for its
simplicity and readability.
Key Features
Simple Syntax: Easy to learn and write.
Basic Syntax
Variables and Data Types
Variables: Store data values.
x = 5
y = "Hello, World!"
Common Data Types: int , float , str , bool , list , tuple , dict , set .
Control Structures
Conditional Statements: if , elif , else
if x > 0:
print("Positive")
elif x == 0:
for i in range(5):
print(i)
while x > 0:
print(x)
x -= 1
Functions
Defined using def keyword.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
Data Structures
Lists
Ordered, mutable collections.
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
print(my_list[2])
Tuples
Ordered, immutable collections.
my_tuple = (1, 2, 3)
Dictionaries
Key-value pairs, unordered.
Sets
Unordered collections of unique elements.
my_set = {1, 2, 3, 3}
print(my_set) # Output: {1, 2, 3}
Advanced Concepts
List Comprehensions
Concise way to create lists.
Exception Handling
Using try , except , finally blocks.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution complete")
def greet(self):
print(f"Hello, my name is {self.name}")
p = Person("Alice", 25)
p.greet()
import math
print(math.sqrt(16))
Creating Modules
Save Python code in .py file and import.
# in mymodule.py
def add(a, b):
return a + b
# in another file
from mymodule import add
print(add(3, 4))
Virtual Environments
Isolate project dependencies.
Popular Libraries
NumPy
Library for numerical computations.
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)
Pandas
Data manipulation and analysis.
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 3
0]})
print(df)
Matplotlib
Plotting and visualization.
Requests
HTTP library for making requests.
import requests
response = requests.get('<https://api.example.com/data>')
print(response.json())
def generate_numbers():
for i in range(5):
yield i
gen = generate_numbers()
for number in gen:
print(number)
Decorators
Functions that modify the behavior of other functions or methods.
def my_decorator(func):
def wrapper():
print("Something is happening before the function i
s called.")
func()
print("Something is happening after the function is
called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Context Managers
Manage resources using with statement.
Lambda Functions
Anonymous functions defined using lambda keyword.
square = lambda x: x ** 2
print(square(5))
my_list = [1, 2, 3]
iterator = iter(my_list)
print(next(iterator))
print(next(iterator))
File Handling
Reading and Writing Files
Use built-in functions open() , read() , write() , and close() .
# Writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, World!")
Regular Expressions
import re
Web Development
Flask
Micro web framework for building web applications.
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
Django
High-level web framework for building robust web applications.
# In views.py
def home(request):
return HttpResponse("Hello, Django!")
# In urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
]
Testing
Unit Testing
Using the unittest module.
import unittest
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(3, 4), 7)
if __name__ == '__main__':
unittest.main()
Mocking
Using the unittest.mock module.
Concurrency
Multithreading
Using the threading module for parallelism.
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
Multiprocessing
Using the multiprocessing module for true parallelism.
import multiprocessing
def print_numbers():
for i in range(5):
print(i)
process = multiprocessing.Process(target=print_numbers)
Asyncio
Asynchronous programming using the asyncio module.
import asyncio
asyncio.run(print_numbers())
Database Interaction
SQLite
Using the sqlite3 module to interact with SQLite databases.
import sqlite3
connection = sqlite3.connect('example.db')
cursor = connection.cursor()
# Create a table
cursor.execute('''CREATE TABLE users (id INTEGER PRIMARY KE
Y, name TEXT)''')
# Insert data
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
connection.commit()
# Query data
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())
SQLAlchemy
ORM (Object-Relational Mapping) for working with databases.
engine = create_engine('sqlite:///example.db')
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()