Learn Python 3 - Python - Code Challenges (Optional) Cheatsheet - Codecademy
Learn Python 3 - Python - Code Challenges (Optional) Cheatsheet - Codecademy
Comparison Operators
In Python, relational operators compare two values or
expressions. The most common ones are: a = 2
b = 3
< less than
if Statement
The Python if statement is used to determine the
execution of code based on the evaluation of a Boolean # if Statement
expression.
test_value = 100
If the if statement expression evaluates to
if test_value > 1:
statement is executed.
else Statement
The Python else statement provides alternate code to
execute if the expression in an if statement evaluates # else Statement
to False .
The indented code for the if statement is executed if test_value = 50
the expression evaluates to True . The indented code
immediately following the else is executed only if the
if test_value < 1:
expression evaluates to False . To mark the end of the
print("Value is < 1")
else block, the code must be unindented to the same
else:
level as the starting if line.
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 values, variables, or True and True # Evaluates to True
expressions. If both sides of the operator evaluate to True and False # Evaluates to False
True then the and operator returns True . If either False and False # Evaluates to False
side (or both sides) evaluates to False , then the and 1 == 1 and 1 < 2 # Evaluates to True
operator returns False . A non-Boolean value (or
1 < 2 and 3 < 1 # Evaluates to False
variable that stores a value) will always evaluate to
"Yes" and 100 # Evaluates to True
True when used with the and operator.
elif Statement
The Python elif statement allows for continued
checks to be performed after an initial if statement. # elif Statement
An elif statement differs from the else statement
because another expression is provided to be checked, pet_type = "fish"
just as with the initial if statement.
If the expression is True , the indented code following
if pet_type == "dog":
the elif is executed. If the expression evaluates to
print("You have a dog.")
False , the code can continue to an optional else
elif pet_type == "cat":
statement. Multiple elif statements can be used
print("You have a cat.")
following an initial if to perform a series of checks.
Once an elif expression evaluates to True , no elif pet_type == "fish":
further elif statements are executed. # this is performed
print("You have a fish")
else:
print("Not sure!")
Equal Operator ==
The equal operator, == , is used to compare two
values, variables or expressions to determine if they are # Equal operator
the same.
If the values being compared are the same, the if 'Yes' == 'Yes':
operator returns True , otherwise it returns False . # evaluates to True
The operator takes the data type into account when
print('They are equal')
making the comparison, so a string value of "2" is not
considered the same as a numeric value of 2 .
if (2 > 1) == (5 < 10):
# 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')
print(numPen)
# Output: 3
print(size)
# Output: 5
print(orders)
appended value. This .append() method is not to be
List Indices
Python list elements are ordered by index, a number
referring to their placement in the list. List indices start berries = ["blueberry", "cranberry",
at 0 and increment by one. "raspberry"]
To access a list element by index, square bracket
berries[0] # "blueberry"
berries[2] # "raspberry"
sorted() Function
The Python sorted() function accepts a list as an
argument, and will return a new, sorted list containing unsortedList = [4, 2, 1, 3]
the same elements as the original. Numerical lists will sortedList = sorted(unsortedList)
be sorted in ascending order, and lists of Strings will be
print(sortedList)
sorted into alphabetical order. It does not modify the
# Output: [1, 2, 3, 4]
original, unsorted list.
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 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']
tools_slice[0] = 'nail'
everything until but excluding the END_NUMBER item.
Function Parameters
Sometimes functions require input to provide data for
their code. This input is defined using parameters. def write_a_book(character, setting,
Parameters are variables that are defined in the special_skill):
function definition.
They are assigned the values which
special_skill)
For example, the function definition defines parameters
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 code
same level. A Python function is one type of code blocks
block. All code under a function declaration should be
def testfunction(number):
be additional indentation within a function to handle
sum = 0
function code.
for x in range(number):
sum += x
return sum
Function Arguments
Parameters in python are variables — placeholders for
the actual values the function needs. When the def sales(grocery_store, item_on_sale,
function is called, these values are passed in as cost):
arguments.
year_to_check = 2018
returned_value
= check_leap_year(year_to_check)
print(returned_value) # 2018 is not
a leap year.