0% found this document useful (0 votes)
31 views3 pages

Python Cheatsheet

The document provides a comprehensive overview of Python programming concepts, including data types, variables, functions, loops, and file operations. It emphasizes the use of strings, numbers, and collections, along with examples of operations and methods. Additionally, it highlights best practices for coding and offers resources for further learning on Python.

Uploaded by

Huy Bach
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views3 pages

Python Cheatsheet

The document provides a comprehensive overview of Python programming concepts, including data types, variables, functions, loops, and file operations. It emphasizes the use of strings, numbers, and collections, along with examples of operations and methods. Additionally, it highlights best practices for coding and offers resources for further learning on Python.

Uploaded by

Huy Bach
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Data Types Strings Numbers & Math

Real Python Python is dynamically typed It’s recommended to use double-quotes for strings Arithmetic Operators
Pocket Reference Use None to represent missing or optional values Use "\n" to create a line break in a string
10 + 3 # 13
Use type() to check object type To write a backslash in a normal string, write "\\" 10 - 3 # 7
Visit realpython.com to Check for a specific type with isinstance() 10 * 3 # 30
issubclass() checks if a class is a subclass Creating Strings 10 / 3 # 3.3333333333333335
turbocharge your 10 // 3 # 3
single = 'Hello'
Python learning with Type Investigation double = "World"
10 % 3
2 ** 3
#
#
1
8
in‑depth tutorials, type(42) # <class 'int'> multi = """Multiple
line string"""
real‑world examples, type(3.14)
type("Hello")
#
#
<class
<class
'float'>
'str'> Useful Functions
and expert guidance. type(True) # <class 'bool'>
String Operations abs(-5) # 5
type(None) # <class 'NoneType'>
round(3.7) # 4
greeting = "me" + "ow!" # "meow!" round(3.14159, 2) # 3.14
isinstance(3.14, float) # True
repeat = "Meow!" * 3 # "Meow!Meow!Meow!" min(3, 1, 2) # 1
issubclass(int, object) # True - everything inherits from object
length = len("Python") # 6 max(3, 1, 2) # 3
Getting Started sum([1, 2, 3]) # 6
Type Conversion String Methods
Follow these guides to kickstart your Python journey: int("42") # 42 "a".upper() # "A" Learn More on realpython.com/search:
realpython.com/what-can-i-do-with-python float("3.14") # 3.14 "A".lower() # "a" math ∙ operators ∙ built in functions
realpython.com/installing-python str(42) # "42" " a ".strip() # "a"
realpython.com/python-first-steps bool(1) # True "abc".replace("bc", "ha") # "aha"
list("abc") # ["a", "b", "c"] "a b".split() # ["a", "b"] Conditionals
"-".join(["a", "b"]) # "a-b"
Start the Interactive Shell
Learn More on realpython.com/search: Python uses indentation for code blocks
$ python data types ∙ type checking ∙ isinstance ∙ issubclass String Indexing & Slicing Use 4 spaces per indentation level

text = "Python"
Quit the Interactive Shell text[0] # "P" (first) If-Elif-Else
Variables & Assignment
>>> exit() text[-1] # "n" (last) if age < 13:
text[1:4] # "yth" (slice) category = "child"
Variables are created when first assigned
text[:3] # "Pyt" (from start) elif age < 20:
Run a Script Use descriptive variable names text[3:] # "hon" (to end) category = "teenager"
Follow snake_case convention text[::2] # "Pto" (every 2nd) else:
$ python my_script.py
text[::-1] # "nohtyP" (reverse) category = "adult"
Basic Assignment
Run a Script in Interactive Mode
name = "Leo" # String String Formatting Comparison Operators
$ python -i my_script.py age = 7 # Integer # f-strings
height = 5.6 # Float x == y # Equal to
name = "Aubrey"
is_cat = True # Boolean x != y # Not equal to
Learn More on realpython.com/search: age = 2
x < y # Less than
flaws = None # None type f"Hello, {name}!" # "Hello, Aubrey!"
interpreter ∙ run a script ∙ command line f"{name} is {age} years old" # "Aubrey is 2 years old" x <= y # Less than or equal
f"Debug: {age=}" # "Debug: age=2" x > y # Greater than
Parallel & Chained Assignments x >= y # Greater than or equal
Comments # Format method
x, y = 10, 20 # Assign multiple values template = "Hello, {name}! You're {age}."
a = b = c = 0 # Give same value to multiple variables template.format(name="Aubrey", age=2) # "Hello, Aubrey! You're 2." Logical Operators
Always add a space after the #
Use comments to explain “why” of your code if age >= 18 and has_car:
Augmented Assignments Raw Strings print("Roadtrip!")
Write Comments counter += 1 # Normal string with an escaped tab
if is_weekend or is_holiday:
numbers += [4, 5] "This is:\tCool." # "This is: Cool."
# This is a comment print("No work today.")
permissions |= write
# print("This code will not run.") # Raw string with escape sequences
print("This will run.") # Comments are ignored by Python if not is_raining:
r"This is:\tCool." # "This is:\tCool." print("You can go outside.")
Learn More on realpython.com/search:
Learn More on realpython.com/search: variables ∙ assignment operator ∙ walrus operator
Learn More on realpython.com/search:
Learn More on realpython.com/search:
comment ∙ documentation strings ∙ string methods ∙ slice notation ∙ raw strings
conditional statements ∙ operators ∙ truthy falsy

Continue your learning journey and become a Python expert at realpython.com/start-here


Loops Calling Functions Class Attributes & Methods Raising Exceptions
greet() # "Hello!" class Cat: def validate_age(age):
range(5) generates 0 through 4 greet_person("Bartosz") # "Hello, Bartosz" species = "Felis catus" # Class attribute if age < 0:
Use enumerate() to get index and value add(5, 3) # 8 raise ValueError("Age cannot be negative")
break exits the loop, continue skips to next add(7) # 17 def __init__(self, name): return age
Be careful with while to not create an infinite loop self.name = name # Instance attribute
Return Values def meow(self): Learn More on realpython.com/search:
For Loops def get_min_max(numbers): return f"{self.name} says Meow!" exceptions ∙ errors ∙ debugging
# Loop through range return min(numbers), max(numbers)
for i in range(5): # 0, 1, 2, 3, 4 @classmethod
print(i) minimum, maximum = get_min_max([1, 5, 3]) def create_kitten(cls, name): Collections
return cls(f"Baby {name}")
# Loop through collection A collection is any container data structure that stores multiple items
Useful Built-in Functions If an object is a collection, then you can loop through it
fruits = ["apple", "banana"] Inheritance
for fruit in fruits: callable() # Checks if an object can be called as a function Strings are collections, too
print(fruit) dir() # Lists attributes and methods class Animal:
def __init__(self, name): Use len() to get the size of a collection
globals() # Get a dictionary of the current global symbol table
# With enumerate for index hash() # Get the hash value self.name = name You can check if an item is in a collection with the in keyword
for i, fruit in enumerate(fruits): id() # Get the unique identifier Some collections may look similar, but each data structure solves specific
print(f"{i}: {fruit}") locals() # Get a dictionary of the current local symbol table def speak(self): needs
repr() # Get a string representation for debugging pass

While Loops class Dog(Animal): Lists


Lambda Functions
while True: def speak(self): # Creating lists
user_input = input("Enter 'quit' to exit: ") square = lambda x: x**2 return f"{self.name} barks!" empty = []
if user_input == "quit": result = square(5) # 25 nums = [5]
break Learn More on realpython.com/search: mixed = [1, "two", 3.0, True]
print(f"You entered: {user_input}") # With map and filter
numbers = [1, 2, 3, 4] object oriented programming ∙ classes # List methods
squared = list(map(lambda x: x**2, numbers)) nums.append("x") # Add to end
Loop Control evens = list(filter(lambda x: x % 2 == 0, numbers)) nums.insert(0, "y") # Insert at index 0
Exceptions nums.extend(["z", 5]) # Extend with iterable
for i in range(10):
if i == 3: Learn More on realpython.com/search: nums.remove("x") # Remove first "x"
When Python runs and encounters an error, it creates an exception last = nums.pop() # Pop returns last element
continue # Skip this iteration define functions ∙ return multiple values ∙ lambda
if i == 7: Use specific exception types when possible
break # Exit loop else runs if no exception occurred # List indexing and checks
print(i) fruits = ["banana", "apple", "orange"]
Classes finally always runs, even after errors
fruits[0] # "banana"
fruits[-1] # "orange"
Learn More on realpython.com/search: Classes are blueprints for objects Try-Except "apple" in fruits # True
for loop ∙ while loop ∙ enumerate ∙ control flow You can create multiple instances of one class len(fruits) # 3
try:
You commonly use classes to encapsulate data number = int(input("Enter a number: "))
Inside a class, you provide methods for interacting with the data result = 10 / number Tuples
Functions .__init__() is the constructor method except ValueError:
print("That's not a valid number!") # Creating tuples
self refers to the instance point = (3, 4)
Define functions with def except ZeroDivisionError:
Always use () to call a function print("Cannot divide by zero!") single = (1,) # Note the comma!
Defining Classes else: empty = ()
Add return to send values back
print(f"Result: {result}")
Create anonymous functions with the lambda keyword class Dog: # Basic tuple unpacking
finally:
def __init__(self, name, age): point = (3, 4)
print("Calculation attempted")
Defining Functions self.name = name x, y = point
self.age = age x # 3
def greet(): y # 4
return "Hello!" def bark(self): Common Exceptions
return f"{self.name} says Woof!" ValueError # Invalid value # Extended unpacking
def greet_person(name): TypeError # Wrong type first, *rest = (1, 2, 3, 4)
return f"Hello, {name}!" # Create instance IndexError # List index out of range first # 1
my_dog = Dog("Frieda", 3) KeyError # Dict key not found rest # [2, 3, 4]
def add(x, y=10): # Default parameter print(my_dog.bark()) # Frieda says Woof! FileNotFoundError # File doesn't exist
return x + y

Continue your learning journey and become a Python expert at realpython.com/start-here


Sets File I/O Virtual Environments Pythonic Constructs
# Creating Sets # Swap variables
a = {1, 2, 3} File Operations Virtual Environments are often called “venv” a, b = b, a
b = set([3, 4, 4, 5]) Use venvs to isolate project packages from the system-wide Python packages
# Read an entire file
with open("file.txt", mode="r", encoding="utf-8") as file: # Flatten a list of lists
# Set Operations content = file.read() Create Virtual Environment matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
a | b # {1, 2, 3, 4, 5} flat = [item for sublist in matrix for item in sublist]
a & b # {3} $ python -m venv .venv
# Read a file line by line
a - b # {1, 2} # Remove duplicates
with open("file.txt", mode="r", encoding="utf-8") as file:
a ^ b # {1, 2, 4, 5} unique_unordered = list(set(my_list))
for line in file: Activate Virtual Environment (Windows)
print(line.strip())
PS> .venv\Scripts\activate # Remove duplicates, preserve order
Dictionaries unique = list(dict.fromkeys(my_list))
# Write a file
# Creating Dictionaries with open("output.txt", mode="w", encoding="utf-8") as file:
empty = {} Activate Virtual Environment (Linux & macOS) # Count occurrences
file.write("Hello, World!\n")
pet = {"name": "Leo", "age": 42} from collections import Counter
$ source .venv/bin/activate
# Dictionary Operations # Append to a File
pet["sound"] = "Purr!" # Add key and value with open("log.txt", mode="a", encoding="utf-8") as file: counts = Counter(my_list)
pet["age"] = 7 # Update value Deactivate Virtual Environment
file.write("New log entry\n")
age = pet.get("age", 0) # Get with default
del pet["sound"] # Delete key (.venv) $ deactivate Learn More on realpython.com/search:
pet.pop("age") # Remove and return
Learn More on realpython.com/search: counter ∙ tricks
# Dictionary Methods files ∙ context manager ∙ pathlib Learn More on realpython.com/search:
pet = {"name": "Frieda", "sound": "Bark!"}
pet.keys() # dict_keys(['name', 'sound']) virtual environment ∙ venv
pet.values() # dict_values(['Frieda', 'Bark!'])
pet.items() # dict_items([('name', 'Frieda'), ('sound', 'Bark!')]) Imports & Modules Do you want to go deeper on any topic in the Python curriculum?
Packages
Prefer explicit imports over import * At Real Python you can immerse yourself in any topic. Level up your
Learn More on realpython.com/search:
Use aliases for long module names The official third-party package repository is the Python Package Index (PyPI) skills effectively with curated resources like:
list ∙ tuple ∙ set ∙ dictionary ∙ indexing ∙ unpacking Group imports: standard library, third-party libraries, user-defined modules Learning paths
Install Packages
Video courses
Comprehensions Import Styles $ python -m pip install requests Written tutorials
# Import entire module Interactive quizzes
You can think of comprehensions as condensed for loops
import math Save Requirements & Install from File
Comprehensions are faster than equivalent loops result = math.sqrt(16) Podcast interviews
$ python -m pip freeze > requirements.txt Reference articles
List Comprehensions # Import specific function $ python -m pip install -r requirements.txt
from math import sqrt Continue your learning journey and become a Python expert at
# Basic result = sqrt(16) realpython.com/start-here
squares = [x**2 for x in range(10)] Related Tutorials
# Import with alias Installing Python Packages
# With condition import numpy as np Requirements Files in Python Projects
evens = [x for x in range(20) if x % 2 == 0] array = np.array([1, 2, 3])

# Nested # Import all (not recommended) Miscellaneous


matrix = [[i*j for j in range(3)] for i in range(3)] from math import *
Truthy Falsy
Other Comprehensions Package Imports
-42 0
# Dictionary comprehension # Import from package
word_lengths = {word: len(word) for word in ["hello", "world"]} import package.module 3.14 0.0
from package import module
# Set comprehension from package.subpackage import module "John" ""
unique_lengths = {len(word) for word in ["who", "what", "why"]}
# Import specific items [1, 2, 3] []
# Generator expression
from package.module import function, Class
sum_squares = sum(x**2 for x in range(1000))
from package.module import name as alias ("apple", "banana") ()
Learn More on realpython.com/search:
{"key": None} {}
comprehensions ∙ data structures ∙ generators Learn More on realpython.com/search:
import ∙ modules ∙ packages None

Continue your learning journey and become a Python expert at realpython.com/start-here

You might also like