- Variables and Data Types
- Control Flow
- Functions
- Collections
- List Comprehensions
- File Handling
- Modules and Packages
- Error Handling
- Classes and Objects
- Useful Libraries
- Decorators
- Generators
# Integer
x = 10
# Float
pi = 3.14
# String
name = "Python"
# Boolean
is_cool = True
# NoneType
nothing = None
# Convert to string
str_x = str(x)
# Convert to integer
int_pi = int(pi)
# Convert to float
float_x = float(x)
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
for i in range(5):
print(i)
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
count = 5
while count > 0:
print(count)
count -= 1
for i in range(10):
if i == 5:
break # Exit the loop
if i % 2 == 0:
continue # Skip the rest of the code in this iteration
print(i)
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
def greet(name="Guest"):
return f"Hello, {name}!"
print(greet())
def add(*args):
return sum(args)
print(add(1, 2, 3, 4))
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25)
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits)
# Accessing elements
print(fruits[1]) # Output: banana
# Slicing
print(fruits[1:3]) # Output: ['banana', 'cherry']
coordinates = (10, 20)
print(coordinates)
# Unpacking
x, y = coordinates
print(x, y)
unique_numbers = {1, 2, 3, 4, 4}
print(unique_numbers)
# Set operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b) # Intersection
print(a | b) # Union
print(a - b) # Difference
person = {"name": "Alice", "age": 25}
print(person["name"])
# Adding and updating
person["city"] = "New York"
person["age"] = 26
# Iterating over keys and values
for key, value in person.items():
print(f"{key}: {value}")
# Basic list comprehension
squares = [x**2 for x in range(10)]
print(squares)
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
with open("example.txt", "w") as file:
file.write("Hello, file!")
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open("example.txt", "a") as file:
file.write("\nAppend this line.")
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes trailing newline
import math
print(math.sqrt(16))
from math import pi
print(pi)
Create a file mymodule.py
:
def greet(name):
return f"Hello, {name}!"
Use the module:
import mymodule
print(mymodule.greet("Alice"))
pip install requests
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always run.")
class CustomError(Exception):
pass
try:
raise CustomError("An error occurred")
except CustomError as e:
print(e)
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
my_dog = Dog("Rex", 5)
print(my_dog.bark())
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def speak(self):
return f"{self.name} says woof!"
my_dog = Dog("Rex")
print(my_dog.speak())
class MyClass:
@classmethod
def class_method(cls):
return "Class method called"
@staticmethod
def static_method():
return "Static method called"
print(MyClass.class_method())
print(MyClass.static_method())
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())
import numpy as np
array = np.array([1, 2, 3, 4])
print(array * 2)
matrix = np.array([[1, 2], [3, 4]])
print(matrix)
print(matrix.T) # Transpose
import pandas as pd
data = {"name": ["Alice", "Bob"], "age": [25, 30]}
df = pd.DataFrame(data)
print(df)
# Basic operations
print(df.describe())
print(df[df["age"] > 25])
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.title("Simple Plot")
plt.show()
from sklearn.linear_model import LinearRegression
import numpy as np
# Sample data
X = np.array([[1], [2], [3], [4]])
y = np.array([1, 2, 3, 4])
# Create and train the model
model = LinearRegression()
model.fit(X, y)
# Make predictions
predictions = model.predict(np.array([[5]]))
print(predictions)
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
def decorator(cls):
class Wrapped(cls):
def __init__(self, *args, **kwargs):
print("Wrapped class")
super().__init__(*args, **kwargs)
return Wrapped
@decorator
class MyClass:
def __init__(self):
print("Original class")
instance = MyClass()
def countdown
(n):
while n > 0:
yield n
n -= 1
for number in countdown(5):
print(number)
squares = (x**2 for x in range(10))
for square in squares:
print(square)