1. Print to Console
print("Hello, World!")
2. Variables
x = 5
y = "Hello"
3. Data Types
x = 5 # int
y = 3.14 # float
z = "Hello" # str
a = True # bool
b = [1, 2, 3] # list
c = (1, 2, 3) # tuple
d = {"name": "John", "age": 30} # dict
4. Basic Operators
x = 5
y = 3
print(x + y) # addition
print(x - y) # subtraction
print(x * y) # multiplication
print(x / y) # division
print(x % y) # modulus
print(x ** y) # exponentiation
5. Comparison Operators
x = 5
y = 3
print(x == y) # equal
print(x != y) # not equal
print(x > y) # greater than
print(x < y) # less than
print(x >= y) # greater than or equal
print(x <= y) # less than or equal
6. Logical Operators
x = 5
y = 3
print(x > 2 and y < 4) # and
print(x > 2 or y < 4) # or
print(not x > 2) # not
7. Conditional Statements
x = 5
if x > 10:
print("x is greater than 10")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 10")
8. Loops
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
x = 0
while x < 5:
print(x)
x += 1
9. Functions
def greet(name):
print("Hello, " + name)
greet("John")
10. Lists
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # access first element
fruits.append("orange") # add element
fruits.remove("banana") # remove element
11. Tuples
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # access first element
12. Dictionaries
person = {"name": "John", "age": 30}
print(person["name"]) # access value
person["country"] = "USA" # add key-value pair
13. Sets
fruits = {"apple", "banana", "cherry"}
print(fruits) # print set
fruits.add("orange") # add element
fruits.remove("banana") # remove element
14. Modules
import math
print(math.pi) # access module function
15. File Input/Output
with open("example.txt", "r") as file:
print(file.read())
with open("example.txt", "w") as file:
file.write("Hello, World!")
16. Exception Handling
try:
x = 5 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed")
17. Classes and Objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
person = Person("John", 30)
person.greet()
18. Inheritance
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
student = Student("Alice", 20, "S123")
print(student.name, student.student_id)
19. List Comprehensions
squares = [x**2 for x in range(10)]
print(squares)
20. Lambda Functions
add = lambda x, y: x + y
print(add(5, 3))
21. Map Function
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)
22. Filter Function
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
23. Reduce Function
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)
24. String Formatting
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
25. Regular Expressions
import re
pattern = r"\d+"
result = re.findall(pattern, "There are 2 apples and 3 oranges.")
print(result)
26. JSON Handling
import json
data = '{"name": "John", "age": 30}'
person = json.loads(data)
print(person["name"])
27. Date and Time
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
28. List Slicing
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[1:3]) # ['banana', 'cherry']
29. Enumerate Function
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
30. Zip Function
names = ["John", "Alice", "Bob"]
ages = [30, 25, 22]
combined = list(zip(names, ages))
print(combined)
31. Any and All Functions
numbers = [1, 2, 3, 4]
print(any(x > 2 for x in numbers)) # True
print(all(x > 0 for x in numbers)) # True
32. Iterators and Generators
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)
33. Context Managers
class MyContext:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting the context")
with MyContext() as context:
print("Inside the context")
34. Property Decorators
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
person = Person("John")
print(person.name)
35. Static and Class Methods
class MyClass:
@staticmethod
def static_method():
print("Static method called")
@classmethod
def class_method(cls):
print("Class method called")
MyClass.static_method()
MyClass.class_method()
36. Type Hinting
def add(x: int, y: int) -> int:
return x + y
print(add(5, 3))
37. Type Checking
from typing import List, Dict
def process_data(data: List[Dict[str, int]]) -> None:
for item in data:
print(item)
process_data([{"a": 1}, {"b": 2}])
38. F-Strings
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
39. Command Line Arguments
import sys
print("Arguments:", sys.argv)
40. Multithreading
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
41. Multiprocessing
from multiprocessing import Process
def print_numbers():
for i in range(5):
print(i)
process = Process(target=print_numbers)
process.start()
process.join()
42. Decorators
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()
43. Assertions
x = 5
assert x > 0, "x should be positive"
44. Docstrings
def my_function():
"""This is a docstring."""
pass
print(my_function.__doc__)
45. List Comprehensions with Conditions
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)
46. String Methods
text = " Hello, World! "
print(text.strip()) # Remove whitespace
print(text.lower()) # Convert to lowercase
print(text.upper()) # Convert to uppercase
47. Dictionary Methods
person = {"name": "John", "age": 30}
print(person.keys()) # Get keys
print(person.values()) # Get values
48. Set Methods
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits)
49. String Joining
words = ["Hello", "World"]
sentence = " ".join(words)
print(sentence)
50. String Splitting
text = "Hello, World"
words = text.split(", ")
print(words)
51. List Sorting
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers)
52. List Reversing
numbers = [1, 2, 3]
numbers.reverse()
print(numbers)
53. Dictionary Comprehensions
squares = {x: x**2 for x in range(5)}
print(squares)
54. Set Comprehensions
squares = {x**2 for x in range(5)}
print(squares)
55. Using the `with` Statement
with open("example.txt", "w") as file:
file.write("Hello, World!")
56. Reading CSV Files
import csv
with open('data.csv', mode='r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
57. Writing CSV Files
import csv
with open('data.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["John", 30])
58. Using `requests` Library
import requests
response = requests.get('https://api.example.com/data')
print(response.json())
59. Using `requests` Library
import requests
response = requests.get('https://api.example.com/data')
print(response.json())
60. Using `BeautifulSoup` for Web Scraping
from bs4 import BeautifulSoup
import requests
response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.string)
61. Using `Pandas` for Data Analysis
import pandas as pd
data = pd.read_csv('data.csv')
print(data.head())
62. Using `NumPy` for Numerical Operations
import numpy as np
array = np.array([1, 2, 3])
print(np.mean(array))
63. Using `Matplotlib` for Plotting
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [4, 5, 6]
plt.plot(x, y)
plt.show()
64. Using `Seaborn` for Statistical Data Visualization
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
sns.barplot(x="day", y="total_bill", data=tips)
plt.show()
65. Using `Scikit-learn` for Machine Learning
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
X = [[1], [2], [3], [4]]
y = [1, 2, 3, 4]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = LinearRegression().fit(X_train, y_train)
print(model.predict(X_test))
66. Using `TensorFlow` for Deep Learning
import tensorflow as tf
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit([[1], [2], [3]], [1, 2, 3], epochs=10)
67. Using `Flask` for Web Development
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run()
68. Using `Django` for Web Development
# In views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
69. Using `SQLite` for Database Management
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)''')
conn.commit()
conn.close()
70. Using `pytest` for Testing
def test_add():
assert add(1, 2) == 3
71. Using `unittest` for Testing
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
if __name__ == '__main__':
unittest.main()
72. Using `logging` for Logging
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
73. Using `argparse` for Command Line Arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--name', help='Name of the user')
args = parser.parse_args()
print(f"Hello, {args.name}!")
74. Using `time` for Time Management
import time
time.sleep(1) # Sleep for 1 second
print("1 second later")
75. Using `random` for Random Number Generation
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
76. Using `math` for Mathematical Functions
import math
print (math.sqrt(16)) # Square root of 16
77. Using `os` for Operating System Interaction
import os
print(os.getcwd()) # Get current working directory
78. Using `sys` for System-Specific Parameters and Functions
import sys
print(sys.version) # Print Python version
79. Using `shutil` for File Operations
import shutil
shutil.copy('source.txt', 'destination.txt') # Copy file
80. Using `pickle` for Object Serialization
import pickle
data = {'name': 'John', 'age': 30}
with open('data.pkl', 'wb') as file:
pickle.dump(data, file)
81. Using `xml` for XML Parsing
import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
print(root.tag)
82. Using `csv` for CSV File Handling
import csv
with open('data.csv', mode='r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
83. Using `collections` for Specialized Container Data Types
from collections import Counter
count = Counter(['apple', 'banana', 'apple'])
print(count) # Count occurrences
84. Using `itertools` for Iterators
import itertools
for combination in itertools.combinations([1, 2, 3], 2):
print(combination)
85. Using `functools` for Higher-Order Functions
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10)) # Fibonacci of 10
86. Using `contextlib` for Context Managers
from contextlib import contextmanager
@contextmanager
def my_context():
print("Entering")
yield
print("Exiting")
with my_context():
print("Inside")
87. Using `socket` for Networking
import socket
s = socket.socket()
s.connect(('localhost', 8080))
s.send(b'Hello, World!')
s.close()
88. Using `threading` for Multithreading
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
89. Using `multiprocessing` for Parallel Processing
from multiprocessing import Process
def print_numbers():
for i in range(5):
print(i)
process = Process(target=print_numbers)
process.start()
process.join()
90. Using `asyncio` for Asynchronous Programming
import asyncio
async def main():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(main())
91. Using `pytest` for Testing
def test_add():
assert add(1, 2) == 3
92. Using `unittest` for Testing
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
if __name__ == '__main__':
unittest.main()
93. Using `logging` for Logging
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
94. Using `argparse` for Command Line Arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--name', help='Name of the user')
args = parser.parse_args()
print(f"Hello, {args.name}!")
95. Using `time` for Time Management
import time
time.sleep(1) # Sleep for 1 second
print("1 second later
96. Using `random` for Random Number Generation
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
97. Using `math` for Mathematical Functions
import math
print(math.sqrt(16)) # Square root of 16
98. Using `os` for Operating System Interaction
import os
print(os.getcwd()) # Get current working directory
99. Using `sys` for System-Specific Parameters and Functions
import sys
print(sys.version) # Print Python version
100. Using `shutil` for File Operations
import shutil
shutil.copy('source.txt', 'destination.txt') # Copy file