Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
71 views

Hello World: Cheatsheets / Learn Python 3

This document provides an overview of key Python syntax concepts including comments, arithmetic operations, variables, strings, errors, and data types. It defines each concept and provides examples to illustrate proper syntax and usage. Key points covered include using # for single-line comments, arithmetic operators like + - * / % **, assigning values to variables with =, concatenating strings with +, and types of errors like NameError, SyntaxError, ZeroDivisionError that may occur.

Uploaded by

Dillon McConnell
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views

Hello World: Cheatsheets / Learn Python 3

This document provides an overview of key Python syntax concepts including comments, arithmetic operations, variables, strings, errors, and data types. It defines each concept and provides examples to illustrate proper syntax and usage. Key points covered include using # for single-line comments, arithmetic operators like + - * / % **, assigning values to variables with =, concatenating strings with +, and types of errors like NameError, SyntaxError, ZeroDivisionError that may occur.

Uploaded by

Dillon McConnell
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

12/28/20, 12:55 AM

Cheatsheets / Learn Python 3

Hello World

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 1 of 6
12/28/20, 12:55 AM

Comments
A comment is a piece of text within a program that is
not executed. It can be used to provide additional # Comment on a single line
information to aid in understanding the code.
The # character is used to start a comment and it user = "JDoe" # Comment after code
continues until the end of the line.

Arithmetic Operations
Python supports di!erent types of arithmetic
operations that can be performed on literal numbers, # Arithmetic operations
variables, or some combination. The primary
arithmetic operators are: result = 10 + 30
result = 40 - 10

+ for addition
result = 50 * 5

- for subtraction result = 16 / 4
result = 25 % 2

* for multiplication
result = 5 ** 3

/ for division

% for modulus (returns the remainder)

** for exponentiation

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 2 of 6
12/28/20, 12:55 AM

Plus-Equals Operator +=
The plus-equals operator += provides a convenient
way to add a value to an existing variable and assign # Plus-Equal Operator
the new value back to the same variable. In the case
where the variable and the value are strings, this counter = 0
operator performs string concatenation instead of counter += 10
addition.
The operation is performed in-place, meaning that any # This is equivalent to
other variable which points to the variable being
updated will also be updated.
counter = 0
counter = counter + 10

# The operator will also perform


string concatenation

message = "Part 1 of message "


message += "Part 2 of message"

Variables
A variable is used to store data that will be used by the
program. This data can be a number, a string, a # These are all valid variable names
Boolean, a list or some other data type. Every variable and assignment
has a name which can consist of letters, numbers, and
the underscore character _ . user_name = "@sonnynomnom"
The equal sign = is used to assign a value to a user_id = 100
variable. After the initial assignment is made, the value verified = False
of a variable can be updated to new values as needed.

# A variable's value can be changed


after assignment

points = 100
points = 120

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 3 of 6
12/28/20, 12:55 AM

Modulo Operator %
A modulo calculation returns the remainder of a
division between the "rst and second number. For # Modulo operations
example:
zero = 8 % 4

The result of the expression 4 % 2 would
result in the value 0, because 4 is evenly divisible
nonzero = 12 % 5
by 2 leaving no remainder.


The result of the expression 7 % 3 would
return 1, because 7 is not evenly divisible by 3,
leaving a remainder of 1.

Integers
An integer is a number that can be written without a
fractional part (no decimal). An integer can be a # Example integer numbers
positive number, a negative number or the number 0
so long as there is no decimal portion. chairs = 4
The number 0 represents an integer value but the tables = 1
same number written as 0.0 would represent a broken_chairs = -2
#oating point number. sofas = 0

# Non-integer numbers

lights = 2.5
left_overs = 0.0

String Concatenation
Python supports the joining (concatenation) of strings
together using the + operator. The + operator is # String concatenation
also used for mathematical addition operations. If the
parameters passed to the + operator are strings, first = "Hello "
then concatenation will be performed. If the second = "World"
parameter passed to + have di!erent types, then
Python will report an error condition. Multiple result = first + second
variables or literal strings can be joined together using
the + operator. long_result = first + second + "!"

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 4 of 6
12/28/20, 12:55 AM

Errors
The Python interpreter will report errors present in
your code. For most error cases, the interpreter will if False ISNOTEQUAL True:
display the line of code where the error was detected ^
and place a caret character ^ under the portion of SyntaxError: invalid syntax
the code where the error was detected.

ZeroDivisionError
A ZeroDivisionError is reported by the Python
interpreter when it detects a division operation is numerator = 100
being performed and the denominator (bottom denominator = 0
number) is 0. In mathematics, dividing a number by bad_results = numerator / denominator
zero has no de"ned value, so Python treats this as an
error condition and will report a ZeroDivisionError and
ZeroDivisionError: division by zero
display the line of code where the division occurred.
This can also happen if a variable is used as the
denominator and its value has been set to or changed
to 0.

Strings
A string is a sequence of characters (letters, numbers,
whitespace or punctuation) enclosed by quotation user = "User Full Name"
marks. It can be enclosed using either the double game = 'Monopoly'
quotation mark " or the single quotation mark ' .
If a string has to be broken into multiple lines, the longer = "This string is broken up \
backslash character \ can be used to indicate that over multiple lines"
the string continues on the next line.

SyntaxError
A SyntaxError is reported by the Python interpreter
when some portion of the code is incorrect. This can age = 7 + 5 = 4
include misspelled keywords, missing or too many
brackets or parenthesis, incorrect operators, missing File "<stdin>", line 1
or too many quotation marks, or other conditions.
SyntaxError: can't assign to operator

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 5 of 6
12/28/20, 12:55 AM

NameError
A NameError is reported by the Python interpreter
when it detects a variable that is unknown. This can misspelled_variable_name
occur when a variable is used before it has been
assigned a value or if a variable name is spelled NameError: name
di!erently than the point at which it was de"ned. The
'misspelled_variable_name' is not
Python interpreter will display the line of code where
defined
the NameError was detected and indicate which name
it found that was not de"ned.

Floating Point Numbers


Python variables can be assigned di!erent types of
data. One supported data type is the #oating point # Floating point numbers
number. A #oating point number is a value that
contains a decimal portion. It can be used to pi = 3.14159
represent numbers that have fractional quantities. For meal_cost = 12.99
example, a = 3/5 can not be represented as an tip_percent = 0.20
integer, so the variable a is assigned a #oating point
value of 0.6 .

print() Function
The print() function is used to output text,
numbers, or other printable information to the print("Hello World!")
console.
It takes one or more arguments and will output each print(100)
of the arguments to the console separated by a space.
If no arguments are provided, the print() pi = 3.14159
function will output a blank line. print(pi)

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-syntax/cheatsheet Page 6 of 6
12/28/20, 12:55 AM

Cheatsheets / Learn Python 3

Functions

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 1 of 6
12/28/20, 12:55 AM

Function Parameters
Sometimes functions require input to provide data for
their code. This input is de!ned using parameters. def write_a_book(character, setting,
Parameters are variables that are de!ned in the special_skill):
function de!nition. They are assigned the values which print(character + " is in " +
were passed as arguments when the function was setting + " practicing her "
called, elsewhere in the code.
+
For example, the function de!nition de!nes
special_skill)
parameters for a character, a setting, and a skill, which
are used as inputs to write the !rst sentence of a
book.

Multiple Parameters
Python functions can have multiple parameters. Just
as you wouldn’t go to school without both a backpack def ready_for_school(backpack,
and a pencil case, functions may also need more than pencil_case):
one input to carry out their operations. if (backpack == 'full' and
To de!ne a function with multiple parameters, pencil_case == 'full'):
parameter names are placed one after another,
print ("I'm ready for school!")
separated by commas, within the parentheses of the
function de!nition.

Functions
Some tasks need to be performed multiple times
within a program. Rather than rewrite the same code # Define a function my_function()
in multiple places, a function may be de!ned using the with parameter x
def keyword. Function de!nitions may include
parameters, providing data input to the function. def my_function(x):
Functions may return a value using the return return x + 1
keyword followed by the value to return.
# Invoke the function

print(my_function(2)) # Output:
3
print(my_function(3 + 5)) # Output:
9

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 2 of 6
12/28/20, 12:55 AM

Function Indentation
Python uses indentation to identify blocks of code.
Code within the same block should be indented at the # Indentation is used to identify
same level. A Python function is one type of code code blocks
block. All code under a function declaration should be
indented to identify it as part of the function. There def testfunction(number):
can be additional indentation within a function to
# This code is part of testfunction
handle other statements such as for and if so print("Inside the testfunction")
long as the lines are not indented less than the !rst
sum = 0
line of the function code.
for x in range(number):
# More indentation because 'for'
has a code block
# but still part of he function
sum += x
return sum
print("This is not part of
testfunction")

Calling Functions
Python uses simple syntax to use, invoke, or call a
preexisting function. A function can be called by doHomework()
writing the name of it, followed by parentheses.
For example, the code provided would call the
doHomework() method.

Function Arguments
Parameters in python are variables — placeholders for
the actual values the function needs. When the def sales(grocery_store,
function is called, these values are passed in as item_on_sale, cost):
arguments. print(grocery_store + " is selling
For example, the arguments passed into the function " + item_on_sale + " for " + cost)
.sales() are the “The Farmer’s Market”,
“toothpaste”, and “$1” which correspond to the
sales("The Farmer’s Market",
parameters grocery_store , "toothpaste", "$1")
item_on_sale , and cost .

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 3 of 6
12/28/20, 12:55 AM

Function Keyword Arguments


Python functions can be de!ned with named
arguments which may have default values provided. def findvolume(length=1, width=1,
When function arguments are passed using their depth=1):
names, they are referred to as keyword arguments. print("Length = " + str(length))
The use of keyword arguments when calling a function print("Width = " + str(width))
allows the arguments to be passed in any order — not
print("Depth = " + str(depth))
just the order that they were de!ned in the function. If
return length * width * depth;
the function is invoked without a value for a speci!c
argument, the default value will be used.
findvolume(1, 2, 3)
findvolume(length=5, depth=2,
width=4)
findvolume(2, depth=3, width=4)

Returning Multiple Values


Python functions are able to return multiple values
using one return statement. All values that should def square_point(x, y, z):
be returned are listed after the return keyword x_squared = x * x
and are separated by commas. y_squared = y * y
In the example, the function square_point()
z_squared = z * z
# Return all three values:
returns x_squared , y_squared , and
return x_squared, y_squared,
z_squared .
z_squared

three_squared, four_squared,
five_squared = square_point(3, 4, 5)

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 4 of 6
12/28/20, 12:55 AM

The Scope of Variables


In Python, a variable de!ned inside a function is called
a local variable. It cannot be used outside of the scope a = 5
of the function, and attempting to do so without
de!ning the variable outside of the function will cause def f1():
an error.
a = 2
In the example, the variable a is de!ned both inside print(a)
and outside of the function. When the function
f1() is implemented, a is printed as 2 because print(a) # Will print 5
it is locally de!ned to be so. However, when printing f1() # Will print 2
a outside of the function, a is printed as 5
because it is implemented outside of the scope of the
function.

Returning Value from Function


A return keyword is used to return a value from a
Python function. The value returned from a function def check_leap_year(year):
can be assigned to a variable which can then be used if year % 4 == 0:
in the program. return str(year) + " is a leap
In the example, the function check_leap_year year."
returns a string which indicates if the passed else:
parameter is a leap year or not. return str(year) + " is not
a leap year."

year_to_check = 2018
returned_value
= check_leap_year(year_to_check)
print(returned_value) # 2018 is not
a leap year.

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 5 of 6
12/28/20, 12:55 AM

Global Variables
A variable that is de!ned outside of a function is called
a global variable. It can be accessed inside the body of a = "Hello"
a function.
In the example, the variable a is a global variable def prints_a():
because it is de!ned outside of the function print(a)
prints_a . It is therefore accessible to
prints_a , which will print the value of a . # will print "Hello"
prints_a()

Parameters as Local Variables


Function parameters behave identically to a function’s
local variables. They are initialized with the values def my_function(value):
passed into the function when it was called. print(value)
Like local variables, parameters cannot be referenced
from outside the scope of the function.
# Pass the value 7 into the function
In the example, the parameter value is de!ned as my_function(7)
part of the de!nition of my_function , and
therefore can only be accessed within # Causes an error as `value` no
my_function . Attempting to print the contents longer exists
of value from outside the function causes an print(value)
error.

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet Page 6 of 6
12/28/20, 12:55 AM

Cheatsheets / Learn Python 3

Control Flow

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 1 of 6
12/28/20, 12:55 AM

elif Statement
The Python elif statement allows for continued
# elif Statement
checks to be performed after an initial if
statement. An elif statement di!ers from the
pet_type = "fish"
else statement because another expression is
provided to be checked, just as with the initial if
if pet_type == "dog":
statement.
print("You have a dog.")
If the expression is True , the indented code
elif pet_type == "cat":
following the elif is executed. If the expression print("You have a cat.")
evaluates to False , the code can continue to an elif pet_type == "fish":
optional else statement. Multiple elif # this is performed
statements can be used following an initial if to print("You have a fish")
perform a series of checks. Once an elif else:
expression evaluates to True , no further elif print("Not sure!")
statements are executed.

Handling Exceptions in Python


A try and except block can be used to handle
error in code block. Code which may raise an error def check_leap_year(year):
can be written in the try block. During execution, if
is_leap_year = False
if year % 4 == 0:
that code block raises an error, the rest of the try
is_leap_year = True
block will cease executing and the except code
block will execute.
try:
check_leap_year(2018)
print(is_leap_year)
# The variable is_leap_year is
declared inside the function
except:
print('Your code raised an error!')

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 2 of 6
12/28/20, 12:55 AM

or Operator
The Python or operator combines two Boolean
True or True # Evaluates to True
expressions and evaluates to True if at least one of
True or False # Evaluates to True
the expressions returns True . Otherwise, if both
False or False # Evaluates to
expressions are False , then the entire expression
False
evaluates to False .
1 < 2 or 3 < 1 # Evaluates to True
3 < 1 or 1 > 6 # Evaluates to
False
1 == 1 or 1 < 2 # Evaluates to True

Equal Operator ==
The equal operator, == , is used to compare two
values, variables or expressions to determine if they # Equal operator
are the same.
If the values being compared are the same, the if 'Yes' == 'Yes':
operator returns True , otherwise it returns # evaluates to True
False . print('They are equal')
The operator takes the data type into account when
making the comparison, so a string value of "2" is if (2 > 1) == (5 < 10):
not considered the same as a numeric value of 2 . # evaluates to True
print('Both expressions give the
same result')

c = '2'
d = 2

if c == d:
print('They are equal')
else:
print('They are not equal')

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 3 of 6
12/28/20, 12:55 AM

Not Equals Operator !=


The Python not equals operator, != , is used to
compare two values, variables or expressions to # Not Equals Operator
determine if they are NOT the same. If they are NOT
the same, the operator returns True . If they are the if "Yes" != "No":
same, then it returns False .
# evaluates to True
The operator takes the data type into account when print("They are NOT equal")
making the comparison so a value of 10 would NOT
val1 = 10
be equal to the string value "10" and the operator
val2 = 20
would return True . If expressions are used, then
they are evaluated to a value of True or False
if val1 != val2:
before the comparison is made by the operator.
print("They are NOT equal")

if (10 > 1) != (10 > 1000):


# True != False
print("They are NOT equal")

Comparison Operators
In Python, relational operators compare two values or
expressions. The most common ones are: a = 2
b = 3

< less than a < b # evaluates to True

> greater than a > b # evaluates to False
a >= b # evaluates to False

<= less than or equal to a <= b # evaluates to True

>= greater than or equal too a <= a # evaluates to True

If the relation is sound, then the entire expression will


evaluate to True . If not, the expression evaluates to
False .

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 4 of 6
12/28/20, 12:55 AM

if Statement
The Python if statement is used to determine the
execution of code based on the evaluation of a # if Statement
Boolean expression.
test_value = 100

If the if statement expression evaluates to
True , then the indented code following the if test_value > 1:
statement is executed. # Expression evaluates to True
print("This code is executed!")

If the expression evaluates to False then the
indented code following the if statement is
if test_value > 1000:
skipped and the program executes the next line
# Expression evaluates to False
of code which is indented at the same level as
print("This code is NOT executed!")
the if statement.

print("Program continues at this


point.")

else Statement
The Python else statement provides alternate
# else Statement
code to execute if the expression in an if
statement evaluates to False .
test_value = 50
The indented code for the if statement is executed
if the expression evaluates to True . The indented
if test_value < 1:
code immediately following the else is executed print("Value is < 1")
only if the expression evaluates to False . To mark else:
the end of the else block, the code must be print("Value is >= 1")
unindented to the same level as the starting if line.
test_string = "VALID"

if test_string == "NOT_VALID":
print("String equals NOT_VALID")
else:
print("String equals something
else!")

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 5 of 6
12/28/20, 12:55 AM

and Operator
The Python and operator performs a Boolean
comparison between two Boolean values, variables, or True and True # Evaluates to True
expressions. If both sides of the operator evaluate to True and False # Evaluates to
True then the and operator returns True . If False
either side (or both sides) evaluates to False , then
False and False # Evaluates to
False
the and operator returns False . A non-Boolean
value (or variable that stores a value) will always
1 == 1 and 1 < 2 # Evaluates to True
1 < 2 and 3 < 1 # Evaluates to
evaluate to True when used with the and
operator.
False
"Yes" and 100 # Evaluates to True

Boolean Values
Booleans are a data type in Python, much like integers,
"oats, and strings. However, booleans only have two is_true = True
values: is_false = False


True print(type(is_true))

False # will output: <class 'bool'>

Speci#cally, these two values are of the bool type.


Since booleans are a data type, creating a variable that
holds a boolean value is the same as with other data
types.

not Operator
The Python Boolean not operator is used in a
Boolean expression in order to evaluate the expression not True # Evaluates to False
to its inverse value. If the original expression was not False # Evaluates to True
True , including the not operator would make 1 > 2 # Evaluates to False
the expression False , and vice versa.
not 1 > 2 # Evaluates to True
1 == 1 # Evaluates to True
not 1 == 1 # Evaluates to False

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-control-flow/cheatsheet Page 6 of 6
12/28/20, 12:55 AM

Cheatsheets / Learn Python 3

Lists

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet Page 1 of 5
12/28/20, 12:55 AM

Lists
In Python, lists are ordered collections of items that
allow for easy use of a set of data. primes = [2, 3, 5, 7, 11]
List values are placed in between square brackets [ print(primes)
] , separated by commas. It is good practice to put a
space between the comma and the next value. The empty_list = []
values in a list do not need to be unique (the same
value can be repeated).
Empty lists do not contain any values within the square
brackets.

Adding Lists Together


In Python, lists can be added to each other using the
plus symbol + . As shown in the code block, this will items = ['cake', 'cookie', 'bread']
result in a new list containing the same items in the total_items = items + ['biscuit',
same order with the !rst list’s items coming !rst. 'tart']
Note: This will not work for adding one item at a time print(total_items)
(use .append() method). In order to add one # Result: ['cake', 'cookie', 'bread',
item, create a new list with a single value and then use 'biscuit', 'tart']
the plus symbol to add the list.

Python Lists: Data Types


In Python, lists are a versatile data type that can
contain multiple di"erent data types within the same numbers = [1, 2, 3, 4, 10]
square brackets. The possible data types within a list names = ['Jenny', 'Sam', 'Alexis']
include numbers, strings, other objects, and even mixed = ['Jenny', 1, 2]
other lists. list_of_lists = [['a', 1], ['b', 2]]

List Method .append()


In Python, you can add values to the end of a list using
the .append() method. This will place the object orders = ['daisies', 'periwinkle']
passed in as a new element at the very end of the list. orders.append('tulips')
Printing the list afterwards will visually show the print(orders)
appended value. This .append() method is not # Result: ['daisies', 'periwinkle',
to be confused with returning an entirely new list with 'tulips']
the passed object.

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet Page 2 of 5
12/28/20, 12:55 AM

Aggregating Iterables Using zip()


In Python, data types that can be iterated (called
iterables) can be used with the zip() function to owners_names = ['Jenny', 'Sam',
aggregate data. The zip() function takes iterables, 'Alexis']
aggregates corresponding elements based on the dogs_names = ['Elphonse', 'Dr. Doggy
iterables passed in, and returns an iterator. Each DDS', 'Carter']
element of the returned iterator is a tuple of values. owners_dogs = zip(owners_names,
As shown in the example, zip() is aggregating the dogs_names)
data between the owners’ names and the dogs’ names print(list(owners_dogs))
to match the owner to their dogs. zip() returns an # Result: [('Jenny', 'Elphonse'),
iterator containing the data based on what the user ('Sam', 'Dr.Doggy DDS'), ('Alexis',
passes to the function. Empty iterables passed in will 'Carter')]
result in an empty iterator. To view the contents of the
iterator returned from zip() , we can cast it as a
list by using the list() function and printing the
results.

List Item Ranges Including First or Last Item


In Python, when selecting a range of list items, if the
!rst item to be selected is at index 0 , no index needs items = [1, 2, 3, 4, 5, 6]
to be speci!ed before the : . Similarly, if the last item
selected is the last item in the list, no index needs to # All items from index `0` to `3`
be speci!ed after the : . print(items[:4])

# All items from index `2` to the


last item, inclusive
print(items[2:])

List Method .count()


The .count() Python list method searches a list
for whatever search term it receives as an argument, backpack = ['pencil', 'pen',
then returns the number of matching entries found. 'notebook', 'textbook', 'pen',
'highlighter', 'pen']
numPen = backpack.count('pen')
print(numPen)
# Output: 3

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet Page 3 of 5
12/28/20, 12:55 AM

Determining List Length with len()


The Python len() function can be used to
determine the number of items found in the list it knapsack = [2, 4, 3, 7, 10]
accepts as an argument. size = len(knapsack)
print(size)
# Output: 5

Zero-Indexing
In Python, list index begins at zero and ends at the
length of the list minus one. For example, in this list, names = ['Roger', 'Rafael', 'Andy',
'Andy' is found at index 2 . 'Novak']

List Method .sort()


The .sort() Python list method will sort the
contents of whatever list it is called on. Numerical lists exampleList = [4, 2, 1, 3]
will be sorted in ascending order, and lists of Strings exampleList.sort()
will be sorted into alphabetical order. It modi!es the print(exampleList)
original list, and has no return value. # Output: [1, 2, 3, 4]

List Indices
Python list elements are ordered by index, a number
referring to their placement in the list. List indices berries = ["blueberry", "cranberry",
start at 0 and increment by one. "raspberry"]
To access a list element by index, square bracket
notation is used: list[index] . berries[0] # "blueberry"
berries[2] # "raspberry"

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet Page 4 of 5
12/28/20, 12:55 AM

Negative List Indices


Negative indices for lists in Python can be used to
reference elements in relation to the end of a list. This soups = ['minestrone', 'lentil',
can be used to access single list elements or as part of 'pho', 'laksa']
de!ning a list range. For instance: soups[-1] # 'laksa'
soups[-3:] # 'lentil', 'pho',

To select the last element, my_list[-1] .
'laksa'
● To select the last three elements, soups[:-2] # 'minestrone', 'lentil'
my_list[-3:] .
● To select everything except the last two
elements, my_list[:-2] .

List Slicing
A slice, or sub-list of Python list elements can be
selected from a list using a colon-separated starting tools = ['pen', 'hammer', 'lever']
and ending point. tools_slice = tools[1:3] # ['hammer',
The syntax pattern is 'lever']
myList[START_NUMBER:END_NUMBER] . tools_slice[0] = 'nail'
The slice will include the START_NUMBER index,
and everything until but excluding the # Original list is unaltered:
END_NUMBER item. print(tools) # ['pen', 'hammer',
When slicing a list, a new list is returned, so if the slice 'lever']
is saved and then altered, the original list remains the
same.

sorted() Function
The Python sorted() function accepts a list as
an argument, and will return a new, sorted list unsortedList = [4, 2, 1, 3]
containing the same elements as the original. sortedList = sorted(unsortedList)
Numerical lists will be sorted in ascending order, and print(sortedList)
lists of Strings will be sorted into alphabetical order. It # Output: [1, 2, 3, 4]
does not modify the original, unsorted list.

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet Page 5 of 5
12/28/20, 12:55 AM

Cheatsheets / Learn Python 3

Loops

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet Page 1 of 5
12/28/20, 12:55 AM

break Keyword
In a loop, the break keyword escapes the loop,
numbers = [0, 254, 2, -1, 3]
regardless of the iteration number. Once break
executes, the program will continue to execute after
the loop. for num in numbers:
In this example, the output would be: if (num < 0):
print("Negative number

0 detected!")
break

254
print(num)

2
# 0

Negative number detected!
# 254
# 2
# Negative number detected!

Python List Comprehension


Python list comprehensions provide a concise way for
creating lists. It consists of brackets containing an # List comprehension for the squares
expression followed by a for clause, then zero or more of all even numbers between 0 and 9
for or if clauses: [EXPRESSION for ITEM in result = [x**2 for x in range(10) if
LIST <if CONDITIONAL>] . x % 2 == 0]
The expressions can be anything - any kind of object
can go into a list. print(result)
A list comprehension always returns a list. # [0, 4, 16, 36, 64]

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet Page 2 of 5
12/28/20, 12:55 AM

Python For Loop


A Python for loop can be used to iterate over a list
of items and perform a set of actions on each item. for <temporary variable> in <list
The syntax of a for loop consists of assigning a variable>:
temporary value to a variable on each successive <action statement>
iteration. <action statement>
When writing a for loop, remember to properly
indent each action, otherwise an #each num in nums will be printed
IndentationError will result. below
nums = [1,2,3,4,5]
for num in nums:
print(num)

The Python continue Keyword


In Python, the continue keyword is used inside a
loop to skip the remaining code inside the loop code big_number_list = [1, 2, -1, 4, -5,
block and begin the next loop iteration. 5, 2, -9]

# Print only positive numbers:


for i in big_number_list:
if i < 0:
continue
print(i)

Python for Loops


Python for loops can be used to iterate over and
perform an action one time for each element in a list. dog_breeds = ["boxer", "bulldog",
Proper for loop syntax assigns a temporary value, "shiba inu"]
the current item of the list, to a variable on each
successive iteration: for <temporary # Print each breed:
for breed in dog_breeds:
value> in <a list>:
print(breed)
for loop bodies must be indented to avoid an
IndentationError .

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet Page 3 of 5
12/28/20, 12:55 AM

Python Loops with range().


In Python, a for loop can be used to perform an
action a speci!c number of times in a row. # Print the numbers 0, 1, 2:
The range() function can be used to create a list
for i in range(3):
that can be used to specify the number of iterations in print(i)
a for loop.
# Print "WARNING" 3 times:
for i in range(3):
print("WARNING")

In!nite Loop
An in!nite loop is a loop that never terminates. In!nite
loops result when the conditions of the loop prevent it
from terminating. This could be due to a typo in the
conditional statement within the loop or incorrect
logic. To interrupt a Python program that is running
forever, press the Ctrl and C keys together on
your keyboard.

Python while Loops


In Python, a while loop will repeatedly execute a
code block as long as a condition evaluates to # This loop will only run 1 time
True . hungry = True
while hungry:
The condition of a while loop is always checked
!rst before the block of code runs. If the condition is
print("Time to eat!")
not met initially, then the code block will never run. hungry = False

# This loop will run 5 times


i = 1
while i < 6:
print(i)
i = i + 1

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet Page 4 of 5
12/28/20, 12:55 AM

Python Nested Loops


In Python, loops can be nested inside other loops.
Nested loops can be used to access items of lists groups = [["Jobs", "Gates"],
which are inside other lists. The item selected from the ["Newton", "Euclid"], ["Einstein",
outer loop can be used as the list for the inner loop to "Feynman"]]
iterate over.

# This outer loop will iterate over


each list in the groups list
for group in groups:
# This inner loop will go through
each name in each list
for name in group:
print(name)

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-loops/cheatsheet Page 5 of 5
12/28/20, 12:56 AM

Cheatsheets / Learn Python 3

Strings

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 1 of 7
12/28/20, 12:56 AM

Strings
In computer science, sequences of characters are
referred to as strings. Strings can be any length and
can include any character such as letters, numbers,
symbols, and whitespace (spaces, tabs, new lines).

Escaping Characters
Backslashes ( \ ) are used to escape characters in a
Python string. txt = "She said \"Never let go\"."
For instance, to print a string with quotation marks, the print(txt) # She said "Never let go".
given code snippet can be used.

The in Syntax
The in syntax is used to determine if a letter or a
game = "Popular Nintendo Game: Mario
substring exists in a string. It returns True if a
Kart"
match is found, otherwise False is returned.

print("l" in game) # Prints: True


print("x" in game) # Prints: False

Indexing and Slicing Strings


Python strings can be indexed using the same notation
as lists, since strings are lists of characters. A single str = 'yellow'
character can be accessed with bracket notation str[1] # => 'e'
( [index] ), or a substring can be accessed using str[-1] # => 'w'
slicing ( [start:end] ). str[4:6] # => 'ow'
Indexing with negative numbers counts from the end str[:4] # => 'yell'
of the string. str[-3:] # => 'low'

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 2 of 7
12/28/20, 12:56 AM

Iterate String
To iterate through a string in Python, “for…in” notation
is used. str = "hello"
for c in str:
print(c)

# h
# e
# l
# l
# o

Built-in Function len()


In Python, the built-in len() function can be used
to determine the length of an object. It can be used to length = len("Hello")
compute the length of strings, lists, sets, and other print(length)
countable objects. # Output: 5

colors = ['red', 'yellow', 'green']


print(len(colors))
# Output: 3

String Concatenation
To combine the content of two strings into a single
string, Python provides the + operator. This process x = 'One fish, '
of joining strings is called concatenation. y = 'two fish.'

z = x + y

print(z)
# Output: One fish, two fish.

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 3 of 7
12/28/20, 12:56 AM

Immutable strings
Strings are immutable in Python. This means that once
a string has been de!ned, it can’t be changed.
There are no mutating methods for strings. This is
unlike data types like lists, which can be modi!ed once
they are created.

IndexError
When indexing into a string in Python, if you try to
access an index that doesn’t exist, an fruit = "Berry"
IndexError is generated. For example, the indx = fruit[6]
following code would create an IndexError :

Python String .format()


The Python string method .format() replaces
msg1 = 'Fred scored {} out of {}
empty brace ( {} ) placeholders in the string with its
arguments.
points.'
If keywords are speci!ed within the placeholders, they msg1.format(3, 10)
are replaced with the corresponding named # => 'Fred scored 3 out of 10
arguments to the method. points.'

msg2 = 'Fred {verb} a {adjective}


{noun}.'
msg2.format(adjective='fluffy',
verb='tickled', noun='hamster')
# => 'Fred tickled a fluffy hamster.'

String Method .lower()


The string method .lower() returns a string with
all uppercase characters converted into lowercase. greeting = "Welcome To Chili's"

print(greeting.lower())
# Prints: welcome to chili's

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 4 of 7
12/28/20, 12:56 AM

String Method .strip()


The string method .strip() can be used to
remove characters from the beginning and end of a text1 = ' apples and oranges '
string. text1.strip() # => 'apples and
A string argument can be passed to the method, oranges'
specifying the set of characters to be stripped. With
no arguments to the method, whitespace is removed. text2 = '...+...lemons and
limes...-...'

# Here we strip just the "."


characters
text2.strip('.') # => '+...lemons
and limes...-'

# Here we strip both "." and "+"


characters
text2.strip('.+') # => 'lemons and
limes...-'

# Here we strip ".", "+", and "-"


characters
text2.strip('.+-') # => 'lemons and
limes'

String Method .title()


The string method .title() returns the string in
title case. With title case, the !rst character of each my_var = "dark knight"
word is capitalized while the rest of the characters are print(my_var.title())
lowercase.
# Prints: Dark Knight

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 5 of 7
12/28/20, 12:56 AM

String Method .split()


The string method .split() splits a string into a
list of items: text = "Silicon Valley"

● If no argument is passed, the default behavior is print(text.split())


to split on whitespace. # Prints: ['Silicon', 'Valley']
● If an argument is passed to the method, that
value is used as the delimiter on which to split print(text.split('i'))
the string. # Prints: ['S', 'l', 'con Valley']

Python string method .find()


The Python string method .find() returns the
index of the !rst occurrence of the string passed as mountain_name = "Mount Kilimanjaro"
the argument. It returns -1 if no occurrence is
print(mountain_name.find("o")) #
found. Prints 1 in the console.

String replace
The .replace() method is used to replace the
occurence of the !rst argument with the second fruit = "Strawberry"
argument within the string. print(fruit.replace('r', 'R'))
The !rst argument is the old substring to be replaced,
and the second argument is the new substring that will # StRawbeRRy
replace every occurence of the !rst one within the
string.

String Method .upper()


The string method .upper() returns the string
with all lowercase characters converted to uppercase. dinosaur = "T-Rex"

print(dinosaur.upper())
# Prints: T-REX

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 6 of 7
12/28/20, 12:56 AM

String Method .join()


The string method .join() concatenates a list of
strings together to create a new string joined with the x = "-".join(["Codecademy", "is",
desired delimiter. "awesome"])
The .join() method is run on the delimiter and
the array of strings to be concatenated together is print(x)
passed in as an argument. # Prints: Codecademy-is-awesome

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-strings/cheatsheet Page 7 of 7
12/28/20, 12:56 AM

Cheatsheets / Learn Python 3

Modules

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-modules/cheatsheet Page 1 of 4
12/28/20, 12:56 AM

Date and Time in Python


Python provides a module named datetime to
deal with dates and times. import datetime
It allows you to set date , time or both date
feb_16_2019
= datetime.date(year=2019, month=2,
and time using the date() , time() and
day=16)
datetime() functions respectively, after
feb_16_2019 = datetime.date(2019, 2,
importing the datetime module .
16)
print(feb_16_2019) #2019-02-16

time_13_48min_5sec
= datetime.time(hour=13, minute=48,
second=5)
time_13_48min_5sec
= datetime.time(13, 48, 5)
print(time_13_48min_5sec) #13:48:05

timestamp=
datetime.datetime(year=2019, month=2,
day=16, hour=13, minute=48, second=5)
timestamp = datetime.datetime(2019,
2, 16, 13, 48, 5)
print (timestamp) #2019-01-02
13:48:05

Aliasing with ‘as’ keyword


In Python, the as keyword can be used to give an
alternative name as an alias for a Python module or # Aliasing matplotlib.pyplot as plt
function. from matplotlib import pyplot as plt
plt.plot(x, y)

# Aliasing calendar as c
import calendar as c
print(c.month_name[1])

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-modules/cheatsheet Page 2 of 4
12/28/20, 12:56 AM

Import Python Modules


The Python import statement can be used to import
Python modules from other !les. # Three different ways to import
Modules can be imported in three di"erent ways: modules:
import module , from module import # First way
functions , or from module import * . import module
from module import * is discouraged, as it module.function()
can lead to a cluttered local namespace and can make
the namespace unclear. # Second way
from module import function
function()

# Third way
from module import *
function()

random.randint() and random.choice()


In Python, the random module o"ers methods to
simulate non-deterministic behavior in selecting a # Returns a random integer N in
random number from a range and choosing a random a given range, such that start <=
item from a list. N <= end
The randint() method provides a uniform # random.randint(start, end)
random selection from a range of integers. The r1 = random.randint(0, 10)
choice() method provides a uniform selection of print(r1) # Random integer where 0 <=
a random element from a sequence. r1 <= 10

# Prints a random element from


a sequence
seq = ["a", "b", "c", "d", "e"]
r2 = random.choice(seq)
print(r2) # Random element in the
sequence

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-modules/cheatsheet Page 3 of 4
12/28/20, 12:56 AM

Module importing
In Python, you can import and use the content of
another !le using import filename , provided # file1 content
that it is in the same folder as the current !le you are # def f1_function():
writing. # return "Hello World"

# file2
import file1

# Now we can use f1_function, because


we imported file1
f1_function()

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-modules/cheatsheet Page 4 of 4
12/28/20, 12:56 AM

Cheatsheets / Learn Python 3

Dictionaries

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 1 of 4
12/28/20, 12:56 AM

Accessing and writing data in a Python dictionary


Values in a Python dictionary can be accessed by
placing the key within square brackets next to the my_dictionary = {"song": "Estranged",
dictionary. Values can be written by placing key within "artist": "Guns N' Roses"}
square brackets next to the dictionary and using the print(my_dictionary["song"])
assignment operator ( = ). If the key already exists, the my_dictionary["song"] = "Paradise
old value will be overwritten. Attempting to access a City"
value with a key that does not exist will cause a
KeyError .
To illustrate this review card, the second line of the
example code block shows the way to access the value
using the key "song" . The third line of the code
block overwrites the value that corresponds to the key
"song" .

Syntax of the Python dictionary


The syntax for a Python dictionary begins with the left
curly brace ( { ), ends with the right curly brace ( } ), roaster = {"q1": "Ashley", "q2":
and contains zero or more key : value items
"Dolly"}

separated by commas ( , ). The key is separated


from the value by a colon ( : ).

Merging Dictionaries with the .update() Method in Python


Given two dictionaries that need to be combined,
Python makes this easy with the .update() dict1 = {'color': 'blue', 'shape':
function. 'circle'}
For dict1.update(dict2) , the key-value dict2 = {'color': 'red', 'number':
pairs of dict2 will be written into the dict1 42}
dictionary.
For keys in both dict1 and dict2 , the value in dict1.update(dict2)

dict1 will be overwritten by the corresponding


# dict1 is now {'color': 'red',
value in dict2 .
'shape': 'circle', 'number': 42}

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 2 of 4
12/28/20, 12:56 AM

Dictionary value types


Python allows the values in a dictionary to be any type
– string, integer, a list, another dictionary, boolean, dictionary = {
etc. However, keys must always be an immutable data 1: 'hello',
type, such as strings, numbers, or tuples. 'two': True,
In the example code block, you can see that the keys '3': [1, 2, 3],
are strings or numbers (int or !oat). The values, on the
'Four': {'fun': 'addition'},
other hand, are many varied data types.
5.0: 5.5
}

Python dictionaries
A python dictionary is an unordered collection of
items. It contains data as a set of key: value pairs. my_dictionary = {1: "L.A. Lakers", 2:
"Houston Rockets"}

Dictionary accession methods


When trying to look at the information in a Python
dictionary, there are multiple methods that access the ex_dict = {"a": "anteater", "b":
dictionary and return lists of its contents. "bumblebee", "c": "cheetah"}
.keys() returns the keys (the "rst object in the
key-value pair), .values() returns the values ex_dict.keys()
(the second object in the key-value pair), and # ["a","b","c"]
.items() returns both the keys and the values as
a tuple. ex_dict.values()
# ["anteater", "bumblebee",
"cheetah"]

ex_dict.items()
# [("a","anteater"),
("b","bumblebee"),("c","cheetah")]

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 3 of 4
12/28/20, 12:56 AM

get() Method for Dictionary


Python provides a .get() method to access a
# without default
dictionary value if it exists. This method takes
{"name": "Victor"}.get("name")
the key as the "rst argument and an optional
# returns "Victor"
default value as the second argument, and it returns
the value for the speci"ed key if key is in the
{"name": "Victor"}.get("nickname")
dictionary. If the second argument is not speci"ed and
# returns None
key is not found then None is returned.

# with default
{"name": "Victor"}.get("nickname",
"nickname is not a key")
# returns "nickname is not a key"

The .pop() Method for Dictionaries in Python


Python dictionaries can remove key-value pairs with
the .pop() method. The method takes a key as an famous_museums = {'Washington':
argument and removes it from the dictionary. At the 'Smithsonian Institution', 'Paris':
same time, it also returns the value that it removes 'Le Louvre', 'Athens': 'The Acropolis
from the dictionary. Museum'}
famous_museums.pop('Athens')
print(famous_museums) #
{'Washington': 'Smithsonian
Institution', 'Paris': 'Le Louvre'}

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 4 of 4
12/28/20, 12:57 AM

Cheatsheets / Learn Python 3

Files

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 1 of 7
12/28/20, 12:57 AM

Python File Object


A Python !le object is created when a !le is opened
with the open() function. You can associate this
!le object with a variable when you open a !le using
the with and as keywords. For example:

with open('somefile.txt') as
file_object:

You can then print the content of the !le object,


file_object with print() .

print(file_object)

You might see something like this on the output


terminal:

<_io.TextIOWrapper
name='somefile.txt' mode='r'
encoding='UTF-8'>

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 2 of 7
12/28/20, 12:57 AM

Python Readline Method


To read only one line instead of multiple lines in a
Python !le, use the method .readline() on a
!le object that is returned from the open()
function. Every subsequent .readline() will
extract the next line in the !le if it exists.

with open('story.txt') as
story_object:
print(story_object.readline(
))

will print only the !rst line in story.txt .

Parsing JSON !les to dictionary


JSON format is used to store key value pairs. Python’s
json module allows reading such data format and # Use json.load with an opened file
parsing it to a dictionary. The json.load function object to read the contents into
takes a !le object as an argument and returns the data a Python dictionary.
in a dictionary format.
# Contents of file.json
# { 'userId': 10 }

import json
with open('file.json') as json_file:
python_dict = json.load(json_file)

print(python_dict.get('userId'))
# Prints 10

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 3 of 7
12/28/20, 12:57 AM

Python Append To File


Writing to an opened !le with the 'w' "ag
overwrites all previous content in the !le. To avoid this,
we can append to a !le instead. Use the 'a' "ag as
the second argument to open() . If a !le doesn’t
exist, it will be created for append mode.

with open('shopping.txt', 'a')


as shop:
shop.write('Tomatoes,
cucumbers, celery\n')

Python Write To File


By default, a !le when opened with open() is only
for reading. A second argument 'r' is passed to it
by default. To write to a !le, !rst open the !le with
write permission via the 'w' argument. Then use
the .write() method to write to the !le. If the
!le already exists, all prior content will be overwritten.

with open('diary.txt','w') as
diary:
diary.write('Special events
for today')

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 4 of 7
12/28/20, 12:57 AM

Python Readlines Method


Instead of reading the entire content of a !le, you can
read a single line at a time. Instead of .read()
which returns a string, call .readlines() to
return a list of strings, each representing an individual
line in the !le. Calling this code:

with open('lines.txt') as
file_object:
file_data
= file_object.readlines()
print(file_data)

returns a list of strings in file_data :

['1. Learn Python.\n', '2.


Work hard.\n', '3. Graduate.']

Iterating over the list, file_data , and printing it:

for line in file_data:


print(line)

outputs:

1. Learn Python.

2. Work hard.

3. Graduate.

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 5 of 7
12/28/20, 12:57 AM

Class csv.DictWriter
In Python, the csv module implements classes to
read and write tabular data in CSV format. It has a # An example of csv.DictWriter
class DictWriter which operates like a regular import csv
writer but maps a dictionary onto output rows. The
keys of the dictionary are column names while values with open('companies.csv', 'w') as
are actual data. csvfile:
The csv.DictWriter constructor takes two fieldnames = ['name', 'type']
arguments. The !rst is the open !le handler that the writer = csv.DictWriter(csvfile,
CSV is being written to. The second named parameter, fieldnames=fieldnames)
fieldnames , is a list of !eld names that the CSV writer.writeheader()
is going to handle. writer.writerow({'name':
'Codecademy', 'type': 'Learning'})
writer.writerow({'name': 'Google',
'type': 'Search'})

"""
After running the above code,
companies.csv will contain the
following information:

name,type
Codecademy,Learning
Google,Search
"""

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 6 of 7
12/28/20, 12:57 AM

Python Read Method


After a !le is opened with open() returning a !le
object, call the .read() method of the !le object
to return the entire !le content as a Python string.
Executing the following Python code:

with open('mystery.txt') as
text_file:
text_data = text_file.read()
print(text_data)

will produce a string containing the entire content of


the read !le:

Mystery solved.
Congratulations!

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-files/cheatsheet Page 7 of 7
12/28/20, 12:57 AM

Cheatsheets / Learn Python 3

Classes

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 1 of 9
12/28/20, 12:57 AM

Python repr method


The Python __repr__() method is used to tell
Python what the string representation of the class class Employee:
should be. It can only have one parameter, self ,
def __init__(self, name):
and it should return a string. self.name = name

def __repr__(self):
return self.name

john = Employee('John')
print(john) # John

Python class methods


In Python, methods are functions that are de!ned as
part of a class. It is common practice that the !rst # Dog class
argument of any method that is part of a class is the class Dog:
actual object calling the method. This argument is # Method of the class
usually called self.
def bark(self):
print("Ham-Ham")

# Create a new instance


charlie = Dog()

# Call the method


charlie.bark()
# This will output "Ham-Ham"

Instantiate Python Class


In Python, a class needs to be instantiated before use.
As an analogy, a class can be thought of as a blueprint class Car:
(Car), and an instance is an actual implementation of "This is an empty class"
the blueprint (Ferrari). pass

# Class Instantiation
ferrari = Car()

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 2 of 9
12/28/20, 12:57 AM

Python Class Variables


In Python, class variables are de!ned outside of all
methods and have the same value for every instance class my_class:
of the class. class_variable = "I am a Class
Class variables are accessed with the Variable!"
instance.variable or
class_name.variable syntaxes. x = my_class()
y = my_class()

print(x.class_variable) #I am a Class
Variable!
print(y.class_variable) #I am a Class
Variable!

Python init method


In Python, the .__init__() method is used to
initialize a newly created object. It is called every time class Animal:
the class is instantiated. def __init__(self, voice):
self.voice = voice

# When a class instance is created,


the instance variable
# 'voice' is created and set to the
input value.
cat = Animal('Meow')
print(cat.voice) # Output: Meow

dog = Animal('Woof')
print(dog.voice) # Output: Woof

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 3 of 9
12/28/20, 12:57 AM

Python type() function


The Python type() function returns the data type
of the argument passed to it. a = 1
print(type(a)) # <class 'int'>

a = 1.1
print(type(a)) # <class 'float'>

a = 'b'
print(type(a)) # <class 'str'>

a = None
print(type(a)) # <class 'NoneType'>

Python class
In Python, a class is a template for a data type. A class
can be de!ned using the class keyword. # Defining a class
class Animal:
def __init__(self, name,
number_of_legs):
self.name = name
self.number_of_legs
= number_of_legs

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 4 of 9
12/28/20, 12:57 AM

Python dir() function


In Python, the built-in dir() function, without any
argument, returns a list of all the attributes in the class Employee:
current scope. def __init__(self, name):
With an object as argument, dir() tries to return self.name = name
all valid object attributes.
def print_name(self):
print("Hi, I'm " + self.name)

print(dir())
# ['Employee', '__builtins__',
'__doc__', '__file__', '__name__',
'__package__', 'new_employee']

print(dir(Employee))
# ['__doc__', '__init__',
'__module__', 'print_name']

__main__ in Python
In Python, __main__ is an identi!er used to
reference the current !le context. When a module is
read from standard input, a script, or from an
interactive prompt, its __name__ is set equal to
__main__ .
Suppose we create an instance of a class called
CoolClass . Printing the type() of the
instance will result in:

<class '__main__.CoolClass'>

This means that the class CoolClass was de!ned


in the current script !le.

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 5 of 9
12/28/20, 12:57 AM

Super() Function in Python Inheritance


Python’s super() function allows a subclass to
invoke its parent’s version of an overridden method. class ParentClass:
def print_test(self):
print("Parent Method")

class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
# Calls the parent's version of
print_test()
super().print_test()

child_instance = ChildClass()
child_instance.print_test()
# Output:
# Child Method
# Parent Method

User-de!ned exceptions in Python


In Python, new exceptions can be de!ned by creating
a new class which has to be derived, either directly or class CustomError(Exception):
indirectly, from Python’s Exception class. pass

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 6 of 9
12/28/20, 12:57 AM

Polymorphism in Python
When two Python classes o"er the same set of
methods with di"erent implementations, the classes class ParentClass:
are polymorphic and are said to have the same def print_self(self):
interface. An interface in this sense might involve a print('A')
common inherited class and a set of overridden
methods. This allows using the two objects in the same
class ChildClass(ParentClass):
way regardless of their individual types.
def print_self(self):
When a child class overrides a method of a parent
print('B')
class, then the type of the object determines the
version of the method to be called. If the object is an
instance of the child class, then the child class version obj_A = ParentClass()
of the overridden method will be called. On the other obj_B = ChildClass()
hand, if the object is an instance of the parent class,
then the parent class version of the method is called. obj_A.print_self() # A
obj_B.print_self() # B

Dunder methods in Python


Dunder methods, which stands for “Double Under”
(Underscore) methods, are special methods which class String:
have double underscores at the beginning and end of # Dunder method to initialize
their names. object
We use them to create functionality that can’t be
def __init__(self, string):
represented as a normal method, and resemble native
self.string = string
Python data type interactions. A few examples for
dunder methods are: __init__ , __add__ ,
string1 = String("Hello World!")
__len__ , and __iter__ . print(string1.string) # Hello World!
The example code block shows a class with a de!nition
for the __init__ dunder method.

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 7 of 9
12/28/20, 12:57 AM

Method Overriding in Python


In Python, inheritance allows for method overriding,
which lets a child class change and rede!ne the class ParentClass:
implementation of methods already de!ned in its def print_self(self):
parent class. print("Parent")
The following example code block creates a
ParentClass and a ChildClass which class ChildClass(ParentClass):
both de!ne a print_test() method. def print_self(self):
As the ChildClass inherits from the print("Child")
ParentClass , the method print_test()
will be overridden by ChildClass such that it child_instance = ChildClass()
prints the word “Child” instead of “Parent”. child_instance.print_self() # Child

Python issubclass() Function


The Python issubclass() built-in function
checks if the !rst argument is a subclass of the second class Family:
argument. def type(self):
In the example code block, we check that Member print("Parent class")
is a subclass of the Family class.
class Member(Family):
def type(self):
print("Child class")

print(issubclass(Member, Family)) #
True

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 8 of 9
12/28/20, 12:57 AM

Python Inheritance
Subclassing in Python, also known as “inheritance”,
allows classes to share the same attributes and class Animal:
methods from a parent or superclass. Inheritance in def __init__(self, name, legs):
Python can be accomplished by putting the superclass self.name = name
name between parentheses after the subclass or child
self.legs = legs
class name.
In the example code block, the Dog class subclasses
class Dog(Animal):
the Animal class, inheriting all of its attributes. def sound(self):
print("Woof!")

Yoki = Dog("Yoki", 4)
print(Yoki.name) # YOKI
print(Yoki.legs) # 4
Yoki.sound() # Woof!

+ Operator
In Python, the + operation can be de!ned for a
user-de!ned class by giving that class an class A:
.__add()__ method. def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other.a

obj1 = A(5)
obj2 = A(10)
print(obj1 + obj2) # 15

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-classes/cheatsheet Page 9 of 9
12/28/20, 12:57 AM

Cheatsheets / Learn Python 3

Function Arguments

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-function-arguments/cheatsheet Page 1 of 4
12/28/20, 12:57 AM

Default argument is fallback value


In Python, a default parameter is de!ned with a
fallback value as a default argument. Such parameters def greet(name, msg="How do you
are optional during a function call. If no argument is do?"):
provided, the default value is used, and if an argument print("Hello ", name + ', ' + msg)
is provided, it will overwrite the default value.

greet("Ankit")
greet("Ankit", "How do you do?")

"""
this code will print the following
for both the calls -
`Hello Ankit, How do you do?`
"""

Mutable Default Arguments


Python’s default arguments are evaluated only once
when the function is de!ned, not each time the # Here, an empty list is used as
function is called. This means that if a mutable default a default argument of the function.
argument is used and is mutated, it is mutated for all def append(number, number_list=[]):
future calls to the function as well. This leads to buggy number_list.append(number)
behaviour as the programmer expects the default
print(number_list)
value of that argument in each function call.
return number_list

# Below are 3 calls to the `append`


function and their expected and
actual outputs:
append(5) # expecting: [5], actual:
[5]
append(7) # expecting: [7], actual:
[5, 7]
append(2) # expecting: [2], actual:
[5, 7, 2]

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-function-arguments/cheatsheet Page 2 of 4
12/28/20, 12:57 AM

Python Default Arguments


A Python function cannot de!ne a default argument in
its signature before any required parameters that do # Correct order of declaring default
not have a default argument. Default arguments are argments in a function
ones set using the form parameter=value . If def greet(name, msg = "Good
no input value is provided for such arguments, it will morning!"):
take on the default value. print("Hello ", name + ', ' + msg)

# The function can be called in the


following ways
greet("Ankit")
greet("Kyla","How are you?")

# The following function definition


would be incorrect
def greet(msg = "Good morning!",
name):
print("Hello ", name + ', ' + msg)
# It would cause a "SyntaxError: non-
default argument follows default
argument"

Python function default return value


If we do not not specify a return value for a Python
function, it returns None . This is the default # Function returning None
behaviour. def my_function(): pass

print(my_function())

#Output
None

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-function-arguments/cheatsheet Page 3 of 4
12/28/20, 12:57 AM

Python variable None check


To check if a Python variable is None we can make use
of the statement variable is None . # Variable check for None
If the above statement evaluates to True, the if variable_name is None:
variable value is None. print "variable is None"
else:
print "variable is NOT None"

Python function arguments


A function can be called using the argument name as a
keyword instead of relying on its positional value. # The function will take arg1 and
Functions de!ne the argument names in its arg2
composition then those names can be used when def func_with_args(arg1, arg2):
calling the function. print(arg1 + ' ' + arg2)

func_with_args('First', 'Second')
# Prints:
# First Second

func_with_args(arg2='Second',
arg1='First')
# Prints
# First Second

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-function-arguments/cheatsheet Page 4 of 4

You might also like