Python Programming Language Cheat Sheet
Naming Conventions
- Class names - CapWords
- Functions - all_lowercase()
- Variable names = all_lowercase
Indentation
- 4 spaces per indentation
Comments
# use pound/octothorpe/hashtag for comments
Running from commandline
python filename.py
main()
def main()
print("hello world!")
I/O
Input
input('What Is Your Name?')
you can store this into a variable
Output
print('Very nice to meet you!')
name = 'Barbara'
age = '32'
print('Very nice to meet you! My name is', name, 'and I am', age, 'years old')
String Literals
print(f'Very nice to meet you, {name}!')
additionally
str.format()
function
print('Very nice to meet you, {}!'.format(name))
Variables
Declaring
name = 'Mat'
temperature = 97.25
Casting
temperature = str(97.5) #string
temperature = int(97.5) #int
temperature = float(97.5) #float
temperature = bool(true) #bool
to check type
type(temperature) #prints the kind it is
Operators
Arithmetic Operators
x = 4
y = 3
x + y # returns 7
x - y # returns 1
x * y # returns 12
x ** y # returns 64
x / y # returns 1.333
x // y # returns 1
x % y # returns 1
Assignment Operators
# x=4
x += 4 # x is 8
x -= 4 # x is 0
x *= 4 # x is 16
x /= 4 # x is 1.0
x %= 4 # x is 0
Comparison Operators
x = 4
y = 3
x == y # returns False
x != y # returns True
x > y # returns True
x < y # returns False
x >= y # returns True
x <= y # returns False
Logical Operators
x = 4
y = 3
x > 2 and y > 1 # returns True
x > 5 or y <= 3 # returns True
not(x > 2 and y > 1) # returns False
if, elif, else
If
score = 90
if score >= 80:
print('You pass the course!')
Else
score = 70
if score >= 80:
print('You pass the course!')
else:
print('You do not pass the course!')
Elif
score = 70
if score >= 80:
print('You pass the course with flying colors!')
elif score > 65:
print('You pass the course! Talk to your instructor.')
else:
print('You do not pass the course!')
Loops
For Loops
nums = [1, 2, 3, 4, 5]
for num in nums:
print(num + 1)
For Loops With range()
The range()
function can be used with the for
loop to execute a block of code multiple times. The code below iterates between numbers 0
to 2
and prints each number.
for i in range(3):
print(i)
Nested For Loops
teams = [['Jody', 'Abe'], ['Abhishek', 'Kim'], ['Taylor', 'Jen']]
for team in teams:
for name in team:
print(name)
While Loops
i = 1
while i < 6:
print(i)
i += 1
Pass
The pass
keyword is mostly used as a placeholder in a loop. Nothing gets executed when pass
is placed under a condition.
Break
The break
keyword terminates a loop. break
statements are typically found within conditional statements. If a certain condition is met, the loop stops iterating and breaks at that point.
names = ['Joyce', 'Hannah', 'Manny', 'Manoj', 'Ezekiel']
for name in names:
if 'h' in name.lower():
break
else:
print(name)
Continue
The continue
keyword skips over an iteration if the condition is met and goes onto the next iteration. The difference between the continue
keyword and pass
is that continue
goes onto the next iteration while pass
simply does not do anything.
names = ['Joyce', 'Hannah', 'Manny', 'Manoj', 'Ezekiel']
for name in names:
if 'm' in name.lower():
continue
else:
print(name)
Error Handling
Try and Except
The clause try
attempts to execute a block of code and except
executes another block of code if try
fails.
nums = [0, 1, 2, 3]
try:
print(sum(nums))
except:
print('Cannot print the sum! Your variables are not numbers.')
Finally
The finally
clause executes a block of code regardless of which clause, try
or except
, was executed. The finally
clause is useful in cases where both of your try
and except
might fail.
nums = ['x', 'y', 'z']
try:
print(sum(nums))
except:
print('Cannot print the sum! Your variables are not numbers.')
finally:
print('Hope you got the result you want!')
Functions
Creating a function
use def
def add_three(num1, num2, num3):
sum_three = num1 + num2 + num3
return sum_three
Calling a function
sum_output = add_three(2, 4, 6)
Parameters
Functions can be built to include parameters. Parameters are treated as local variables within the body of the function. The function below has the parameter language
.
def greetings(language):
if language == 'Spanish':
greeting = 'Hola'
elif language == 'English':
greeting = 'Hello'
elif language == 'French':
greeting = 'Bonjour'
Arguments
Arguments are values that can be passed into the function and used as parameters. We can call the above function with the argument French
like this:
greetings('French')
Recursion
The word recursion in Python describes the process of repeatedly calling a function within itself.
def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num-1)
Lambda Function
A lambda function in Python is a simple, anonymous function that is defined without a name. In this article, we’ll cover the syntax and characteristics of lambda functions.
lambda functions are defined with the lambda keyword without a name.
lambda argument(s): expression
add_two = lambda x: x + 2
add_two(5)
would give 7
Why Use Lambda Functions?
Lambda functions are typically used in the following scenarios:
- When we want to write a quick function with one line
- When we want to combine with other built-in functions such as
map()
,filter()
, andapply()
to filter for data
Classes and Objects
Classes
A class is a data type that encapsulates information and functions as a blueprint for objects. Let’s take a look at the syntax for creating a new class:
class Dog:
# this is a blank class
pass
Objects
An object is an instance of a class, which means the object contains everything from the class that it’s instantiated from. We can take the above class Dog
and create an object named pepper
as such:
pepper = Dog()
print(pepper)
Constructors and Destructors
In object-oriented programming (OOP), constructors are functions that are called when an object of a class is created and destructors are called to delete an object.
Constructors are special functions that are executed when an object is instantiated. In Python, the __init__()
function is used as the constructor and is called when creating an object
Constructors
init()
It is common practice for classes to contain Python’s built-in __init__()
method as the constructor. In the example below, the __init__()
method would be called every time the ClassSchedule
class is instantiated, and used to initialize a newly created object:
class ClassSchedule:
def __init__(self, course):
self.course = course
Instance Variables
The self
parameter in the __init__()
method refers to the current instance and the instance variable course
allows for input to assign a value. We can create a class instance by calling the class and inputting the value for course
. Let’s create an instance with the instance variable ’Chemistry’
and assign it to an object named first
:
class ClassSchedule:
def __init__(self, course):
self.course = course
first = ClassSchedule('Chemistry')
print(first.course)
this would print
Chemistry
Destructor
Destructors are special functions that are called when an object gets deleted. In Python, the __del__()
method is commonly used as the destructor and is called when an object is deleted.
del()
Python’s built-in __del__()
method represents the destructor in a class. In the example below, the __del__()
method would be called every time an object initiated from the ClassSchedule
class is deleted.
class ClassSchedule:
def __init__(self, course):
self.course = course
def __del__(self):
print('You successfully deleted your schedule')
The self
parameter in the __del__()
method refers to the current object. Triggering this method by deleting the object will execute the print()
statement. So, if we use del
to delete the sched
object as such:
sched = ClassSchedule('Chemistry')
del sched
would give the following outpout
You successfully deleted your schedule
Access Modifiers
Public
By default, all members within a class are public.
Being public means that these members can easily be accessed outside of the class, in another part of the program. For example:
class ClassSchedule:
def __init__(self, course, instructor):
self.course = course
self.instructor = instructor
def display_course(self):
print(f'Course: {self.course}, Instructor: {self.instructor}')
All members here are accessible outside of the class. For example, we can access the variable course
and method display_course()
without any limitations:
Protected
Protected access modifiers, denoted with the prefix _
, prevent members from being accessed outside of the class, unless it’s from a subclass.
class ClassSchedule:
def __init__(self, course, instructor):
self._course = course # protected
self._instructor = instructor # protected
def display_course(self):
print(f'Course: {self._course}, Instructor: {self._instructor}')
sched = ClassSchedule('Biology', 'Ms. Smith')
sched.display_course()
The variables course
and instructor
are now protected members in the class.
Private
Private access modifiers, denoted with the prefix __
, declare members to be accessible within the class only. Members with this modifier will be marked private and any attempt to access these members outside of the class will cause an Attribute Error message.
class ClassSchedule:
def __init__(self, course, instructor):
self.__course = course # private
self.__instructor = instructor # private
def display_course(self):
# public
print(f'Course: {self.__course}, Instructor: {self.__instructor}')
sched = ClassSchedule('Biology', 'Ms. Smith')
sched.__course # this will throw an Attribute Error because we're trying to access a private member
sched.display_course() # this won't throw an Attribute Error because this method is public
Encapsulation
In object-oriented programming (OOP), encapsulation is a fundamental concept that describes wrapping variables and methods in one unit.
A popular example of encapsulation is a class, as it “encapsulates” members such as variables and methods in one single unit. In this article, we’ll explore different members of a class.
Class Variables
A class can contain variables that can only be accessed by an object of the class. The example below shows the class UserInfo
with a constructor that takes in variables username
and email_address
:
class UserInfo:
def __init__(self, username, email_address):
self.username = username
self.email_address = email_address
user = UserInfo('user123', 'abc@edf.ghi')
user.username
user.email_address
The data saved in the object can be accessed using the variables. For example, calling user.username
will return ’user123’
, and calling user.email_address
will return ’abc@efd.ghi’
.
Class Methods
A class can also contain methods that can be accessed by objects of the class. The example below shows the class UserInfo
with the method check_username
that checks whether a username is saved in the object or not:
class UserInfo:
def __init__(self, username, email_address):
self.username = username
self.email_address = email_address
def check_username(self, username_to_check):
if username_to_check == self.username:
return True
else:
return False
We can call the method check_username
on our object to run the method:
user = UserInfo('user123', 'abc@edf.ghi')
user.check_username('user123') # returns True
user.check_username('user456') # returns False
Inheritance
Inheritance is a feature of object-oriented programming (OOP) that enables the transfer of methods and properties of one class to another. Inheritance allows for reusability of code as well as extending the capability of new classes. In this article, we’ll cover the two main components of inheritance:
- Parent class
- Child class
Parent Class
The parent class, also known as base class, is the class whose methods and properties transfer over to the child class. We can define a parent class like we would for any class, with the constructor and any methods and properties we want to include. See an example of a class below:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def print_info(self):
print(f'{self.name} is {self.age} years old')
Child Class
he child class, also known as the derived class, is the class that inherits methods and properties from the parent class. The child class must contain the following:
- Name of the parent class in the definition of the child class
- Constructor of the parent class called within the constructor of the child class
The following example shows Person
as the parent class as well as a child class named Teacher
:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def print_info(self):
print(self.name)
print(self.age)
class Teacher(Person):
def __init__(self, name, age, subject):
self.subject = subject
Person.__init__(self, name, age)
Polymorphism
Polymorphism in OOP is the concept of classes sharing methods with the same name.
Polymorphism with Classes
In Python, classes are allowed to contain methods that share the same name as another method from a different class. The code below shows two different classes that are independent of each other with some methods of the same names:
class Checking():
def type(self):
print('You have a checking account at the Codecademy Bank.')
def balance(self):
print('$20 left in your checking.')
class Savings():
def type(self):
print('You have a savings account at the Codecademy Bank.')
def balance(self):
print('$1000 left in your savings.')
We can create an object for each class, and without worrying about which object belongs to which class, we can call the same methods. In the for
loop, the variable account
iterates through the tuple with the two objects, and executes the method for each class accordingly:
account_a = Checking()
account_b = Savings()
for account in (account_a, account_b):
account.type()
account.balance()
Output
You have a checking account at the Codecademy Bank.
$20 left in your checking.
You have a savings account at the Codecademy Bank.
$1000 left in your checking.
String methods
len()
Returns length of string
str.lower(), str.upper(), str.title()
The built-in function .lower()
takes a string and converts all letters in the string to lowercase. Similarly, the built-in function .upper()
converts all letters in the string to uppercase. .title()
capitalizes the first letter of each word
str.split()
The built-in function .split()
takes a string and splits the string into a list of strings. By default, the function splits by whitespace but the separator can be specified as an argument.
intro = "My name is Jeff!"
print(intro.split()) # prints ['My', 'name', 'is', 'Jeff!']
print(intro.split('name')) # prints ['My ', ' is Jeff!']
print(intro.split('!')) # prints ['My name is Jeff', '']
Lists
In Python, lists are ordered collections of items that can contain different data types such as strings, integers, float values and many more.
lst = ['abc', 123, 'def', 10.5, 62, ['g', 'h', 'i']]
.len()
The length of a list can be measured using the built-in function len()
. It takes the list as an argument to count the items in the list.
.append()
The built-in method .append()
takes an item as an argument to add the item to the end of a list.
.remove()
The built-in method .remove()
removes an item that’s passed as the argument.
.pop()
The built-in method `.pop()’ takes an index and removes an item at that given index and returns that item. If no index is provided, it takes the last item from the list.
Tuples
Tuples are one of the built-in data structures in Python. Just like lists, tuples can hold a sequence of items and have a few key advantages
Tuples are immutable, meaning we can’t modify a tuple’s elements after creating one, and do not require an extra memory block like lists.
Tuples are great to work with if you are working with data that won’t need to be changed in your code.
In Python, tuples are defined with parentheses ()
with comma-separated values. Just like lists, tuples are sequences and can hold objects of different data types.
my_tuple = ('abc', 123, 'def', 456)
Indexing and Slicing
Items in a tuple can be accessed with their index, otherwise known as their position in the tuple. Take a look at the following tuple:
print(my_tuple[0]) # prints abc
print(my_tuple[3:5]) # prints (456, 789)
Built in functions
.len()
gives you the number of items
.max()
gives you max value (need all data types to be the same)
.min()
returns the tuple’s minimum value
.index()
takes in a value as the argument to find its index in the tuple.
.count()
takes in a value as the argument to find the number of occurrences in the tuple.
Dictionaries
In Python, dictionaries are defined with curly brackets {}
. Dictionaries contain what’s called key-value pairs, which refer to pairs of a key and a value separated by a colon :
. The values can hold and be a mix of different data types, including lists or even nested dictionaries. However, keys must be an immutable data type such as strings, numbers or tuples.
groceries = {'fruits': ['mangoes', 'bananas', 'kiwis'],
'protein': ['beef', 'pork', 'salmon'],
'carbs': ['rice', 'pasta', 'bread'],
'veggies': ['lettuce', 'cabbage', 'onions']}
Accessing and Writing Values
there are no built-in ways to use indexing and slicing to access the values in a certain order in the dictionaries. A value within a dictionary can be accessed with its key.
party_planning = {'Yes': 10,
'No': 15,
'Maybe': 30,
'Location': 'Our Backyard',
'Date': '2022/05/01'}
party_planning['Location'] # returns 'Our Backyard'
To update:
party_planning['Location'] = 'At the park'
party_planning['Location'] # prints 'At the park'
To add a new item
party_planning['Dress Code'] = 'Casual'
Built in Functions
.len()
It takes the dictionary as an argument to count the number of key-value pairs in the dictionary.
.update()
takes in a dictionary as an argument to update an existing dictionary. Any new key-value pairs will be added to the existing dictionary, but overlapping key-value pairs from the new dictionary will overwrite the key-value pairs in the existing dictionary.
.keys()
and .values()
used to return the list of keys and values of a dictionary.
shopping_list = {'jewelry': 'earrings', 'clothes': 'jeans', 'budget': 200}
shopping_list.keys() # returns dict_keys(['jewelry', 'clothes', 'budget'])
shopping_list.values() # returns dict_values(['earrings', 'jeans', 200])
Sets
A set is an immutable, unordered collection of unique elements that can consist of integers, floats, strings and tuples. However, sets cannot hold mutable elements such as lists, sets or dictionaries.
set1 = {'Jenny', 26, 'Parker', 10.5}
print(set1) # prints {10.5, 26, 'Jenny', 'Parker'}
The built-in function set()
can be used with a list argument to create a set from that list. Note that this will drop any duplicate elements in the list, as sets can only contain unique, non-duplicated elements. Here we can see lst
being used with the set()
function to create a set set2
:
lst = ['Jenny', 26, 'Parker', 'Parker', 10.5]
set2 = set(lst)
print(set2) # prints {10.5, 26, 'Jenny', 'Parker'}
Accessing and Writing Values
Sets do not have indexes or keys. We can use in
to check to see if the element exists in the set:
students = {'Jane', 'Carlos', 'Amy', 'Bridgette', 'Chau', 'Dmitry'}
print('Chau' in students) # returns True
Built in methods
.add()
new elements can be added using the built-in method add()
which takes in an element to add to a set:
students = {'Jane', 'Carlos', 'Amy', 'Bridgette', 'Chau', 'Dmitry'}
students.add('George')
print('George' in students) # returns True
.update()
and .union()
Takes in any iterable object, such as tuples, lists, dictionaries or sets, and adds the object to an existing set. Any duplicated elements will not be added.
students1 = {'Jane', 'Carlos', 'Amy', 'Bridgette', 'Chau', 'Dmitry'}
students2 = {'Alice', 'Lily', 'Zhuo', 'Amy', 'Jane'}
students1.update(students2)
Similarly, the built-in method .union()
takes an iterable object and joins the new object with the existing object:
students1 = {'Jane', 'Carlos', 'Amy', 'Bridgette', 'Chau', 'Dmitry'}
students2 = {'Alice', 'Lily', 'Zhuo', 'Amy', 'Jane'}
students3 = students1.union(students2)
.remove()
The built-in method .remove()
takes in an element and removes it from the set. See an example below:
students = {'Jane', 'Carlos', 'Amy', 'Bridgette', 'Chau', 'Dmitry'}
students.remove('Bridgette')
for loops
Because sets are iterable, we can utilize a for
loop to iterate through a set. count_down = set([9, 8, 7, 6, 5, 4, 3, 2, 1])
for num in count_down:
print(num, 'seconds left!')
Queues and Stacks
Queues
Queues are collections of items that follow the FIFO protocol to store and remove data.
We can use nodes to implement class Queue
:
class Queue:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def enqueue(self, value):
if self.has_space():
item_to_add = Node(value)
print("Adding " + str(item_to_add.get_value()) + " to the queue!")
if self.is_empty():
self.head = item_to_add
self.tail = item_to_add
else:
self.tail.set_next_node(item_to_add)
self.tail = item_to_add
self.size += 1
else:
print("Sorry, no more room!")
def dequeue(self):
if self.get_size() > 0:
item_to_remove = self.head
print(str(item_to_remove.get_value()) + " is served!")
if self.get_size() == 1:
self.head = None
self.tail = None
else:
self.head = self.head.get_next_node()
self.size -= 1
return item_to_remove.get_value()
else:
print("The queue is totally empty!")
def peek(self):
if self.size > 0:
return self.head.get_value()
else:
print("No orders waiting!")
def get_size(self):
return self.size
def is_empty(self):
return self.size == 0
.enqueue()
adds the value into the queue
.dequeue()
removes the next value
peek()
returns the front value in the queue
get_size()
returns the size of the queue
is_empty()
checks to see if queue is empty
Stacks
Stacks follow the LIFO (last-in-first-out) protocol to store and remove data.
from node import Node
class Stack:
def __init__(self, limit=1000):
self.top_item = None
self.size = 0
def push(self, value):
if self.has_space():
item = Node(value)
item.set_next_node(self.top_item)
self.top_item = item
self.size += 1
else:
print("All out of space!")
def pop(self):
if self.size > 0:
item_to_remove = self.top_item
self.top_item = item_to_remove.get_next_node()
self.size -= 1
return item_to_remove.get_value()
else:
print("This stack is totally empty.")
def peek(self):
if self.size > 0:
return self.top_item.get_value()
else:
print("Nothing to see here!")
def is_empty(self):
return self.size == 0
.push()
This method takes in a value and adds it to the top of the stack.
.pop()
This method removes the top value in the stack if there are existing values.
.peek()
this method returns the top value in the stack if there are existing values.
.is_empty()
this method checks to see if the stack is empty and will return True
if it is and False
if it is not.