0% found this document useful (0 votes)
78 views12 pages

Short Notes On Python

Uploaded by

webdeveloper2533
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views12 pages

Short Notes On Python

Uploaded by

webdeveloper2533
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Short notes on Python

Python Overview
What is Python?
Python is a high-level, interpreted programming language known for its
simplicity and readability.

Created by Guido van Rossum and first released in 1991.

Key Features
Simple Syntax: Easy to learn and write.

Interpreted: Executes code line by line.

Dynamically Typed: No need to declare variable types.

Object-Oriented: Supports classes and objects.

Extensive Libraries: Rich standard library and third-party modules.

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:

Short notes on Python 1


print("Zero")
else:
print("Negative")

Loops: for , while

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)

Short notes on Python 2


print(my_tuple[1])

Dictionaries
Key-value pairs, unordered.

my_dict = {"name": "Alice", "age": 25}


print(my_dict["name"])

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.

squares = [x**2 for x in range(10)]

Exception Handling
Using try , except , finally blocks.

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution complete")

Classes and Objects


Define classes using class keyword.

Short notes on Python 3


class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
print(f"Hello, my name is {self.name}")

p = Person("Alice", 25)
p.greet()

Modules and Packages


Importing Modules
Use import to include modules.

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.

python -m venv myenv


source myenv/bin/activate # On Windows use `myenv\\Scripts

Short notes on Python 4


\\activate`

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.

import matplotlib.pyplot as plt


plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

Requests
HTTP library for making requests.

import requests
response = requests.get('<https://api.example.com/data>')
print(response.json())

Short notes on Python 5


Advanced Topics
Generators
Functions that return an iterable set of items, one at a time, using yield .

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.

with open('file.txt', 'r') as file:


content = file.read()

Short notes on Python 6


print(content)

Lambda Functions
Anonymous functions defined using lambda keyword.

square = lambda x: x ** 2
print(square(5))

Iterators and Iterables


Objects that can be looped over (iterables) and objects that can keep track
of their position during iteration (iterators).

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!")

# Reading from a file


with open('example.txt', 'r') as file:
content = file.read()
print(content)

Regular Expressions

Short notes on Python 7


Using the re Module
Useful for pattern matching and string manipulation.

import re

pattern = r'\\d+' # Matches one or more digits


text = "There are 123 apples"

matches = re.findall(pattern, text)


print(matches)

Web Development
Flask
Micro web framework for building web applications.

from flask import Flask, render_template

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.

# Install Django using `pip install django`


# Create a project using `django-admin startproject myproje
ct`
# Create an app using `python manage.py startapp myapp`

# In views.py

Short notes on Python 8


from django.http import HttpResponse

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

def add(a, b):


return a + b

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.

from unittest.mock import MagicMock

# Example function that makes a network call

Short notes on Python 9


def get_data():
response = requests.get('<https://api.example.com/data
>')
return response.json()

# Mock the network call


requests.get = MagicMock(return_value=MagicMock(json=lambd
a: {"key": "value"}))
print(get_data())

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)

Short notes on Python 10


process.start()
process.join()

Asyncio
Asynchronous programming using the asyncio module.

import asyncio

async def print_numbers():


for i in range(5):
print(i)
await asyncio.sleep(1)

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())

Short notes on Python 11


connection.close()

SQLAlchemy
ORM (Object-Relational Mapping) for working with databases.

from sqlalchemy import create_engine, Column, Integer, Stri


ng
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

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()

# Add a new user


new_user = User(name='Alice')
session.add(new_user)
session.commit()

# Query the user


user = session.query(User).filter_by(name='Alice').first()
print(user.name)

Short notes on Python 12

You might also like