Functions of Python
Functions of Python
Functions of python:
Equals: ==
Not equals: !=
4
These operators compare two items and return True or False if they are
equal or not.
Boolean Variables: You may notice that when you type them in the
code editor (with uppercase T and F), they appear in a different color
than variables or strings. This is because True and False are their own special
type: bool.
Trueand False are the only bool types, and any variable that is assigned one of
these values is called a BOOLEAN VARIABLE.
Boolean variables can be created in several ways. The easiest way is to simply
assign True or False to a variable:
set_to_true = True
set_to_false = False
bool_one = 5 != 7
bool_two = 1 + 1 != 2
bool_three = 3 * 3 == 9
These variables now contain boolean values, so when you reference them they
will only return the True or False values of the expression they were assigned.
print(bool_one) # True
print(bool_two) # False
print(bool_three) # True
and
or
not
Boolean Operators(Or):
he boolean operator or combines two expressions into a larger
expression that is True if either component is True.
Consider the statement
True or (3 + 4 == 7) # True
(1 - 1 == 0) or False # True
(2 < 0) or True # True
(3 == 8) or (3 > 4) # False
Notice that each or statement that has at least one True component
is True, but the final statement has two False components, so it
is False.
Here, we took the True statement oranges are a fruit and added
a not operator to make the False statement oranges are not a
fruit.
This example in English is slightly different from the way it would appear
in Python because in Python we add the not operator to the very
beginning of the statement. Let’s take a look at some of those:
not 1 + 1 == 2 # False
not 7 < 0 # True
7
if weekday:
print("wake up at 6:30")
else:
print("sleep in")
We can use elif statements to control the order we want our program
to check each of our conditional statements. First, the if statement is
checked, then each elif statement is checked from top to bottom, then
finally the else code is executed if none of the previous conditions have
been met.
This can occur if a variable is used before it has been assigned a value or
if a variable name is spelled differently than the point at which it was
defined. The Python interpreter will display the line of code where
the NameError was detected and indicate which name is found that was
not defined.
List: a LIST is one of the many built-in data structures that allows us
to work with a collection of data in sequential order.
Notice that:
3. It’s considered good practice to insert a space ( ) after each comma, but
your code will run just fine if you forget the space.
Instead of storing each student’s height, we can make a list that contains
their names:
We can even combine multiple data types in one list. For example, this
list contains both a string and an integer:
Lists can contain any data type in Python! For example, this list contains
a string, integer, boolean, and float.
print(append_example)
Will output:
Python lists are zero-indexed. This means that the first element in a list
has index 0, rather than 1.
Element Index
"Juan" 0
"Zofia" 1
"Amare" 2
"Ezio" 3
"Ananya" 4
We can select a single element from a list by using square brackets ([])
and the index of the list item. If we wanted to select the third element
from the list, we’d use calls[2]:
print(calls[2])
Will output:
Amare
11
Note: When accessing elements of a list, you must use an int as the
index. If you use a float, you will get an error. This can be especially
tricky when using division. For example print(calls[4/2]) will result
in an error, because 4/2 gets evaluated to the float 2.0.
To solve this problem, you can force the result of your division to be
an int by using the int() function. int() takes a number and cuts off
the decimal point. For example, int(5.9) and int(5.0) will both
become 5. Therefore, calls[int(4/2)] will result in the same value
as calls[2], whereas calls[4/2] will result in an error.
We can use the index -1 to select the last item of a list, even when we
don’t know how many elements are in a list.
print(pancake_recipe[-1])
Would output:
love
print(pancake_recipe[5])
Would output:
love
Element Index
"eggs" -6
"flour" -5
"butter" -4
"milk" -3
"sugar" -2
"love" -1
Thankfully our friend Jiho from Petal Power came to the rescue. Jiho gifted us
some strawberry seeds. We will replace the cauliflower with our new seeds.
print(garden)
Will output:
garden[-1] = "Raspberries"
13
print(garden)
Will output:
["Tomatoes", "Green Beans", "Strawberries", "Raspberries"]
Shrinking Lists[Remove] :
We can remove elements in a list using the .remove() Python method.
shopping_line.remove("Chris")
print(shopping_line)
# Create a list
shopping_line = ["Cole", "Kip", "Chris", "Sylvana", "Chris"]
# Remove a element
shopping_line.remove("Chris")
print(shopping_line)
Will output:
Let’s practice using the. remove() method to remove elements from a list.
14
Previously, we saw that we could create a list representing both Noelle’s name
and height:
We can put several of these lists into one list, such that each entry in the list
represents a student and their height:
We will often find that a two-dimensional list is a very good structure for
representing grids such as games like tic-tac-toe.
The .insert() method will handle shifting over elements and can be used with
negative indices.
Length: Often, we’ll need to find the number of items in a list, usually
called its length.
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
Would output:
start is the index of the first element that we want to include in our
selection. In this case, we want to start at "b", which has index 1.
end is the index of one more than the last index that we want to
include. The last element we want is "f", which has index 5,
so end needs to be 6.
sliced_list = letters[1:6]
print(sliced_list)
Would output:
Notice that the element at index 6 (which is "g") is not included in our
selection.
Suppose we have a list called letters that represents the letters in the
word “Mississippi”:
letters = ["m", "i", "s", "s", "i", "s", "s", "i", "p",
"p", "i"]
If we want to know how many times i appears in this word, we can use
the list method called .count():
num_i = letters.count("i")
print(num_i)
Would output:
18
Would output:
names.sort()
print(names)
Would output:
names.sort(reverse=True)
print(names)
Would output:
Note: The .sort() method does not return any value and thus does not
need to be assigned to a variable since it modifies the list directly. If we
do assign the result of the method, it would assign the value of None to
the variable.
The sorted() function is different from the .sort() method in two ways:
sorted_names = sorted(names)
print(sorted_names)
print(names)
Would output:
For Loops : In a for loop, we will know in advance how many times
the loop will need to iterate because we will be working on a collection
with a predefined length. In our examples, we will be using Python lists
as our collection of elements.
Before we work with any collection, let’s examine the general structure of
a for loop:
Let’s link these concepts back to our ingredients example. This for loop
prints each ingredient in ingredients:
21
In this example:
milk
sugar
vanilla extract
dough
chocolate
Temporary Variables:
for i in ingredients:
print(i)
Indentation:
22
Elegant loops:
Note: One-line for loops are useful for simple programs. It is not
recommended you write one-line loops for any loop that has to perform
multiple complex actions on each iteration. Doing so will hurt the
readability of your code and may ultimately lead to buggier code.
six_steps = range(6)
We can then use the range directly in our for loops as the collection to
perform a six-step iteration:
Would output:
Learning Loops!
Learning Loops!
Learning Loops!
Learning Loops!
Learning Loops!
Learning Loops!
Something to note is we are not using temp anywhere inside of the loop
body. If we are curious about which loop iteration (step) we are on, we
can use temp to track it. Since our range starts at 0, we will add + 1 to
our temp to represent how many iterations (steps) our loop takes more
accurately.
Would output:
count = 0
while count <= 3:
# Loop Body
print(count)
count += 1
1. When the first iteration of the loop has finished, Python returns to
the top of the loop and checks the conditional again. After the first
iteration, count would be equal to 1 so the conditional still
evaluates to True and so the loop continues.
25
0
1
2
3
Note the following about while loops before we write our own:
Indentation:
Notice that in our example the code under the loop declaration is
indented. Similar to a for loop, everything at the same level of
indentation after the while loop declaration is run on every
iteration of the loop while the condition is true.
while count <= 3:
# Loop Body
print(count)
count += 1
# Any other code at this level of indentation will
# run on each iteration
Elegant loops:
count = 0
while count <= 3: print(count); count += 1
We know that while loops require some form of a variable to track the
condition of the loop to start and stop.
Take some time to think about what we would use to track whether we
need to start/stop the loop if we want to iterate through ingredients and
print every element.
length = len(ingredients)
index = 0
index += 1
Explanation
This comes in the form of our length variable which stores the value of
the length of the list.
Explanation
Explanation
In our while loop conditional, we will compare the index variable to the
length of our list stored inside of the length variable.
28
Explanation
Inside of our loop body, we can use the index variable to access
our ingredients list and print the value at the current iteration.
Since our index starts at zero, our first iteration will print the value of the
element at the zeroth index of our ingredients list, then the next iteration
will print the value of the element at the first index, and so on.
Explanation
On each iteration of our while loop, we need to also increment the value
of index to make sure our loop can stop once the index value is no
longer smaller than the length value.
This increment also helps us access the next value of the ingredients list
on the next iteration.
29
milk
sugar
vanilla extract
dough
chocolate
.
Every time we enter the loop, we add a 1 to the end of the list that we are iterating through.
As a result, we never make it to the end of the list. It keeps growing forever!
A loop that never terminates is called an infinite loop. These are very
dangerous for our code because they will make our program run forever and
thus consume all of your computer’s resources.
A program that hits an infinite loop often becomes completely unusable. The
best course of action is to avoid writing an infinite loop.
It’s often the case that we want to search a list to check if a specific value
exists. What does our loop look like if we want to search for the value
of "knit dress" and print out "Found it" if it did exist?
This code goes through each item in items_on_sale and checks for a
match. This is all fine and dandy but what’s the downside?
Since it’s only 5 elements long, iterating through the entire list is not a
big deal in this case but what if items_on_sale had 1000 items? What if
it had 100,000 items? This would be a huge waste of time for our
program!
print("End of search!")
When the loop entered the if statement and saw the break it
immediately ended the loop. We didn’t need to check the elements
of "red headband" or "dinosaur onesie" at all.
What if we want to print out all of the numbers in a list, but only if they
are positive integers. We can use another common loop control
statement called continue.
for i in big_number_list:
if i <= 0:
continue
32
print(i)
1
2
4
5
2
Using a for or while loop can be useful here to get each team:
Would output:
33
Ava
Samantha
James
Lucille
Zed
Edgar
Gabriel
To start, let’s say we had a list of integers and wanted to create a list
where each element is doubled. We could accomplish this using
a for loop and a new list called doubled:
34
print(doubled)
Would output:
Let’s see how we can use the power of list comprehensions to solve
these types of problems in one line. Here is our same problem but now
written as a list comprehension:
print(only_negative_doubled)
Would output:
[-2, -90]
Now, here is what our code would look like using a list comprehension:
[-2, -90]
Would output:
NOTE: This is a bit different than our previous comprehension since the
conditional if num < 0 else num * 3 comes after the expression num *
2 but before our for keyword. The placement of the conditional
expression within the comprehension is dependent on whether or not
an else clause is used. When an if statement is used without else, the
conditional must go after for <element> in <collection>. If the
conditional expression includes an else clause, the conditional must go
before for. Attempting to write the expressions in any other order will
result in a SyntaxError.
A FUNCTION consists of many parts, so let’s first get familiar with its
core - a function definition.
def function_name():
# functions tasks go here
Here is an example of a function that greets a user for our trip planning
application:
def trip_welcome():
print("Welcome to Tripcademy!")
print("Let's get you to your destination.")
Note: Pasting this code into the editor and clicking Run will result in an
empty output terminal. The print() statements within the function will
not execute since our function hasn’t been used. We will explore this
further in the next exercise; for now, let’s practice defining a function.
def directions_to_timesSq():
print("Walk 4 mins to 34th St Herald Square train
station.")
print("Take the Northbound N, Q, R, or W train 1 stop.")
print("Get off the Times Square 42nd Street stop.")
To call our function, we must type out the function’s name followed by a
pair of parentheses and no indentation:
directions_to_timesSq()
Calling the function will execute the print statements within the body
(from the top statement to the bottom statement) and result in the
following output:
Note that you can only call a function after it has been defined in your
code.
def my_function(single_parameter)
# some code
def trip_welcome(destination):
print("Welcome to Tripcademy!")
print("Looks like you're going to " + destination + "
today.")
trip_welcome("Times Square")
Welcome to Tripcademy!
Looks like you're going to Times Square today.
The argument is the data that is passed in when we call the function,
which is then assigned to the parameter name.
40
We can write a function that takes in more than one parameter by using
commas:
When we call our function, we will need to provide arguments for each
of the parameters we assigned in our function definition.
# Calling my_function
my_function(argument1, argument2)
Welcome to Tripcademy
Looks like you are traveling from Prospect Park
And you are heading to Atlantic Terminal
Types of Arguments : In Python, there are 3 different types
of arguments we can give a function.
# 100 is miles_to_travel
# 10 is rate
42
# 5 is discount
calculate_taxi_price(100, 10, 5)
calculate_taxi_price(rate=0.5, discount=10,
miles_to_travel=100)
have been writing so far in our exercises are called USER DEFINED
FUNCTIONS - functions that are written by users (like us!).
There are lots of different built-in functions that we can use in our
programs. Take a look at this example of using len() to get the length
of a string:
destination_name = "Venkatanarasimharajuvaripeta"
28
There are even more obscure ones like help() where Python will print a
link to documentation for us and provide some details:
help("string")
NAME
string - A collection of string constants.
MODULE REFERENCE
https://docs.python.org/3.8/library/string
44
Check out all the latest built-in functions in the official Python docs.