0% found this document useful (0 votes)
3 views9 pages

Learn Python 3_ Python_ Code Challenges (Optional) Cheatsheet _ Codecademy

This document is a cheatsheet for Python 3, covering key concepts such as Boolean operators (or, and), comparison operators, if-else statements, function parameters, and list methods. It provides examples for each concept to illustrate their usage in Python programming. The cheatsheet serves as a quick reference for learners to understand and apply Python syntax and functions effectively.

Uploaded by

sohaibade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

Learn Python 3_ Python_ Code Challenges (Optional) Cheatsheet _ Codecademy

This document is a cheatsheet for Python 3, covering key concepts such as Boolean operators (or, and), comparison operators, if-else statements, function parameters, and list methods. It provides examples for each concept to illustrate their usage in Python programming. The cheatsheet serves as a quick reference for learners to understand and apply Python syntax and functions effectively.

Uploaded by

sohaibade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

9/29/24, 1:08 AM Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy

Cheatsheets / Learn Python 3

Python: Code Challenges (Optional)

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
expressions are False , then the entire expression False or False # Evaluates to 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 a = 2


expressions. The most common 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 expression evaluates to
a <= b # evaluates to True
False . a <= a # evaluates to True

https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 1/9
9/29/24, 1:08 AM Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy

if Statement

The Python if statement is used to determine the # if Statement


execution of code based on the evaluation of a Boolean
expression.
If the if statement expression evaluates to test_value = 100
True , then the indented code following the
statement is executed.
if test_value > 1:
If the expression evaluates to False then the
# Expression evaluates to True
indented code following the if statement is
skipped and the program executes the next line print("This code is executed!")
of code which is indented at the same level as
the if statement.
if test_value > 1000:
# Expression evaluates to False
print("This code is NOT executed!")

print("Program continues at this point.")

else Statement

The Python else statement provides alternate code to # else Statement


execute if the expression in an if statement evaluates
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
level as the starting if line. else:
print("Value is >= 1")

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/cspath-code-challenges/cheatsheet 2/9
9/29/24, 1:08 AM Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy

and Operator

The Python and operator performs a Boolean True and True # Evaluates to True
comparison between two Boolean values, variables, or
True and False # Evaluates to False
expressions. If both sides of the operator evaluate to
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
True when used with the and operator. "Yes" and 100 # Evaluates to True

elif Statement

The Python elif statement allows for continued # elif Statement


checks to be performed after an initial if 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
statement. Multiple elif statements can be used elif pet_type == "cat":
following an initial if to perform a series of checks. print("You have a cat.")
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!")

https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 3/9
9/29/24, 1:08 AM Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy

Equal Operator ==

The equal operator, == , is used to compare two # Equal operator


values, variables or expressions to determine if they are
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')

Not Equals Operator !=

The Python not equals operator, != , is used to # Not Equals Operator


compare two values, variables or expressions to
determine if they are NOT the same. If they are NOT the
same, the operator returns True . If they are the same, if "Yes" != "No":
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 be
equal to the string value "10" and the operator would
return True . If expressions are used, then they are val1 = 10
evaluated to a value of True or False before the val2 = 20
comparison is made by the operator.

if val1 != val2:
print("They are NOT equal")

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


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

https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 4/9
9/29/24, 1:08 AM Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy

Function Parameters

Sometimes functions require input to provide data for def write_a_book(character, setting,
their code. This input is defined using parameters.
special_skill):
Parameters are variables that are defined in the
function definition. 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.
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.

Function Indentation

Python uses indentation to identify blocks of code. # Indentation is used to identify code
Code within the same block should be indented at the
blocks
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 def testfunction(number):
be additional indentation within a function to handle
# This code is part of testfunction
other statements such as for and if so long as the
lines are not indented less than the first line of the print("Inside the testfunction")
function code. 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")

https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 5/9
9/29/24, 1:08 AM Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy

Returning Value from Function

A return keyword is used to return a value from a def check_leap_year(year):


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

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

Parameters as Local Variables

Function parameters behave identically to a function’s def my_function(value):


local variables. They are initialized with the values
print(value)
passed into the function when it was called.
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 defined as
my_function(7)
part of the definition of my_function , and therefore
can only be accessed within my_function .
Attempting to print the contents of value from # Causes an error as `value` no longer
outside the function causes an error. exists
print(value)

Multiple Parameters

Python functions can have multiple parameters. Just as def ready_for_school(backpack,


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

https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 6/9
9/29/24, 1:08 AM Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy

Function Arguments

Parameters in python are variables — placeholders for def sales(grocery_store, item_on_sale,


the actual values the function needs. When the
cost):
function is called, these values are passed in as
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 parameters
grocery_store , item_on_sale , and cost . sales("The Farmer’s Market",
"toothpaste", "$1")

List Method .count()

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

print(numPen)
# Output: 3

Adding Lists Together

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

Determining List Length with len()

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

https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 7/9
9/29/24, 1:08 AM Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy

List Method .append()

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

List Indices

Python list elements are ordered by index, a number berries = ["blueberry", "cranberry",
referring to their placement in the list. List indices start
"raspberry"]
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 List Indices

Negative indices for lists in Python can be used to soups = ['minestrone', 'lentil', 'pho',
reference elements in relation to the end of a list. This
'laksa']
can be used to access single list elements or as part of
defining a list range. For instance: soups[-1] # 'laksa'
To select the last element, my_list[-1] . soups[-3:] # 'lentil', 'pho', '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] .

sorted() Function

The Python sorted() function accepts a list as an unsortedList = [4, 2, 1, 3]


argument, and will return a new, sorted list containing
sortedList = sorted(unsortedList)
the same elements as the original. Numerical lists will
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.

https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 8/9
9/29/24, 1:08 AM Learn Python 3: Python: Code Challenges (Optional) Cheatsheet | Codecademy

Print Share

https://www.codecademy.com/learn/learn-python-3/modules/cspath-code-challenges/cheatsheet 9/9

You might also like