Python Cheatsheet
Python Cheatsheet
Python Cheatsheet
Open in app
441 6
01 Data Types
int_num = 42
float_num = 3.14
string_var = "Hello, Python!"
bool_var = True
02 Variables and Assignment
x = 10
y = "Python"
04 Dictionaries
05 Control Flow
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for item in my_list:
print(item)
while condition:
# code
06 Functions
def greet(name="User"):
return f"Hello, {name}!"
result = greet("John")
08 File Handling
09 Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")
import math
from datetime import datetime
result = math.sqrt(25)
current_time = datetime.now()
11 List Comprehensions
12 Lambda Functions
add = lambda x, y: x + y
result = add(2, 3)
13 Virtual Environment
14 Package Management
# Install a package
pip install package_name
# Create requirements.txt
pip freeze > requirements.txt
import json
16 Regular Expressions
import re
pattern = r'\d+' # Match one or more digits
result = re.findall(pattern, "There are 42 apples and 123 oranges.")
current_date = datetime.now()
future_date = current_date + timedelta(days=7)
18 List Manipulations
numbers = [1, 2, 3, 4, 5]
# Filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Map
squared = list(map(lambda x: x**2, numbers))
19 Dictionary Manipulations
# Dictionary comprehension
squared_dict = {key: value**2 for key, value in my_dict.items()}
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
21 Concurrency with Asyncio
import asyncio
async def print_numbers():
for i in range(5):
print(i)
await asyncio.sleep(1)
asyncio.run(print_numbers())
@app.route('/api/data', methods=['GET'])
def get_data():
data = {'key': 'value'}
return jsonify(data)
if __name__ == '__main__':
app.run(debug=True)
import unittest
# Commit changes
conn.commit()
# Close connection
conn.close()
26 File Handling
# Writing to a file
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
27 Error Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected Error: {e}")
else:
print("No errors occurred.")
finally:
print("This block always executes.")
import json
data = {'name': 'John', 'age': 30}
def decorator(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
@decorator
def my_function():
print("Inside the function")
my_function()
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
union_set = set1 | set2
# Intersection
intersection_set = set1 & set2
# Difference
difference_set = set1 - set2
32 List Comprehensions
numbers = [1, 2, 3, 4, 5]
33 Lambda Functions
add = lambda x, y: x + y
result = add(3, 5)
import gettext
# Set language
lang = 'en_US'
_ = gettext.translation('messages', localedir='locale', languages=[lang]).gettex
print(_("Hello, World!"))
36 Virtual Environment
# Format date
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
39 Regular Expressions
import re
text = "Hello, 123 World!"
# Match numbers
numbers = re.findall(r'\d+', text)
def square_numbers(n):
for i in range(n):
yield i**2
squares = square_numbers(5)
import sqlite3
import zipfile
with zipfile.ZipFile('archive.zip', 'w') as myzip:
myzip.write('file.txt')
with zipfile.ZipFile('archive.zip', 'r') as myzip:
myzip.extractall('extracted')
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
import smtplib
from email.mime.text import MIMEText
# Send email
msg = MIMEText('Hello, Python!')
msg['Subject'] = 'Python Email'
server.sendmail('[email protected]', '[email protected]', msg.as_string()
import json
data = {'name': 'John', 'age': 30}
222 Followers
Strong technical skills, such as coding, software engineering, data analysis, and project
management. Talk about finance, technology & life https://rb.gy/9tod91
66 1 40
8 min read · Aug 30, 2023 5 min read · Nov 14, 2023
1.8K 16 2.6K 29
Lists
4 min read · Nov 28, 2023 5 min read · Dec 26, 2023
931 7 205 1
430 5 180 1