Learn Python 3 - Python - Code Challenges (Optional) Cheatsheet - Codecademy
Learn Python 3 - Python - Code Challenges (Optional) Cheatsheet - Codecademy
or Operator
The Python or operator combines two Boolean expressions and evaluates to True if True or True # Evaluates to True
at least one of the expressions returns True . Otherwise, if both expressions are
True or False # Evaluates to True
False , then the entire expression evaluates to False .
False or 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
Comparison Operators
In Python, relational operators compare two values or expressions. The most common a = 2
ones are:
b = 3
< less than
> greater than a < b # evaluates to True
<= less than or equal to a > b # evaluates to False
>= greater than or equal too a >= b # evaluates to False
If the relation is sound, then the entire expression will evaluate to True . If not, the
a <= b # evaluates to True
expression evaluates to False .
a <= a # evaluates to True
https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 1/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
if Statement
The Python if statement is used to determine the execution of code based on the # if Statement
evaluation of a Boolean expression.
If the if statement expression evaluates to True , then the indented code
following the statement is executed. test_value = 100
If the expression evaluates to False then the indented code following the if
statement is skipped and the program executes the next line of code which is
if test_value > 1:
indented at the same level as the if statement.
# Expression evaluates to True
print("This code is executed!")
https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 2/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
else Statement
The Python else statement provides alternate code to execute if the expression in an # else Statement
if statement evaluates to False .
The indented code for the if statement is executed if the expression evaluates to
True . The indented code immediately following the else is executed only if the test_value = 50
expression evaluates to False . To mark the end of the else block, the code must be
unindented to the same level as the starting if line. if test_value < 1:
print("Value is < 1")
else:
print("Value is >= 1")
test_string = "VALID"
if test_string == "NOT_VALID":
print("String equals NOT_VALID")
else:
print("String equals something else!")
and Operator
The Python and operator performs a Boolean comparison between two Boolean True and True # Evaluates to True
values, variables, or expressions. If both sides of the operator evaluate to True then
True and False # Evaluates to False
the and operator returns True . If either side (or both sides) evaluates to False ,
then the and operator returns False . A non-Boolean value (or variable that stores a False and False # Evaluates to False
value) will always evaluate to True when used with the and operator. 1 == 1 and 1 < 2 # Evaluates to True
1 < 2 and 3 < 1 # Evaluates to False
"Yes" and 100 # Evaluates to True
https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 3/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
The .count() Python list method searches a list for whatever search term it receives backpack = ['pencil', 'pen', 'notebook', 'textbook', 'pen',
as an argument, then returns the number of matching entries found.
'highlighter', 'pen']
numPen = backpack.count('pen')
print(numPen)
# Output: 3
In Python, lists can be added to each other using the plus symbol + . As shown in the items = ['cake', 'cookie', 'bread']
code block, this will result in a new list containing the same items in the same order
total_items = items + ['biscuit', 'tart']
with the first list’s items coming first.
Note: This will not work for adding one item at a time (use .append() method). In print(total_items)
order to add one item, create a new list with a single value and then use the plus # Result: ['cake', 'cookie', 'bread', 'biscuit', 'tart']
symbol to add the list.
The Python len() function can be used to determine the number of items found in knapsack = [2, 4, 3, 7, 10]
the list it accepts as an argument.
size = len(knapsack)
print(size)
# Output: 5
https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 4/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
Zero-Indexing
In Python, list index begins at zero and ends at the length of the list minus one. For names = ['Roger', 'Rafael', 'Andy', 'Novak']
example, in this list, 'Andy' is found at index 2 .
List Slicing
A slice, or sub-list of Python list elements can be selected from a list using a colon- tools = ['pen', 'hammer', 'lever']
separated starting and ending point.
tools_slice = tools[1:3] # ['hammer', 'lever']
The syntax pattern is myList[START_NUMBER:END_NUMBER] . The slice will
include the START_NUMBER index, and everything until but excluding the tools_slice[0] = 'nail'
END_NUMBER item.
When slicing a list, a new list is returned, so if the slice is saved and then altered, the
# Original list is unaltered:
original list remains the same.
print(tools) # ['pen', 'hammer', 'lever']
https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 5/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
elif Statement
The Python elif statement allows for continued checks to be performed after an # elif Statement
initial if statement. An elif statement differs from the else statement because
another expression is provided to be checked, just as with the initial if statement.
If the expression is True , the indented code following the elif is executed. If the pet_type = "fish"
expression evaluates to False , the code can continue to an optional else statement.
Multiple elif statements can be used following an initial if to perform a series of if pet_type == "dog":
checks. Once an elif expression evaluates to True , no further elif statements are
print("You have a dog.")
executed.
elif pet_type == "cat":
print("You have a cat.")
elif pet_type == "fish":
# this is performed
print("You have a fish")
else:
print("Not sure!")
https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 6/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
Equal Operator ==
The equal operator, == , is used to compare two values, variables or expressions to # Equal operator
determine if they are the same.
If the values being compared are the same, the operator returns True , otherwise it
returns False . if 'Yes' == 'Yes':
The operator takes the data type into account when making the comparison, so a # evaluates to True
string value of "2" is not considered the same as a numeric value of 2 . print('They are equal')
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/cspath-code-challenges/cheatsheet 7/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
The Python not equals operator, != , is used to compare two values, variables or # Not Equals Operator
expressions to determine if they are NOT the same. If they are NOT the same, the
operator returns True . If they are the same, then it returns False .
The operator takes the data type into account when making the comparison so a value if "Yes" != "No":
of 10 would NOT be equal to the string value "10" and the operator would return # evaluates to True
True . If expressions are used, then they are evaluated to a value of True or False print("They are NOT equal")
before the comparison is made by the operator.
val1 = 10
val2 = 20
if val1 != val2:
print("They are NOT equal")
Function Parameters
Sometimes functions require input to provide data for their code. This input is defined def write_a_book(character, setting, special_skill):
using parameters.
print(character + " is in " +
Parameters are variables that are defined in the function definition. They are assigned
the values which were passed as arguments when the function was called, elsewhere in setting + " practicing her " +
the code. special_skill)
For example, the function definition defines parameters for a character, a setting, and a
skill, which are used as inputs to write the first sentence of a book.
https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 8/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
Function Indentation
Python uses indentation to identify blocks of code. Code within the same block should # Indentation is used to identify code blocks
be indented at the same level. A Python function is one type of code block. All code
under a function declaration should be indented to identify it as part of the function.
There can be additional indentation within a function to handle other statements such def testfunction(number):
as for and if so long as the lines are not indented less than the first line of the # This code is part of testfunction
function code.
print("Inside the testfunction")
sum = 0
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")
A return keyword is used to return a value from a Python function. The value returned def check_leap_year(year):
from a function can be assigned to a variable which can then be used in the program.
if year % 4 == 0:
In the example, the function check_leap_year returns a string which indicates if the
passed parameter is a leap year or not. return str(year) + " is a leap year."
else:
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/cspath-code-challenges/cheatsheet 9/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
Function parameters behave identically to a function’s local variables. They are def my_function(value):
initialized with the values passed into the function when it was called.
print(value)
Like local variables, parameters cannot be referenced from outside the scope of the
function.
In the example, the parameter value is defined as part of the definition of # Pass the value 7 into the function
my_function , and therefore can only be accessed within my_function . Attempting
my_function(7)
to print the contents of value from outside the function causes an error.
Multiple Parameters
Python functions can have multiple parameters. Just as you wouldn’t go to school def ready_for_school(backpack, pencil_case):
without both a backpack and a pencil case, functions may also need more than one
if (backpack == 'full' and pencil_case == 'full'):
input to carry out their operations.
To define a function with multiple parameters, parameter names are placed one after print ("I'm ready for school!")
another, separated by commas, within the parentheses of the function definition.
Function Arguments
Parameters in python are variables — placeholders for the actual values the function def sales(grocery_store, item_on_sale, cost):
needs. When the function is called, these values are passed in as arguments.
print(grocery_store + " is selling " + item_on_sale + " for
For example, the arguments passed into the function .sales() are the “The Farmer’s
Market”, “toothpaste”, and “$1” which correspond to the parameters grocery_store , " + cost)
item_on_sale , and cost .
sales("The Farmer’s Market", "toothpaste", "$1")
https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 10/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
In Python, you can add values to the end of a list using the .append() method. This orders = ['daisies', 'periwinkle']
will place the object passed in as a new element at the very end of the list. Printing the
orders.append('tulips')
list afterwards will visually show the appended value. This .append() method is not to
be confused with returning an entirely new list with the passed object. print(orders)
# Result: ['daisies', 'periwinkle', 'tulips']
List Indices
Python list elements are ordered by index, a number referring to their placement in the berries = ["blueberry", "cranberry", "raspberry"]
list. List indices start at 0 and increment by one.
To access a list element by index, square bracket notation is used: list[index] .
berries[0] # "blueberry"
berries[2] # "raspberry"
Negative indices for lists in Python can be used to reference elements in relation to the soups = ['minestrone', 'lentil', 'pho', 'laksa']
end of a list. This can be used to access single list elements or as part of defining a list
soups[-1] # 'laksa'
range. For instance:
To select the last element, my_list[-1] . soups[-3:] # 'lentil', 'pho', 'laksa'
To select the last three elements, my_list[-3:] . soups[:-2] # 'minestrone', 'lentil'
To select everything except the last two elements, my_list[:-2] .
https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 11/12
09/12/2023, 08:09 Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy
sorted() Function
The Python sorted() function accepts a list as an argument, and will return a new, unsortedList = [4, 2, 1, 3]
sorted list containing the same elements as the original. Numerical lists will be sorted in
sortedList = sorted(unsortedList)
ascending order, and lists of Strings will be sorted into alphabetical order. It does not
modify the original, unsorted list. print(sortedList)
# Output: [1, 2, 3, 4]
Print Share
https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 12/12