Published , Last updated
Python is one of the most popular and versatile programming languages in the world. Whether you're a beginner starting out or a seasoned developer looking to refresh your memory, this comprehensive Python Cheatsheet will guide you through every important concept from the basics to the most advanced techniques.
Python is a high-level, dynamically typed, interpreted programming language known for its readability and simplicity.
print("Hello, Python!")
x = 10
name = "Alice"
PI = 3.1415
#
for comments
# Numbers
int_num = 5
float_num = 3.14
# Strings
s = "hello"
# Boolean
flag = True
# None
nothing = None
# Arithmetic Operators: +, -, *, /, %, //, **
a = 10
b = 3
print("Arithmetic Operators:")
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333...
print(a % b) # Modulus: 1
print(a ** b) # Exponentiation: 1000
print(a // b) # Floor Division: 3
# Assignment Operators
x = 5
print("\nAssignment Operators:")
x += 3
print(x) # 8
x *= 2
print(x) # 16
x -= 6
print(x) # 10
# Comparison Operators: ==, !=, >, <, >=, <=
a = 5
b = 10
print("\nComparison Operators:")
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= b) # False
print(a <= b) # True
# Logical Operators: and, or, not
x = 5
y = 10
print("\nLogical Operators:")
print(x > 0 and y > 0) # True
print(x > 10 or y > 5) # True
print(not(x > 10)) # True
# Bitwise Operators
a = 5 # Binary: 0101
b = 3 # Binary: 0011
print("\nBitwise Operators:")
print(a & b) # 1 (AND)
print(a | b) # 7 (OR)
print(a ^ b) # 6 (XOR)
print(~a) # -6 (NOT)
print(a << 1) # 10 (Left Shift)
print(a >> 1) # 2 (Right Shift)
# Identity Operators
a = [1, 2]
b = a
c = [1, 2]
print("\nIdentity Operators:")
print(a is b) # True
print(a is c) # False
print(a is not c) # True
# Membership Operators
fruits = ['apple', 'banana', 'cherry']
print("\nMembership Operators:")
print('banana' in fruits) # True
print('grape' not in fruits) # True
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
# For loop
for i in range(5):
print(i)
# While loop
while x > 0:
x -= 1
def greet(name):
return f"Hello, {name}"
print(greet("Bob"))
# List
fruits = ["apple", "banana"]
# Tuple
coordinates = (10.0, 20.0)
# Set
unique = {1, 2, 3}
# Dictionary
person = {"name": "Alice", "age": 25}
s = "hello" print(s.upper()) # HELLO print(s[0:3]) # hel
squares = [x*x for x in range(5)]
import math
from datetime import datetime
try:
x = 1 / 0 except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")
with open("file.txt", "r") as f:
content = f.read()
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hi, I'm", self.name)
p = Person("Alice")
p.greet()
from functools import reduce
# Lambda
square = lambda x: x * x
# Map print(list(map(square, [1, 2, 3])))
# Filter print(list(filter(lambda x: x > 1, [0, 1, 2, 3])))
# Reduce print(reduce(lambda a, b: a + b, [1, 2, 3, 4]))
# Decorator
def my_decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@my_decorator
def say_hi():
print("Hi!")
say_hi()
# Generator
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print(x)
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
import json
import csv
# JSON
data = json.loads('{"name": "Bob"}')
# CSV
with open("data.csv") as f:
reader = csv.reader(f)
for row in reader:
print(row)
bash:
# Create venv
python -m venv venv
# Activate (Windows)
venv\Scripts\activate
# Install packages
pip install requests
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print(soup.title.text)
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello from Flask!"
bash:
pip install django
django-admin startproject mysite
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)
unittest.main()
Whether you're preparing for interviews, learning Python for data science, or building your own applications, this Python Cheatsheet is your go-to resource. Bookmark it, share it, and revisit often as you continue your Python journey.