# Variable assignment
x = 10
name = "John"
# Variable reassignment
x = 20
# Multiple assignments
a, b, c = 1, 2, 3
# Constants (convention)
PI = 3.14
Integers:
Integers are whole numbers without any decimal point.
x = 10
y = -5
Floats:
Floats represent real numbers and include a decimal point.
pi = 3.14
gravity = 9.8
Strings:
Strings represent sequences of characters and are enclosed in single or double quotes.
You can perform various operations on strings, such as concatenation, slicing, and formatting.
name = "John"
message = 'Hello, world!'
# Concatenation
full_name = name + " Doe"
# Slicing
first_name = full_name[:4] # Output: John
# Formatting
formatted_message = f"Hello, {name}!" # Output: Hello, John!
Lists:
Lists are ordered collections of items, and they can contain elements of different data types. Lists are mutable, meaning they can be modified after creation.
You can perform various operations on lists, such as appending elements, accessing elements by index, and slicing.
my_list = [1, 2, 3, "a", "b", "c"]
# Appending elements
my_list.append(4) # Adds 4 to the end of the list
# Accessing elements by index
first_element = my_list[0] # Output: 1
# Slicing
subset = my_list[1:4] # Output: [2, 3, 'a']
Tuples:
Tuples are ordered collections of items, similar to lists, but they are immutable, meaning they cannot be modified after creation.
You can perform operations like accessing elements by index and slicing, but you cannot modify the tuple once it's created.
my_tuple = (1, 2, 3, "a", "b", "c")
# Accessing elements by index
first_element = my_tuple[0] # Output: 1
# Slicing
subset = my_tuple[1:4] # Output: (2, 3, 'a')
Dictionaries:
Dictionaries are unordered collections of key-value pairs, where each key is associated with a value. Dictionaries are mutable and can contain elements of different data types.
You can access values using keys, add new key-value pairs, and remove key-value pairs from dictionaries.
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
# Accessing values using keys
person_name = my_dict['name'] # Output: John
# Adding new key-value pairs
my_dict['occupation'] = 'Engineer'
# Removing key-value pairs
del my_dict['city']
Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations.
# Addition
result_addition = 10 + 5 # Output: 15
# Subtraction
result_subtraction = 10 - 5 # Output: 5
# Multiplication
result_multiplication = 10 * 5 # Output: 50
# Division
result_division = 10 / 5 # Output: 2.0 (always returns a float)
# Floor
Division result_floor_division = 10 // 3 # Output: 3 (returns integer quotient)
# Modulo
result_modulo = 10 % 3 # Output: 1 (returns remainder)
# Exponentiation
result_exponentiation = 2 ** 3 # Output: 8 (2 raised to the power of 3)
Comparison Operators:
Comparison operators are used to compare values.
# Equal to
is_equal = (10 == 5) # Output: False
# Not equal to
not_equal = (10 != 5) # Output: True
# Greater than
greater_than = (10 > 5) # Output: True
# Less than
less_than = (10 < 5) # Output: False
# Greater than or equal to
greater_than_equal = (10 >= 5) # Output: True
# Less than or equal to
less_than_equal = (10 <= 5) # Output: False
Logical Operators:
Logical operators are used to combine conditional statements.
x = 10
y = 5
# AND
logical_and = (x > 0) and (y < 10) # Output: True
# OR
logical_or = (x > 0) or (y > 10) # Output: True
# NOT
logical_not = not (x > 0) # Output: False
Assignment Operators:
Assignment operators are used to assign values to variables.
# Assignment
x = 10
# Addition assignment
x += 5 # Equivalent to x = x + 5
# Subtraction
assignment x -= 5 # Equivalent to x = x - 5
# Multiplication assignment
x *= 2 # Equivalent to x = x * 2
# Division assignment
x /= 2 # Equivalent to x = x / 2
# Modulo assignment
x %= 3 # Equivalent to x = x % 3
# Floor Division assignment
x //= 3 # Equivalent to x = x // 3
# Exponentiation assignment
x **= 2 # Equivalent to x = x ** 2
Membership Operators:
Membership operators are used to test if a sequence is present in an object.
# In
is_present = 'a' in ['a', 'b', 'c'] # Output: True
# Not In
is_not_present = 'd' not in ['a', 'b', 'c'] # Output: True
if Statement:
The if statement checks a condition and executes a block of code if the condition is true.
x = 10
if x > 5:
print("x is greater than 5")
if-else Statement:
The if-else statement executes one block of code if the condition is true and another block if the condition is false.
x = 3
if x % 2 == 0:
print("x is even")
else:
print("x is odd")
if-elif-else Statement:
The if-elif-else statement allows you to check multiple conditions and execute different blocks of code accordingly.
x = 0
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
for Loop:
The for loop iterates over a sequence (e.g., list, tuple, string) and executes a block of code for each item in the sequence.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
for i in range(5):
print(i)
while Loop:
The while loop executes a block of code as long as a specified condition is true.
x = 1
while x <= 5:
print(x)
x += 1
break:
Terminates the loop prematurely.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
continue:
Skips the current iteration of the loop and continues with the next iteration.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue
print(num)
else:
Executes a block of code when the loop completes normally (i.e., without encountering a break statement).
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
else:
print("Loop completed without breaking")
Defining Functions:
You can define a function in Python using the def keyword followed by the function name and parentheses containing any parameters the function takes. The function body is indented and contains the code to be executed when the function is called.
def greet():
print("Hello, world!")
def greet(name):
print("Hello, " + name + "!")
greet() # Output: Hello, world!
greet("John") # Output: Hello, John!
def add(x, y):
return x + y
result = add(3, 5)
print(result) # Output: 8
def greet(name="world"):
print("Hello, " + name + "!")
greet() # Output: Hello, world!
greet("John") # Output: Hello, John!
def greet(name, message):
print(message + ", " + name + "!")
greet(message="Good morning", name="John") # Output: Good morning, John!
def add(*args):
total = 0
for num in args:
total += num
return total
print(add(1, 2, 3, 4, 5)) # Output: 15
def greet(name):
" " "
Greets a person by name.
Parameters:
name (str): The name of the person to greet.
" " "
print("Hello, " + name + "!")
For example, let's create a module named math_operations.py:
# math_operations.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
You can then use this module in another Python script by importing it:
# main.py
import math_operations
result = math_operations.add(5, 3)
print(result) # Output: 8
result = math_operations.subtract(5, 3)
print(result) # Output: 2
For example, let's create a package named my_package:
my_package/
__init__.py
math_operations.py
string_operations.py
Inside math_operations.py, we have the same code as before. Now, let's create another module string_operations.py:
# string_operations.py
def concatenate_strings(str1, str2):
return str1 + str2
def capitalize_string(s):
return s.capitalize()
You can then use these modules from the package in your Python scripts:
# main.py
from my_package import math_operations, string_operations
result = math_operations.add(5, 3)
print(result) # Output: 8
result = string_operations.concatenate_strings("Hello, ", "world!")
print(result) # Output: Hello, world!
result = string_operations.capitalize_string("hello")
print(result) # Output: Hello
Importing Specific Functions:
You can import specific functions from modules or packages using the from ... import ... syntax.
# main.py
from math_operations import add
result = add(5, 3)
print(result) # Output: 8
Renaming Modules or Functions:
You can also rename modules or functions when importing them using the as keyword.
# main.py
from math_operations import add as addition
result = addition(5, 3)
print(result) # Output: 8
# Open a file for reading
file = open("example.txt", "r")
# Open a file for writing (creates a new file if it doesn't exist)
file = open("example.txt", "w")
# Open a file for appending (creates a new file if it doesn't exist)
file = open("example.txt", "a")
# Open a file in binary mode
file = open("example.txt", "rb")
# Read the entire contents of the file
content = file.read()
# Read a single line from the file
line = file.readline()
# Read all lines into a list
lines = file.readlines()
# Write content to the file
file.write("Hello, world!n")
# Write multiple lines to the file
file.writelines(["Line 1n", "Line 2n", "Line 3n"])
# Close the file
file.close()
with open("example.txt", "r") as file:
content = file.read()
# File is automatically closed when exiting the 'with' block
with open("binary_file.bin", "rb") as file:
data = file.read()
with open("new_binary_file.bin", "wb") as file:
file.write(data)
try:
with open("example.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found")
except Exception as e:
print("An error occurred:", e)
try:
# Code that may raise an exception
# ...
except SomeException:
# Code to handle the exception
# ...
try:
# Code that may raise an exception
x = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
# Handling the specific exception
print("Error: Division by zero occurred")
try:
# Code that may raise an exception
x = int("abc") # This will raise a ValueError
except ValueError:
# Handling a specific exception
print("Error: Invalid value provided")
except ZeroDivisionError:
# Handling another specific exception
print("Error: Division by zero occurred")
try:
# Code that may raise an exception
x = int("abc") # This will raise a ValueError
except ValueError:
# Handling a specific exception
print("Error: Invalid value provided")
except ZeroDivisionError:
# Handling another specific exception
print("Error: Division by zero occurred")
except:
# Handling any other exception
print("An error occurred")
try:
# Code that may raise an exception
x = 10 / 2
except ZeroDivisionError:
# Handling the specific exception
print("Error: Division by zero occurred")
else:
# Code to execute if no exceptions occur
print("No errors occurred, result:", x)
finally:
# Cleanup code that always runs
print("Cleanup code")
x = -1
if x < 0:
raise ValueError("x cannot be negative")
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."
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
print(person1.name) # Output: Alice
print(person2.age) # Output: 25
print(person1.greet()) # Output: Hello, my name is Alice and I am 30 years old.
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
# Polymorphic behavior
def animal_sound(animal):
return animal.make_sound()
dog = Dog()
cat = Cat()
print(animal_sound(dog)) # Output: Woof!
print(animal_sound(cat)) # Output: Meow!
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if self.__balance >= amount:
self.__balance -= amount
return amount
else:
return "Insufficient funds"
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
import re
pattern = r"hello"
text = "Hello, world! Hello, Python!"
matches = re.findall(pattern, text)
print(matches) # Output: ['hello', 'hello']
pattern = r"(w+), (w+)"
text = "Doe, John"
match = re.match(pattern, text)
if match:
print(match.group(1)) # Output: Doe
print(match.group(2)) # Output: John
pattern = r"d+"
text = "Age: 30"
new_text = re.sub(pattern, "25", text)
print(new_text) # Output: Age: 25
pattern = r"hello"
text = "Hello, world!"
match = re.search(pattern, text, re.IGNORECASE)
if match:
print("Pattern found")
import sqlite3
# Connect to an SQLite database (creates a new database if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
# Execute SQL command to create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
# Execute SQL command to insert data into the table
cursor.execute('''INSERT INTO users (name, age) VALUES (?, ?)''', ('Alice', 30))
# Commit the transaction
conn.commit()
# Execute SQL command to fetch data from the table
cursor.execute('''SELECT * FROM users''')
# Fetch all rows
rows = cursor.fetchall()
for row in rows:
print(row)
# Close the cursor and connection
cursor.close() conn.close()
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Create an engine
engine = create_engine('sqlite:///example.db')
# Create a sessionmaker
Session = sessionmaker(bind=engine)
# Create a session
session = Session()
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
# Create all defined tables
Base.metadata.create_all(engine)
# Create a new user object
new_user = User(name='Bob', age=25)
# Add the user to the session
session.add(new_user)
# Commit the transaction
session.commit()
# Query all users
users = session.query(User).all()
for user in users:
print(user.name, user.age)
# Close the session
session.close()
pip install beautifulsoup4
from bs4 import BeautifulSoup
import requests
# Send an HTTP request to the URL
url = 'https://example.com'
response = requests.get(url)
# Parse the HTML content
soup = BeautifulSoup(response.content, 'html.parser')
# Find all < a > tags
links = soup.find_all('a')
# Print the href attribute of each link
for link in links:
print(link.get('href'))
pip install scrapy
scrapy startproject myproject
cd myproject
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['https://example.com']
def parse(self, response):
# Extract data using XPath or CSS selectors
titles = response.css('h1::text').getall()
# Yield the extracted data
for title in titles:
yield {'title': title}
scrapy crawl myspider -o output.json