Python Cheat Sheet: The Basics
A quick reference for Python fundamentals, ideal for Data Science, AI, and Development learners.
Python Data Types
String
A sequence of characters stored as text.
my_string = "Hello"
Common operations:
my_string.upper() # Convert to uppercase
len(my_string) # Get length
my_string.find('l') # Find index of first 'l'
my_string.replace('H', 'C') # Replace 'H' with 'C'
Integer
Whole numbers.
my_integer = 12321
Float
Decimal numbers.
my_decimal = 3.14
Boolean
True or False values.
a = True b = False
Dictionary
Changeable collection of key-value pairs.
my_dictionary = {'banana': 1, 12: 'laptop', (0,0): 'center'}
my_dictionary['banana'] # Access value
my_dictionary.keys() # List of keys
my_dictionary.values() # List of values
Tuple
Unchangeable collection of objects.
tup = (1, 3.12, False, "Hi")
List
Changeable collection of objects.
my_collection = [1, 1, 3.12, False, "Hi"]
len(my_collection) # Length
my_collection.extend(["More", "Items"]) # Add multiple items
my_collection.append("Single") # Add single item
del(my_collection[2]) # Delete item at index 2
clone = my_collection[:] # Clone list
my_collection_3 = my_collection + ["a", "b", "c"] # Concatenate
sum([1,2,3,4.5]) # Sum numbers
item in my_collection # Check existence
item not in my_collection # Check non-existence
Set
Unordered collection of unique objects.
a = {100, 3.12, False, "Bye"}
b = {100, 3.12, "Welcome"}
my_set = set([1,1,2,3]) # Convert list to set
a.add(4) # Add item
a.remove("Bye") # Remove item
a.difference(b) # Set difference
a.intersection(b) # Set intersection
a.union(b) # Set union
a.issubset(b) # Subset check
a.issuperset(b) # Superset check
Indexing and Slicing
Access elements by position:
my_string[0] my_collection[1] my_tup[2]
Access a range of elements:
my_string[1:4] my_collection[0:3] my_tup[1:3]
Operators
Comparison Operators
- a == b : Equal
- a < b : Less Than
- a > b : Greater Than
- a >= b : Greater Than or Equal
- a <= b : Less Than or Equal
- a != b : Not Equal
Arithmetic Operators
- + : Addition
- - : Subtraction
- * : Multiplication
- / : Division
- // : Integer Division
Conditional Operators
- a and b : True if both are true
- a or b : True if either is true
- not a : Opposite of a
Control Flow
Loops
for x in range(5): # Loop 5 times
print(x)for item in iterable: # Loop through iterable
print(item)while condition: # Loop while condition is true
# code
Conditional Statements
if condition1:
# code
elif condition2:
# code
else:
# code
Try/Except
try:
# code
except ExceptionType:
# handle error
else:
# code if no error
Common Error Types
- IndexError : Index out of range
- NameError : Variable name not found
- SyntaxError : Code syntax error
- ZeroDivisionError : Division by zero
Range
Create sequences of numbers:
range(5) # 0,1,2,3,4 range(2, 10, 2) # 2,4,6,8
Webscraping
Using BeautifulSoup:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html5lib')
soup.prettify()
soup.find('tag')
soup.find_all('tag')
Requests
Using the requests library:
import requests
response = requests.get(url, params)
response.status_code
response.text
response.json()
requests.post(url, data)
Functions
Define and call functions:
def my_function(param1, param2):
# code
return resultoutput = my_function(arg1, arg2)
Working with Files
Reading:
file = open(file_name, "r")
content = file.read()
file.close()
Writing:
file = open(file_name, "w")
file.write(content)
file.close()
Objects and Classes
Define classes and create objects:
class MyClass:
def init(self, param1, param2):
self.attr1 = param1
self.attr2 = param2def method(self, param): return param
obj = MyClass(val1, val2)
obj.method(val3)
List Comprehensions:
squares = [x*x for x in range(10)]
Lambda Functions
add = lambda x, y: x + y
Importing Modules
import math from collections import Counter
Exception Handling: finally
try: # code finally: # always runs
With Statement (Context Managers)
with open('file.txt', 'r') as f: data = f.read()
Type Conversion
int('123')
str(123)
float('3.14')
list('abc')
Basic Numpy/Pandas Usage (for data science focus)
import numpy as np
import pandas as pd
arr = np.array([1,2,3])
df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
Virtual Environments
python -m venv myenv source myenv/bin/activate
Package Installation
pip install requests
Docstrings
def foo(): """This is a docstring.""" pass
Top comments (2)
Dope stuff, thanks a lot :)
Thanks man