Whether you’re a seasoned developer looking to brush up on Python’s intricacies or a beginner stepping into the world of programming, this Python Cheat Sheet is your handy companion. Within this guide, you’ll find concise explanations, practical examples, and quick references for Python’s core concepts and functionalities.
This cheat sheet is designed to be both comprehensive and digestible. From data types to control structures, function usage to error handling, dive in to get a snapshot of Python’s capabilities. And remember, the key to mastering Python (or any language, for that matter) is consistent practice and application. Happy coding!
Command Reference
In this section, we’ve compiled a handy list of essential Python-related commands. Whether you’re setting up a new environment, installing packages, or managing dependencies, these commands will help streamline your workflow and ensure you’re making the most of Python’s robust ecosystem.
Data Types
Name | Description | Syntax Example |
---|
int | Integer numbers | x = 10 |
float | Decimal number | y = 10.5 |
str | String, or text | text = "Hello, World!" |
list | Ordered collection of items | fruits = ["apple", "banana"] |
tuple | Immutable ordered collection | colors = ("red", "blue") |
set | Unordered collection of unique items | unique_numbers = {1, 2, 3} |
dict | Unordered collection of key-value pairs | person = {"name": "John"} |
bool | Boolean value (True or False) | is_valid = False |
frozenset | Immutable version of a set | immutable_set = frozenset([1, 2, 3]) |
bytes | Immutable sequence of bytes | byte_data = b"Hello" |
bytearray | Mutable sequence of bytes | mutable_byte_data = bytearray(b"Hello") |
None | Represents absence of a value or null object | x = None |
Common Built-in Functions
Name | Description | Syntax Example |
---|
len() | Returns the number of items in an object | length = len([1, 2, 3]) |
print() | Outputs text or variables to the console | print("Hello, World!") |
type() | Returns the type of the object | obj_type = type(123) |
isinstance() | Check if an object is an instance of a certain class or tuple of classes | check = isinstance(5, int) |
sorted() | Return a sorted list of the specified iterable’s elements | sorted_list = sorted([3, 1, 2]) |
sum() | Returns the sum of all items in an iterable | total = sum([1, 2, 3]) |
max(), min() | Return the largest/smallest item in an iterable or two or more arguments | maximum = max([1, 2, 3]) |
abs() | Returns the absolute value of a number | absolute_value = abs(-5) |
round() | Round a number to the nearest integer or to the given number of decimals | rounded_value = round(3.14159, 2) |
input() | Read a line from input, optionally using the provided prompt string | user_input = input("Enter your name: ") |
deque() | Returns a new deque object initialized from data | from collections import deque; d = deque([1, 2, 3]) |
range() | Returns a sequence of numbers | range(start, stop, step) |
dict.update() | Updates the dictionary with the specified key-value pairs | dict1.update(dict2) |
list.extend() | Adds the elements of a list to the end of the current list | list1.extend(list2) |
slice | Returns a slice of an object | my_list[start:stop:step] |
set.difference() | Returns a set containing the difference between two or more sets | a.difference(b) |
Basic Math Operators
Operator | Description | Syntax Example |
---|
+ | Addition | a + b |
– | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
// | Integer division (floors the result) | a // b |
% | Modulus (remainder of division) | a % b |
** | Exponentiation | a ** b |
& | Bitwise AND | a & b |
| | Bitwise OR | a \| b |
^ | Bitwise XOR | a ^ b |
<< | Left shift | a << 1 |
>> | Right shift | a >> 1 |
~ | Bitwise NOT | ~a |
+= | Increment a variable’s value | variable += 1 |
Type Conversion
Name | Description | Syntax Example |
---|
int | Converts a value to an integer | int("123") |
str | Converts a value to a string | str(123) |
list | Converts a value to a list | list("hello") |
String Manipulation
Name | Description | Syntax Example |
---|
.format() | Format strings using positional and keyword arguments | '{} {}'.format('one', 'two') |
f-string | Embed expressions inside string literals | f"The sum is {1+2}" |
.split() | Splits a string into a list | "Hello, World".split(", ") |
.join() | Joins elements of an iterable with a string separator | ", ".join(["apple", "banana", "cherry"]) |
String Methods
Name | Description | Syntax Example |
---|
lower | Converts string to lowercase | "HELLO".lower() |
upper | Converts string to uppercase | "hello".upper() |
strip | Removes whitespace from start and end | " hello ".strip() |
replace | Replaces a substring with another | "hello".replace("e", "a") |
ord() | Returns an integer representing the Unicode character | ord('a') |
chr() | Returns a string representing a character whose Unicode code point is the integer | chr(97) |
List Methods
Name | Description | Syntax Example |
---|
append | Adds an item to the end of the list | fruits.append("orange") |
remove | Removes the first occurrence of the item | fruits.remove("apple") |
pop | Removes the item at the specified index | fruits.pop(1) |
sort | Sorts the list | numbers.sort() |
index | Returns the index of the first occurrence of the item | colors.index("red") |
Control Structures
Name | Description | Syntax Example |
---|
if | Conditional statement | if x > 10: |
if-elif-else | Conditional statements | if x > 10: ... elif x == 10: ... else: ... |
if not | Logical NOT condition | if not x: |
for | Loop over a sequence | for i in range(3): |
while | Loop as long as condition is true | while x < 5: |
break | Exits the current loop | if x == 5: break |
continue | Skips the rest of the loop’s current iteration | if x == 3: continue |
exit | Exits the current Python script | exit() |
Functions and Modules
Name | Description | Syntax Example |
---|
def | Define a function | def< my_func(): |
import | Import a module or library | import math |
from | Import a specific part from a module | from datetime import date |
return | Returns a value from a function | def sum(a, b): return a+b |
class | Defines a class | class Person: ... |
Exception Handling
Name | Description | Syntax Example |
---|
raise | Raises an exception | raise ValueError("A value error occurred!") |
assert | Used for debugging, raises an error if false | assert x > 0, "Only positive numbers are allowed" |
try-except | Catches and handles exceptions | try: ... except SomeError: ... |
List Comprehensions & Generators
Name | Description | Syntax Example |
---|
List comprehension | Generates a new list by applying an expression | [x**2 for x in range(5)] |
Generator | Produces items one at a time and requires less memory | (x**2 for x in range(5)) |
Decorators & Metaclasses
Name | Description | Syntax Example |
---|
Decorator | Modifies or extends the behavior of functions/classes | @staticmethod |
Metaclass | A class of a class that defines how a class behaves | class MyClass(metaclass=Meta): ... |
File Handling
Name | Description | Syntax Example |
---|
open | Opens a file | file = open("filename.txt", "r") |
close | Closes a file | file.close() |
with | Used with file operations to automatically close a file | with open("filename.txt", "r") as file: ... |
os.rename() | Rename a file or directory | import os; os.rename('old_name.txt', 'new_name.txt') |
os.remove() | Remove a file | import os; os.remove('filename.txt') |
shutil.copy() | Copy a file | import shutil; shutil.copy('source.txt', 'dest.txt') |
Environment Variables & OS Interactions
Name | Description | Syntax Example |
---|
os.environ | Access environment variables | user = os.environ.get("USERNAME") |
os.system() | Execute a shell command | os.system('echo Hello World') |
Web Server Interactions
Name | Description | Syntax Example |
---|
GET method | Retrieve data from a server | response = requests.get(url) |
POST method | Send data to a server | response = requests.post(url, data=payload) |
Miscellaneous
Name | Description | Syntax Example |
---|
pass | A null statement, a placeholder for future code | def my_function(): pass |
global | Accesses a global variable inside a function | def set_global_x(): global x; x = 10 |
nonlocal | Accesses a variable in the nearest enclosing scope | def outer_func(): x = 10; def inner_func(): nonlocal x; x = 20 |
deepcopy | Creates a new object that’s a copy of the original | from copy import deepcopy; new_obj = deepcopy(obj) |
lambda | Creates a small anonymous function | x = lambda a : a + 10 |
map | Applies a function to all items in an input list | squared = map(lambda x: x**2, [1, 2, 3, 4]) |
filter | Filters elements in a list based on a function | filter(lambda x: x%2 == 0, [1, 2, 3]) |
reduce | Apply a function to items, reducing list to a single value | from functools import reduce; reduce(lambda x, y: x*y, [1, 2, 3]) |
JSON Handling
Name | Description | Syntax Example |
---|
json.load() | Load JSON data from a file | with open("data.json") as f: data = json.load(f) |
json.loads() | Parse JSON string | data = json.loads(json_string) |
json.dump() | Write JSON data to a file | with open("output.json", "w") as f: json.dump(data, f) |
json.dumps() | Convert Python object to JSON string | |
Web Server Request Handling with Flask
Name | Description | Syntax Example |
---|
Flask route (GET) | Define a route that listens for HTTP GET requests | @app.route('/endpoint') |
Flask route (POST) | Define a route that listens for HTTP POST requests | @app.route('/endpoint', methods=['POST']) |
Request.args | Access GET (query string) parameters | value = request.args.get('param_name') |
Request.form | Access POST form data | value = request.form.get('field_name') |
Request.data | Access raw data sent in the request (e.g., for JSON payloads) | raw_data = request.data |
Request.json | Access parsed JSON data in the request body | data_obj = request.json |
Return Response | Return a specific response to the client | return "Hello World", 200 |
Illustrative Example Program
After acquainting ourselves with the key commands, it’s time to see Python in action! Below, we’ll walk you through setting up a Python environment and then delve into an illustrative program. This example serves to showcase the various Python concepts we’ve covered, integrating them into a single, cohesive script.
It’s one thing to understand a concept in isolation; it’s another to see how it fits within the larger picture of Python programming. Dive in and observe how these individual pieces come together!
Setting up the environment
First, let’s learn how to install a module dependency. You can use pip or poetry to install Python modules.
PiP installs the dependency on the OS as a whole, available to all python scripts.
Poetry on the other hand, creates a virtual environment for each Python application, allowing you to use different versions of a module for each Python application. This is great for compatibility and tidyness!
# Install a specific version of a module with pip
pip install requests==2.25.1
# Or using poetry
poetry add [email protected]
# Specify a particular version for poetry in the pyproject.toml
echo 'requests = "^2.25.1"' >> pyproject.toml
# Open your Python file using nano to start coding
nano my_python_script.py
Python Code Example
Now, you can copy / paste the example program and run it.
Read over it to see how the different Python commands and functions are actually used in a program.
It’s one thing to read a syntax specification, and quite another to see how you actually type it out and see what it does!
import os
import json
import requests
import math
from copy import deepcopy
# Using "requests" to get IP with error handling
try:
response = requests.get('https://api.ipify.org?format=json')
ip_data = json.loads(response.text)
my_ip = ip_data["ip"]
print(f"Your IP is: {my_ip}")
except requests.ConnectionError:
print("Failed to connect to the website!")
except Exception as e:
print(f"An unknown error occurred: {e}")
# Data Types
# Immutable Object Types
my_str = "Hello"
my_num = 123
my_float = 3.14
my_tuple = (4, 5, 6)
# Mutable Object Types:
my_list = [1, 2, 3]
my_set = {7, 8, 9}
my_dict = {'a': 1, 'b': 2}
# Careful: mutable variables are passed by reference
def modify_list(lst):
# Appending a new item to the list
lst.append(4)
# Test the function
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # Output: [1, 2, 3, 4]
# Avoid mutable default arguments with "None"
# Avoid altering passed variables using deepcopy
def add_to_list(value, my_list_argument=None):
# If no list is provided, use an empty one
if my_list_argument is None:
my_list = []
else:
my_list = deepcopy(my_list_argument)
my_list.append(value)
return my_list
# Test the function
original_list = [1, 2, 3]
new_list = add_to_list(4, original_list)
print(original_list) # Output: [1, 2, 3] - remains unchanged
print(new_list) # Output: [1, 2, 3, 4] - value added to new list
# Built-in Functions & Methods
print("Hello, World!") # This is a comment
my_str = f"My IP address is {my_ip} and it's {len(my_ip)} characters long."
print my_str
rounded_down = math.floor(3.6)
print(f"Rounded down: {rounded_down}")
# Prints "Rounded down: 3"
# Data type conversions and String concatenation
num_str = "15"
num_int = 20
print(num_str + " + " + str(num_int) + " = " + str(int(num_str) + num_int))
# Outputs "15 + 20 = 35"
# Using decorator functions
def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling function: {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_decorator
def greet(name):
return f"Hello, {name}"
print(greet("Alice"))
# Prints Two lines:
# Calling function: greet
# Hello, Alice
# Classes & OOP
class Animal:
def __init__(self, species):
self.species = species
class Dog(Animal):
def bark(self):
return "Woof!"
dog = Dog("Canine")
print(dog.bark())
# Control Structures & List Comprehensions
numbers = [1, 5, 8, 10] # Sample list of numbers
# Using a for loop to extract odd numbers
odds = []
for num in numbers:
if num % 2 != 0:
odds.append(num)
# % modulo gives the remainder of a division. If the remainder dividing by 2 is not 0, the number is odd.
# Using a list comprehension to extract even numbers (compact equivalent to the above logic)
evens = [num for num in numbers if num % 2 == 0]
# Calculate the sum of the even numbers
even_sum = sum(evens)
# Print results
print(f"Odd numbers: {odds}") # 1, 5
print(f"Sum of even numbers: {even_sum}") # 18
# Iterating through environment variables
# For loop method
for key, value in os.environ.items():
if key == "SECRET_PASSWORD":
print("Encountered sensitive data. Exiting...")
break
print(f"{key}: {value}")
# While loop method
env_items = list(os.environ.items()) # Convert dict items to a list
i = 0
while i < len(env_items):
key, value = env_items[i]
if key == "SECRET_PASSWORD":
print("Encountered sensitive data. Exiting...")
break
print(f"{key}: {value}")
i += 1
# Grabbing a specific environment variable
environment_value = os.getenv("HOME") # Fetch an environment variable
print(f"My home directory is: {environment_value}. String in lowercase: {environment_value.lower()}")
print("End of Program!")
After walking through the example program, you’ve likely noticed how Python beautifully integrates different concepts to achieve a desired outcome. We’ve seen how it handles errors gracefully with try
and except
, how it can interact with the web using requests
, and how it manipulates various data types seamlessly.
The true strength of Python lies in its versatility and readability. Each module and function has a specific role, and the community-driven packages expand its capabilities even further.
Conclusion
Python is a dynamic and versatile language, suitable for a wide range of tasks from web development to data analysis and machine learning. The cheat sheet provided here is a testament to its rich feature set and user-friendly syntax. As you delve deeper into Python, always remember to leverage the vast resources available, including documentation and community forums. Happy coding!