Python Syntax Cheat Sheet

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

NameDescriptionSyntax Example
intInteger numbersx = 10
floatDecimal numbery = 10.5
strString, or texttext = "Hello, World!"
listOrdered collection of itemsfruits = ["apple", "banana"]
tupleImmutable ordered collectioncolors = ("red", "blue")
setUnordered collection of unique itemsunique_numbers = {1, 2, 3}
dictUnordered collection of key-value pairsperson = {"name": "John"}
boolBoolean value (True or False)is_valid = False
frozensetImmutable version of a setimmutable_set = frozenset([1, 2, 3])
bytesImmutable sequence of bytesbyte_data = b"Hello"
bytearrayMutable sequence of bytesmutable_byte_data = bytearray(b"Hello")
NoneRepresents absence of a value or null objectx = None

Common Built-in Functions

NameDescriptionSyntax Example
len()Returns the number of items in an objectlength = len([1, 2, 3])
print()Outputs text or variables to the consoleprint("Hello, World!")
type()Returns the type of the objectobj_type = type(123)
isinstance()Check if an object is an instance of a certain class or tuple of classescheck = isinstance(5, int)
sorted()Return a sorted list of the specified iterable’s elementssorted_list = sorted([3, 1, 2])
sum()Returns the sum of all items in an iterabletotal = sum([1, 2, 3])
max(), min()Return the largest/smallest item in an iterable or two or more argumentsmaximum = max([1, 2, 3])
abs()Returns the absolute value of a numberabsolute_value = abs(-5)
round()Round a number to the nearest integer or to the given number of decimalsrounded_value = round(3.14159, 2)
input()Read a line from input, optionally using the provided prompt stringuser_input = input("Enter your name: ")
deque()Returns a new deque object initialized from datafrom collections import deque; d = deque([1, 2, 3])
range()Returns a sequence of numbersrange(start, stop, step)
dict.update()Updates the dictionary with the specified key-value pairsdict1.update(dict2)
list.extend()Adds the elements of a list to the end of the current listlist1.extend(list2)
sliceReturns a slice of an objectmy_list[start:stop:step]
set.difference()Returns a set containing the difference between two or more setsa.difference(b)

Basic Math Operators

OperatorDescriptionSyntax Example
+Additiona + b
Subtractiona - b
*Multiplicationa * b
/Divisiona / b
//Integer division (floors the result)a // b
%Modulus (remainder of division)a % b
**Exponentiationa ** b
&Bitwise ANDa & b
|Bitwise ORa \| b
^Bitwise XORa ^ b
<<Left shifta << 1
>>Right shifta >> 1
~Bitwise NOT~a
+=Increment a variable’s valuevariable += 1

Type Conversion

NameDescriptionSyntax Example
intConverts a value to an integerint("123")
strConverts a value to a stringstr(123)
listConverts a value to a listlist("hello")

String Manipulation

NameDescriptionSyntax Example
.format()Format strings using positional and keyword arguments'{} {}'.format('one', 'two')
f-stringEmbed expressions inside string literalsf"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

NameDescriptionSyntax Example
lowerConverts string to lowercase"HELLO".lower()
upperConverts string to uppercase"hello".upper()
stripRemoves whitespace from start and end" hello ".strip()
replaceReplaces a substring with another"hello".replace("e", "a")
ord()Returns an integer representing the Unicode characterord('a')
chr()Returns a string representing a character whose Unicode code point is the integerchr(97)

List Methods

NameDescriptionSyntax Example
appendAdds an item to the end of the listfruits.append("orange")
removeRemoves the first occurrence of the itemfruits.remove("apple")
popRemoves the item at the specified indexfruits.pop(1)
sortSorts the listnumbers.sort()
indexReturns the index of the first occurrence of the itemcolors.index("red")

Control Structures

NameDescriptionSyntax Example
ifConditional statementif x > 10:
if-elif-elseConditional statementsif x > 10: ... elif x == 10: ... else: ...
if notLogical NOT conditionif not x:
forLoop over a sequencefor i in range(3):
whileLoop as long as condition is truewhile x < 5:
breakExits the current loopif x == 5: break
continueSkips the rest of the loop’s current iterationif x == 3: continue
exitExits the current Python scriptexit()

Functions and Modules

NameDescriptionSyntax Example
defDefine a functiondef< my_func():
importImport a module or libraryimport math
fromImport a specific part from a modulefrom datetime import date
returnReturns a value from a functiondef sum(a, b): return a+b
classDefines a classclass Person: ...

Exception Handling

NameDescriptionSyntax Example
raiseRaises an exceptionraise ValueError("A value error occurred!")
assertUsed for debugging, raises an error if falseassert x > 0, "Only positive numbers are allowed"
try-exceptCatches and handles exceptionstry: ... except SomeError: ...

List Comprehensions & Generators

NameDescriptionSyntax Example
List comprehensionGenerates a new list by applying an expression[x**2 for x in range(5)]
GeneratorProduces items one at a time and requires less memory(x**2 for x in range(5))

Decorators & Metaclasses

NameDescriptionSyntax Example
DecoratorModifies or extends the behavior of functions/classes@staticmethod
MetaclassA class of a class that defines how a class behavesclass MyClass(metaclass=Meta): ...

File Handling

NameDescriptionSyntax Example
openOpens a filefile = open("filename.txt", "r")
closeCloses a filefile.close()
withUsed with file operations to automatically close a filewith open("filename.txt", "r") as file: ...
os.rename()Rename a file or directoryimport os; os.rename('old_name.txt', 'new_name.txt')
os.remove()Remove a fileimport os; os.remove('filename.txt')
shutil.copy()Copy a fileimport shutil; shutil.copy('source.txt', 'dest.txt')

Environment Variables & OS Interactions

NameDescriptionSyntax Example
os.environAccess environment variablesuser = os.environ.get("USERNAME")
os.system()Execute a shell commandos.system('echo Hello World')

Web Server Interactions

NameDescriptionSyntax Example
GET methodRetrieve data from a serverresponse = requests.get(url)
POST methodSend data to a serverresponse = requests.post(url, data=payload)

Miscellaneous

NameDescriptionSyntax Example
passA null statement, a placeholder for future codedef my_function(): pass
globalAccesses a global variable inside a functiondef set_global_x(): global x; x = 10
nonlocalAccesses a variable in the nearest enclosing scopedef outer_func(): x = 10; def inner_func(): nonlocal x; x = 20
deepcopyCreates a new object that’s a copy of the originalfrom copy import deepcopy; new_obj = deepcopy(obj)
lambdaCreates a small anonymous functionx = lambda a : a + 10
mapApplies a function to all items in an input listsquared = map(lambda x: x**2, [1, 2, 3, 4])
filterFilters elements in a list based on a functionfilter(lambda x: x%2 == 0, [1, 2, 3])
reduceApply a function to items, reducing list to a single valuefrom functools import reduce; reduce(lambda x, y: x*y, [1, 2, 3])

JSON Handling

NameDescriptionSyntax Example
json.load()Load JSON data from a filewith open("data.json") as f: data = json.load(f)
json.loads()Parse JSON stringdata = json.loads(json_string)
json.dump()Write JSON data to a filewith open("output.json", "w") as f: json.dump(data, f)
json.dumps()Convert Python object to JSON string

Web Server Request Handling with Flask

NameDescriptionSyntax 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.argsAccess GET (query string) parametersvalue = request.args.get('param_name')
Request.formAccess POST form datavalue = request.form.get('field_name')
Request.dataAccess raw data sent in the request (e.g., for JSON payloads)raw_data = request.data
Request.jsonAccess parsed JSON data in the request bodydata_obj = request.json
Return ResponseReturn a specific response to the clientreturn "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!