Python is one of the most popular programming languages in the world. Some of the world’s most famous companies use Python like Netflix, Google, and Uber. But if you’ve seen our article on developer’s confessions then you already know developers use cheat sheets all the time!
To help you learn Python, we here at OneMonth wanted to offer this free Python cheat sheet that you can use anytime to look up python variables, functions, tuples, and more. Enjoy!
Python Primitives
Variables
Variables are used for storing values. A string is a series of characters, surrounded by quotes.
x = 1 #integer
y = 1.1 #float
z = 1 + 2j #complex
a = "this is a string" #string
b = True #boolean
v1 = 1
v2 = 2
v1, v2 = v2, v1 #variable swapping
String Manipulation
String manipulation is for accessing specific characters within a string.
this_is_a_string = “Python is awesome” len(this_is_a_string) #returns the length of a string this_is_a_string[0] #returns the first char of a string this_is_a_string[1] #returns the second char of a string this_is_a_string[0:4] #returns the first 5 chars of a string
Escape Sequences
Escape sequences are used for indicating special characters that are used in the languages, such as quotes.
\"
\’
\\
\n
Type Conversions
Type conversions are used for converting between different types of values.
int(value) #converts value to an integer
float(value) #converts value to a float
bool(value) #converts value to a boolean
string(value) #converts value to a string
Useful Number Functions
A couple of useful number related functions.
abs(value) #returns an absolute value round(value) #returns a rounded value
Useful String Methods
Useful and common string functions.
str.upper() #returns the string as uppercase str.lower() #returns the string as lowercase str.strip() #returns the string with both leading and trailing characters removed str.find("x") #finds “x” in str str.replace("x", "y") #replaces “x” with “y” "a" in str #checks if “a” exists within str
Formatting Strings
Formatting strings is the most common way to format a string.
print("Hello, I am {} years old !".format(18)) #this prints the following string: Hello, I am 18 years old!
Falsy Values
Falsy values are values that evaluate to false.
“” 0 None
Logic Flow
Regular Conditions
Conditions control the logic flow within a program.
if person == "me": print("it’s me") elif person == "you": print("it’s you") else: print("no, it’s someone else")
Ternary Condition
Ternary condition is the short version of an if-else condition statement.
person = "it’s me" if who == "me" else "it’s you or someone else"
Chaining Comparison
Chaining Comparison is a way to chain two conditions into one.
if 18 <= tariff < 28:
For Loops
Loops repeat a block of code for a specific number of iterations.
for number in range(0, 99):
Python While Loops
Repeats a block of code until a specific condition is true.
while number > 0:
Boolean Logic
Determines what is true or false.
red and blue #both should be true red or blue #at least one true not red #inverses a boolean
Equality
Checks if two items are equal or not.
== #equal != #not equal
Functions
How to Define a Function
A function is a named block of code designed to do one specific job.
def add(n1, n2): return n1 + n2
Variable Number of Arguments
Variable number of parameters that are passed to a function.
def print_items(*items): for item in items: print item … print_items(1, 2, 3, 4, 5, 6)
Variable Number of Keyword Arguments
def say_something(**person): ... say_something(firstname="John", lastname="Doe")
Keyword Arguments
say_something("John", lastname="Doe")
Python Lists
Creation
Stores a series of items in a particular order.
items = ["red", "green", "blue"] num_range = list(range(10)) matrix_list = [["red", "green"], ["green”, "blue"]] ones = [1] * 5 combined = ones + items
Access
items = ["red", "green", "blue"] items[0] # returns “x” items[-1] # returns “z”
Unpacking
item1, *others = items
Looping
Items within a list are accessed using an index, or within a loop.
for item in items: … for idx, item in enumerate(items): ...
Adding
items.append("dark red") # items is now ["red", "green", "blue", "dark red"] items.insert(0, "white") # items is now ["white", "red", "green", "blue", "dark red"]
Removing
items.pop(0) # items is now ["red", "green", "blue", "dark red"] items.remove("green") # items is now ["red", "blue", "dark red"] del items[1:2] # items is now ["red"] items = ["red", "green", "blue"] # re-assigning the original items
Finding
if "red" in items: items.index("red")
Sorting
items.sort() # orders items as red, green, blue items.sort(reverse=True) # orders items as blue, green, red
List Zipping
a = [1, 2] b = [10, 20] c = list(zip(a, b)) # returns [(1, 10), (2, 20)]
Python Dictionaries, Sets & Tuples
Dictionaries
Dictionaries store connections between pieces of information. Each item is a key-value pair.
dic = {"a": 1, "b": 2} # returns {"a": 1, "b": 2} dic = dict(a=1, b=2) # returns {"a": 1, "b": 2} dic["c"] = 3 # {"a": 1, "b": 2, "c": 3} if "a" in dic: ... del dic["c"] # {"a": 1, "b": 2} for key, value in dic.items(): ...
Sets
a = {1, 2, 3, 4} b = {1, 5} a | b # {1, 2, 3, 4, 5} a & b # {1} a - b # {2, 3, 4}
Python Tuples
Similar to lists, but the items can’t be modified.
t = 1, 2, 3 t = (1, 2, 3) t = (1,) t = () t(0:3) a, b, c = t if 1 in t: …
Generators
List
items = [a * 2 for a in range(15)] items = [a * 2 for a in range(15) if a % 2 == 0]
Set
items = {a * 2 for a in range(15)}
Dictionary
items = {a: a * 2 for a in range(15)}
Exceptions
Handling
Exceptions help respond appropriately to errors that are likely to occur.
try: … except (ValueError, ZeroDivisionError): … else: # no exceptions raised finally: # code cleanup here
Raising
if x < 1: raise ValueError("…") With with open("file.txt") as file: # any exception produced, it is handled inside this statement …
Python Classes
Creating
A class defines the behavior of an object and the kind of information an object can store.
class Test: def __init__(self, a, b): self.a = a self.b = b def something(self):
Attributes
The information in a class is stored in attributes.
class Test: name = "Cristiano Ronaldo" # attribute def __init__(self, a, b): self.a = a
Instance / Class / Statics Methods
Functions that belong to a class are called methods.
class Test: def something(self): # instance method … @classmethod # class method def anotherthing(cls): … @staticmethod # static method def onemorething(): …
Private Members
class Test: def __init__(self, a): self.__a = a # __a is a private member
Properties
class Point:
def __init__(self, a):
self.__a = a # __a is a private member
@property
def a(self): # defines the ‘a’ property for the __a is a private member
return self.__a
@property.setter:
def a.setter(self, value): # defines the setter for property ‘a’
self.__a = value
Inheritance
A child class inherits the attributes and methods from its parent class.
class CsvFileReader(FileReader): # CsvFileReader inherits from FileReader def open(self): super().open() # Invokes the open() method from FileReader
Multiple Inheritance
class CsvFileReader(FileReader, GenericReader): # CsvFileReader inherits from two classes
Named Tuples Example
from collections import namedtuple Item = namedtuple("Item", ["a", "a"]) item= Item(a=1, b=2)
Importing Python Libraries
Importing
import sys # Import all the sys library # Imports namedtuple from the collections library from collections import namedtuple