Introduction
Python is a popular and easy-to-learn programming language. It is used in many fields such as web development, data analysis, automation, artificial intelligence, and more. This cheatsheet covers the most important and commonly used concepts in Python. It is helpful for beginners and also for experienced developers who want to revise the basics quickly.
1. Variables
name = "Alice"
age = 25
2. Data Types
Common types : int
, float
, str
, bool
, list
, tuple
, dict
, set
num = 10 # int
price = 5.5 # float
name = "Tom" # str
is_valid = True # bool
3. Lists
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[1]) # banana
4. Tuples
colors = ("red", "green", "blue")
print(colors[0]) # red
5. Dictionaries
student = {"name": "John", "age": 20}
print(student["name"]) # John
6. Sets
nums = {1, 2, 3, 2}
print(nums) # {1, 2, 3}
7. Conditional Statements
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
8. Loops
for i in range(5):
print(i)
count = 0
while count < 5:
print(count)
count += 1
9. Functions
def greet(name):
print("Hello", name)
greet("Alice")
10. Classes and Objects
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hi, I am", self.name)
p = Person("David")
p.say_hello()
11. Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
12. List Comprehension
squares = [x*x for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
13. Importing Modules
import math
print(math.sqrt(16)) # 4.0
14. File Handling
with open("file.txt", "r") as f:
content = f.read()
with open("file.txt", "w") as f:
f.write("Hello, world")
15. Lambda Functions
add = lambda x, y: x + y
print(add(3, 5)) # 8
16. Map, Filter, Reduce
nums = [1, 2, 3]
squared = list(map(lambda x: x*x, nums))
even = list(filter(lambda x: x % 2 == 0, nums))
from functools import reduce
total = reduce(lambda x, y: x + y, nums)
17. Global and Local Variables
x = 10 # global
def test():
y = 5 # local
print(x + y)
test()
18. String Formatting
name = "Tom"
age = 20
print(f"My name is {name} and I am {age} years old.")
19. Type Conversion
x = "123"
y = int(x) # converts to integer
20. Built-in Functions
Some common ones: len()
, type()
, str()
, int()
, input()
, print()
, sum()
, sorted()
21. Enumerate
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)
22. Zip
names = ["Alice", "Bob"]
scores = [85, 90]
for name, score in zip(names, scores):
print(name, score)
23. Docstrings
def greet():
"""This function prints a greeting"""
print("Hello")
24. args and kwargs
def add(*args):
return sum(args)
def show(**kwargs):
print(kwargs)
add(1, 2, 3)
show(name="Tom", age=30)
25. Virtual Environment (venv)
python -m venv env
26. List Methods
a = [1, 2, 3]
a.append(4)
a.remove(2)
a.pop()
a.sort()
a.reverse()
27. Dictionary Methods
d = {"a": 1, "b": 2}
d.keys()
d.values()
d.items()
d.get("a")
28. Comprehensions with Conditions
evens = [x for x in range(10) if x % 2 == 0]
29. Range
range(5) # 0 to 4
range(1, 6) # 1 to 5
range(1, 10, 2) # step by 2
30. Type Hints (Python 3.5+)
def add(x: int, y: int) -> int:
return x + y
31. Unpacking
a, b = [1, 2]
32. Ternary Operator
result = "Yes" if x > 5 else "No"
33. Chained Comparisons
x = 10
if 5 < x < 15:
print("x is between 5 and 15")
34. Generators
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
35. Decorators
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@decorator
def greet():
print("Hello")
greet()
36. Context Manager (with statement)
with open("file.txt") as f:
data = f.read()
37. Assertions
x = 5
assert x > 0, "x must be positive"
38. The __name__ == "__main__"
Block
if __name__ == "__main__":
print("Running directly")
39. Using pass
, break
, continue
for i in range(5):
if i == 3:
continue
print(i)
40. Global Keyword
x = 10
def modify():
global x
x = 20
41. is
vs ==
a = [1, 2]
b = [1, 2]
print(a == b) # True
print(a is b) # False
42. Python Comments
"""
This is
a multiline comment
"""
43. Command Line Arguments with sys.argv
import sys
print(sys.argv[1]) # First command-line argument
44. Using dir()
and help()
dir(str)
help(str)
45. Using __init__
and __str__
in Classes
class Car:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Car name: {self.name}"
46. Private Variables (by Convention)
class Example:
def __init__(self):
self._protected = "Warning only"
self.__private = "Strongly private"
47. Python Slicing
text = "abcdef"
print(text[1:4]) # 'bcd'
print(text[:3]) # 'abc'
print(text[::-1]) # reverse string
48. Set Operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
print(a.intersection(b)) # {3}
print(a.difference(b)) # {1, 2}
49. Using all()
and any()
nums = [1, 2, 3]
print(all(x > 0 for x in nums)) # True
print(any(x > 2 for x in nums)) # True
50. Chained Function Calls
def add(x):
return x + 1
def multiply(x):
return x * 2
print(multiply(add(3))) # 8
51. NamedTuple (from collections
)
from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(1, 2)
print(p.x, p.y)
52. Defaultdict
from collections import defaultdict
d = defaultdict(int)
d["a"] += 1
print(d) # defaultdict(<class 'int'>, {'a': 1})
53. Counter
from collections import Counter
c = Counter("banana")
print(c) # {'a': 3, 'n': 2, 'b': 1}
54. Date and Time
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))
55. Regular Expressions (Regex)
import re
text = "abc123"
match = re.search(r"\d+", text)
print(match.group()) # 123
56. JSON Handling
import json
data = {"name": "Tom", "age": 20}
json_str = json.dumps(data)
parsed = json.loads(json_str)
57. Using __slots__
(Memory Optimization in Classes)
class Person:
__slots__ = ['name', 'age']
def __init__(self, name, age):
self.name = name
self.age = age
58. Using type()
to Create Classes Dynamically
MyClass = type("MyClass", (object,), {"x": 5})
obj = MyClass()
print(obj.x)
59. Using eval()
and exec()
x = 10
print(eval("x + 5")) # 15
⚠️ Avoid using eval()
or exec()
with user input due to security risks.
60. Unit Testing (with unittest
)
import unittest
class TestAdd(unittest.TestCase):
def test_sum(self):
self.assertEqual(2 + 3, 5)
if __name__ == "__main__":
unittest.main()
Conclusion
If you're serious about mastering Python:
For backend development: Learn Flask
, FastAPI
, or Django
.
For data work: Learn NumPy
, Pandas
, Matplotlib
, Seaborn
.
For automation: Learn Selenium
, PyAutoGUI
, Requests
.
For testing: Learn pytest
.
This is now a complete Python cheatsheet for practical use, projects, interviews, and continued learning.