Killing the internet one fake blog post at a time.

Python 2 CheatSheet.

Written in

by

Sure, here is a cheat sheet for Python 2:

  1. Basic Data Types:
  • int: integers (e.g. 5)
  • float: floating-point numbers (e.g. 3.14)
  • str: strings (e.g. “hello”)
  • bool: boolean values (True or False)
  • None: a special type that represents the absence of a value
  1. Basic Operators:
  • +: addition
  • -: subtraction
  • *: multiplication
  • /: division
  • %: modulo (remainder)
  • **: exponentiation
  • //: floor division (quotient rounded down)
  1. Conditional Statements:
  • if statement:
if condition:
    statement
elif condition:
    statement
else:
    statement
  • ternary operator:
value_if_true if condition else value_if_false
  1. Loops:
  • for loop:
for variable in iterable:
    statement
  • while loop:
while condition:
    statement
  • break statement:
while condition:
    if condition:
        break
    statement
  1. Lists:
  • creating a list:
my_list = [1, 2, 3, "four", True]
  • indexing a list:
my_list[0] # returns 1
my_list[-1] # returns True
  • slicing a list:
my_list[1:3] # returns [2, 3]
my_list[:3] # returns [1, 2, 3]
my_list[3:] # returns ["four", True]
  1. Dictionaries:
  • creating a dictionary:
my_dict = {"name": "John", "age": 30, "gender": "male"}
  • accessing a value in a dictionary:
my_dict["name"] # returns "John"
my_dict.get("age") # returns 30
  1. Functions:
  • defining a function:
def my_function(arg1, arg2):
    statement
    return value
  • calling a function:
my_function(value1, value2)
  1. Modules:
  • importing a module:
import my_module
  • importing a specific function from a module:
from my_module import my_function
  • aliasing a module:
import my_module as mm
  1. File Input/Output:
  • opening a file:
my_file = open("filename.txt", "r") # open for reading
my_file = open("filename.txt", "w") # open for writing
my_file = open("filename.txt", "a") # open for appending
  • reading from a file:
my_file.read() # reads the entire file
my_file.readline() # reads a single line
my_file.readlines() # reads all lines into a list
  • writing to a file:
my_file.write("Hello, world!")
  1. Exception Handling:
  • try/except block:
try:
    statement
except ExceptionType:
    statement
  • raising an exception:
raise ExceptionType, "Error message"

This cheat sheet covers some of the most commonly used features in Python 2, including basic data types, operators, conditional statements, loops, lists, dictionaries, functions, modules, file input/output, and exception handling. Note that Python 2 has been officially deprecated as of January 1, 2020, and users are encouraged to transition to Python 3.