0% found this document useful (0 votes)
16 views44 pages

Functions of Python

Uploaded by

ashfaqahad08
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
16 views44 pages

Functions of Python

Uploaded by

ashfaqahad08
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 44

1

Functions of python:

 Print: In Python, the print () function is used to tell a


computer to talk. The message to be printed should be surrounded
by quotes. (“,’) .

 Variable: In python, Variables can contain varies information.

1. Multiplying any variable with a number does not


change the value of the variable.

 Integer: An INTEGER, or int, is a whole number. It has no


decimal point and contains all counting numbers (1, 2, 3, …) as well
as their negative counterparts and the number 0. If you were
counting the number of people in a room, the number of
jellybeans in a jar, or the number of keys on a keyboard you would
likely use an integer.

 Float: A FLOATING-POINT NUMBER, or a float, is a decimal


number. It can be used to represent fractional quantities as well as
precise measurements. If you were measuring the length of your
bedroom wall, calculating the average test score of a seventh-
grade class, or storing a baseball player’s batting average for the
1998 season you would likely use a float.

 Exponents: Python can also perform exponentiation. In


written math, you might see an exponent as a superscript number,
but typing superscript numbers isn’t always easy on modern
2

keyboards. Since this operation is so related to multiplication, we


use the notation **.

 Modulo: Python offers a companion to the division operator


called the modulo operator. The modulo operator is indicated
by % and gives the remainder of a division calculation. If the two
numbers are divisible, then the result of the modulo operation will
be 0.

# Prints 4 because 29 / 5 is 5 with a remainder of 4

1.Concatenation: The + operator doesn’t just add two


numbers, it can also “add” two strings! The process of combining
two strings is called STRING CONCATENATION . Performing string
concatenation creates a brand new string comprised of the first
string’s contents followed by the second string’s contents (without
any added space in-between).

1. In order to create some space between the two strings in


the final result we need to add (“”) between them.
2. If we want to concantenation a number with two strings in
the final result we need to make the number a string first
Using the str() function. Using str() we can convert variables
that are not strings to strings and then concatenate them.
But we don’t need to convert a number to a string for it to be
an argument to a print statement.

 Plus Equals: Python offers a shorthand for


updating variables. When you have a number saved in a variable
and want to add to the current value of the variable, you can use
the += (plus-equals) operator.
3

1. Plus equals can also be used for string


concatenation.

NOTE: don’t quotations.

 Multi line strings: Python strings are very flexible, but if we


try to create a string that occupies multiple lines we find
ourselves face-to-face with a SyntaxError. Python offers a
solution: MULTI-LINE strings. By using three quote-marks
(""" or ''') instead of one, we tell the program that the string
doesn’t end until the next triple-quote. This method is useful if
the string being defined contains a lot of quotation marks and
we want to be sure we don’t close it premature.

 Boolean Expressions: In order to build control flow


into our program, we want to be able to check if something is
true or not. A boolean expression is a statement that can either
be True or False.

 Relational Operators: Equal or Not Equal:


Relational operators compare two items and return
either True or False. For this reason, you will sometimes hear them
called COMPARATORS.

The two relational operators we’ll cover first are:

 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

You can also set a variable equal to a boolean expression.

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

Rational Operators ||: So far we know two relational operators,


equals and not equals, but there are a ton (well, four) more:

 > greater than


5

 Boolean Operators (And): the conditions you want to


check in your conditional statement will require more than one
boolean expression to cover. In these cases, you can build larger
boolean expressions using BOOLEAN OPERATORS.
These operators (also known as LOGICAL OPERATORS) combine
smaller boolean expressions into larger boolean expressions.

There are three boolean operators that we will cover:

 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

Oranges are a fruit or apples are a vegetable.

This statement is composed of two expressions: oranges are a


fruit which is True and apples are a vegetable which
is False. Because the two expressions are connected by
the or operator, the entire statement is True. Only one component
needs to be True for an or statement to be True.
6

In English, or implies that if one component is True, then the other


component must be False. This is not true in Python. If
an or statement has two True components, it is also True.

Let’s take a look at a couple of examples in Python:

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.

Boolean Operators(Not) : The final boolean operator we will


cover is not. This operator is straightforward: when applied to any
boolean expression it reverses the boolean value. So if we have
a True statement and apply a not operator we get a False statement.

not True == False


not False == True

Consider the following statement:

Oranges are not a fruit.

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

 Else Statements: else statements allow us to elegantly


describe what we want our code to do when certain conditions
are not met.

else statements always appear in conjunction with if statements.


Consider our waking-up example to see how this works:

if weekday:
print("wake up at 6:30")
else:
print("sleep in")

In this way, we can build if statements that execute different code if


conditions are or are not met. This prevents us from needing to
write if statements for each possible condition, we can instead write a
blanket else statement for all the times the condition is not met.

Else If Statements: . An elif statement checks another


condition after the previous if statements conditions aren’t met.

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.

Let’s take a look at this in practice. The following if statement will


display a “thank you” message after someone donates to a charity; there
will be a curated message based on how much was donated.

print("Thank you for the donation!")

if donation >= 1000:


8

print("You've achieved platinum status")


elif donation >= 500:
print("You've achieved gold donor status")
elif donation >= 100:
print("You've achieved silver donor status")
else:
print("You've achieved bronze donor status")

 Syntax Error: SyntaxError means there is something wrong


with the way your program is written — punctuation that does not
belong, a command where it is not expected, or a missing parenthesis
can all trigger a SyntaxError.

Name Error: A NameError is reported by the Python interpreter


when it detects a variable that is unknown.

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.

Type Error: A TypeError is reported by the Python interpreter


when an operation is applied to a variable of an inappropriate type.

This can occur in Python when one attempts to use an operator on


something of the incorrect type.

 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:

1. A list begins and ends with square brackets ( [ and ]).

2. Each item (i.e., 67 or 70) is separated by a comma (,)


9

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.

What can List contain:

Instead of storing each student’s height, we can make a list that contains
their names:

names = ["Noelle", "Ava", "Sam", "Mia"]

We can even combine multiple data types in one list. For example, this
list contains both a string and an integer:

mixed_list_string_number = ["Noelle", 61]

Lists can contain any data type in Python! For example, this list contains
a string, integer, boolean, and float.

mixed_list_common = ["Mia", 27, False, 0.5]

List Methods: methods will follow the form


of list_name.method(). Some methods will require an input value that
will go between the parenthesis of the method ( ).

An example of a popular list method is .append(), which allows us to


add an element to the end of a list.

append_example = [ 'This', 'is', 'an', 'example']


append_example.append('list')

print(append_example)

Will output:

['This', 'is', 'an', 'example', 'list']


10

Growing a list Plus + : we want to add multiple items to a list,


we can use + to combine two lists (this is also known as concatenation).

Accessing List Elements: In Python, we call the location of an


element in a list its index.

Python lists are zero-indexed. This means that the first element in a list
has index 0, rather than 1.

Here are the index numbers for the list calls:

Element Index
"Juan" 0
"Zofia" 1
"Amare" 2
"Ezio" 3
"Ananya" 4

In this example, the element with index 2 is "Amare".

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.

 Accessing List Elements [Negative Index]:

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.

Consider the following list with 6 elements:

pancake_recipe = ["eggs", "flour", "butter", "milk",


"sugar", "love"]

If we select the -1 index, we get the final element, "love".

print(pancake_recipe[-1])

Would output:

love

This is equivalent to selecting the element with index 5:

print(pancake_recipe[5])

Would output:

love

Here are the negative index numbers for our list:


12

Element Index
"eggs" -6
"flour" -5
"butter" -4
"milk" -3
"sugar" -2
"love" -1

 Modifying List Elements:


garden = ["Tomatoes", "Green Beans", "Cauliflower", "Grapes"]

Unfortunately, we forgot to water our cauliflower and we don’t think it is


going to recover.

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.

We will need to modify the list to accommodate the change to


our garden list. To change a value in a list, reassign the value using the
specific index.
garden[2] = "Strawberries"

print(garden)

Will output:

["Tomatoes", "Green Beans", "Strawberries", "Grapes"]

Negative indices will work as well.

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.

Suppose we have a filled list called shopping_line that represents a line at a


grocery store:

shopping_line = ["Cole", "Kip", "Chris", "Sylvana"]

We could remove "Chris" by using the .remove() method:

shopping_line.remove("Chris")

print(shopping_line)

If we examine shopping_line, we can see that it now doesn’t contain "Chris":

["Cole", "Kip", "Sylvana"]

We can also use .remove() on a list that has duplicate elements.

Only the first instance of the matching element is removed:

# Create a list
shopping_line = ["Cole", "Kip", "Chris", "Sylvana", "Chris"]

# Remove a element
shopping_line.remove("Chris")
print(shopping_line)

Will output:

["Cole", "Kip", "Sylvana", "Chris"]

Let’s practice using the. remove() method to remove elements from a list.
14

 Two – Dimensional 2D Lists:


We’ve seen that the items in a list can be numbers or strings. Lists can contain
other lists! We will commonly refer to these as TWO-DIMENSIONAL (2D) lists.

Once more, let’s look at a class height example:

 Noelle is 61 inches tall

 Ava is 70 inches tall

 Sam is 67 inches tall

 Mia is 64 inches tall

Previously, we saw that we could create a list representing both Noelle’s name
and height:

noelle = ["Noelle", 61]

We can put several of these lists into one list, such that each entry in the list
represents a student and their height:

heights = [["Noelle", 61], ["Ava", 70], ["Sam", 67], ["Mia",


64]]

We will often find that a two-dimensional list is a very good structure for
representing grids such as games like tic-tac-toe.

#A 2d list with three lists in each of the indices.


tic_tac_toe = [
["X","O","X"],
["O","X","O"],
["O","O","X"]
]

 Accessing 2D Lists: Two-dimensional lists can be accessed


similar to their one-dimensional counterpart. Instead of providing a
15

single pair of brackets [ ] we will use an additional set for each


dimension past the first.
#Access the sublist at index 0, and then access the 1st index of that
sublist.

Adding by Index (Insert) : The Python list


method .insert() allows us to add an element to a specific index in a list.

The .insert() method takes in two inputs:

1. The index you want to insert into.

2. The element you want to insert at the specified index.

The .insert() method will handle shifting over elements and can be used with
negative indices.

Some important things to note:

1. The order and number of the inputs is important.


The .insert() method expects two inputs, the first being a
numerical index, followed by any value as the second input.
2. When we insert an element into a list, all elements from the
specified index and up to the last index are shifted one index to
the right. This does not apply to inserting an element to the very
end of a list as it will simply add an additional index and no other
elements will need to shift.

 Removing Index (Pop): Python gives us a method to


remove elements at a specific index using a method called .pop().

The .pop() method takes an optional single input:


16

1. The index for the element you want to remove.

 Consecutive Lists (Range): Python gives us an easy way of


creating these types of lists using a built-in function called range().

The function range() takes a single input, and generates numbers


starting at 0 and ending at the number before the input.
The range() function is unique in that it creates a RANGE OBJECT. It is
not a typical list like the ones we have been working with.

Length: Often, we’ll need to find the number of items in a list, usually
called its length.

We can do this using a built-in function called len().

When we apply len() to a list, we get the number of elements in that


list:

my_list = [1, 2, 3, 4, 5]

print(len(my_list))

Would output:

Let’s find the length of various lists!

Slicing Lists 1: In Python, often we want to extract only a portion


of a list. Dividing a list in such a manner is referred to as slicing.

Lets assume we have a list of letters:


17

letters = ["a", "b", "c", "d", "e", "f", "g"]

Suppose we want to select from "b" through "f".

We can do this using the following syntax: letters[start:end], where:

 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:

["b", "c", "d", "e", "f"]

Notice that the element at index 6 (which is "g") is not included in our
selection.

Counting in a List: n Python, it is common to want to count


occurrences of an item in a list.

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

Notice that since .count() returns a value, we can assign it to a variable


to use it.

We can even use .count() to count element appearances in a two-


dimensional list.

Let’s use the list number_collection as an example:

number_collection = [[100, 200], [100, 200], [475, 29],


[34, 34]]

If we wanted to know how often the sublist [100, 200] appears:

num_pairs = number_collection.count([100, 200])


print(num_pairs)

Would output:

Let’s count some list items using the .count() method!

Sorting Lists 1: Often, we will want to sort a list in either numerical


(1, 2, 3, …) or alphabetical (a, b, c, …) order.

We can sort a list using the method .sort().

Suppose that we have a list of names:

names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]

Let’s see what happens when we apply .sort():

names.sort()
print(names)

Would output:

['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']


19

As we can see, the .sort() method sorted our list of names in


alphabetical order.

.sort() also provides us the option to go in reverse. Instead of sorting


in ascending order like we just saw, we can do so in descending order.

names.sort(reverse=True)
print(names)

Would output:

['Xander', 'Willow', 'Giles', 'Buffy', 'Angel']

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.

Sorting Lists 2: A second way of sorting a list in Python is to use


the built-in function sorted().

The sorted() function is different from the .sort() method in two ways:

1. It comes BEFORE a list, instead of after as all built-in functions do.


2. It generates a new list rather than modifying the one that already
exists.

Let’s return to our list of names:

names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]

Using sorted(), we can create a new list, called sorted_names:

sorted_names = sorted(names)
print(sorted_names)

This yields the list sorted alphabetically:


20

['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']

Note that using sorted did not change names:

print(names)

Would output:

['Xander', 'Buffy', 'Angel', 'Willow', 'Giles']

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.

With for loops, on each iteration, we will be able to perform an action on


each element of the collection.

Before we work with any collection, let’s examine the general structure of
a for loop:

for <temporary variable> in <collection>:


<action>

Let’s break down each of these components:

1. A for keyword indicates the start of a for loop.


2. A <temporary variable> that is used to represent the value of the
element in the collection the loop is currently on.
3. An in keyword separates the temporary variable from the collection
used for iteration.
4. A <collection> to loop over. In our examples, we will be using a
list.
5. An <action> to do anything on each iteration of the loop.

Let’s link these concepts back to our ingredients example. This for loop
prints each ingredient in ingredients:
21

ingredients = ["milk", "sugar", "vanilla extract", "dough", "chocolate"]

for ingredient in ingredients:


print(ingredient)

In this example:

1. ingredient is the <temporary variable>.


2. ingredients is our <collection>.
3. print(ingredient) was the <action> performed on every iteration
using the temporary variable of ingredient.

This code outputs:

milk
sugar
vanilla extract
dough
chocolate

Some things to note about for loops:

 Temporary Variables:

A temporary variable’s name is arbitrary and does not need to be


defined beforehand. Both of the following code snippets do the exact
same thing as our above example:

for i in ingredients:
print(i)

for item in ingredients:


print(item)

Programming best practices suggest we make our temporary variables


as descriptive as possible. Since each iteration (step) of our loop is
accessing an ingredient it makes more sense to call our temporary
variable ingredient rather than i or item.

 Indentation:
22

Notice that in all of these examples the print statement is indented.


Everything at the same level of indentation after the for loop
declaration is included in the loop body and is run on every
iteration of the loop.

for ingredient in ingredients:


# Any code at this level of indentation
# will run on each iteration of the loop
print(ingredient)

If we ever forget to indent, we’ll get an IndentationError or unexpected


behavior.

 Elegant loops:

Python loves to help us write elegant code so it allows us to write


simple for loops in one-line. In order to see the below example as one
line, you may need to expand your narrative window. Here is the
previous example in a single line:

for ingredient in ingredients: print(ingredient)

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.

For Loops(Using range): , if we wanted to print out


a "Learning Loops!" message six times using a for loop, we would follow
this structure:

for <temporary variable> in <list of length 6>:


print("Learning Loops!")
Notice that we need to iterate through a list with a length of six, but we
don’t necessarily care what is inside of the list.
23

To create arbitrary collections of any length, we can pair


our for loops with the trusty Python built-in function range().

An example of how the range() function works, this code generates a


collection of 6 integer elements from 0 to 5:

six_steps = range(6)

# six_steps is now a collection with 6 elements:


# 0, 1, 2, 3, 4, 5

We can then use the range directly in our for loops as the collection to
perform a six-step iteration:

for temp in range(6):


print("Learning Loops!")

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.

for temp in range(6):


print("Loop is on iteration number " + str(temp + 1))

Would output:

Loop is on iteration number 1


Loop is on iteration number 2
Loop is on iteration number 3
24

Loop is on iteration number 4


Loop is on iteration number 5
Loop is on iteration number 6

While Loops(Introduction) : In Python, for loops are not the


only type of loops we can use. Another type of loop is called
a while loop and is a form of indefinite iteration.

A while loop performs a set of instructions as long as a given condition


is true.

The structure follows this pattern:

while <conditional statement>:


<action>

Let’s examine this example, where we print the integers 0 through 3:

count = 0
while count <= 3:
# Loop Body
print(count)
count += 1

Let’s break the loop down:

1. count is initially defined with the value of 0. The conditional


statement in the while loop is count <= 3, which is true at the
initial iteration of the loop, so the loop body executes.

Inside the loop body, count is printed and then incremented by 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

2. This continues until the count variable becomes 4. At that point,


when the conditional is tested it will no longer be True and the
loop will stop.
The output would be:

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

If we ever forget to indent, we’ll get an IndentationError or


unexpected behavior.

 Elegant loops:

Similar to for loops, Python allows us to write elegant one-


line while loops. Here is our previous example in a single line:

count = 0
while count <= 3: print(count); count += 1

Note: Here we separate each statement with a ; to denote a separate


line of code.
26

While Loops(lists) : A while loop isn’t only good for counting!


Similar to how we saw for loops working with lists, we can
use while loops to iterate through a list as well.

Let’s return to our ingredient list:

ingredients = ["milk", "sugar", "vanilla extract", "dough", "chocolate"]

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.

Click here to find out!

We know that a list has a predetermined length. If we use the length of


the list as the basis for how long our while loop needs to run, we can
iterate the exact length of the list.

We can use the built-in Python len() function to accomplish this:

# Length would be equal to 5


length = len(ingredients)

We can then use this length in addition to another variable to construct


the while loop:

length = len(ingredients)
index = 0

while index < length:


print(ingredients[index])
27

index += 1

Let’s break this down:

# Length will be 5 in this case


length = len(ingredients)

Explanation

As mentioned, we need a way to know how many times we need our


loop to iterate based on the size of the collection.

This comes in the form of our length variable which stores the value of
the length of the list.

# Index starts at zero


index = 0

Explanation

We still need an additional variable that will be used to compare against


our length.

while index < length:

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

On the first iteration, we will be comparing the equivalent of 0 < 5 which


will evaluate to True, and start the execution of our loop body.

# The first iteration will print ingredients[0]


print(ingredients[index])

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.

# Increment index to access the next element in ingredients


# Each iteration gets closer to making the conditional no longer true
index += 1

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

Our final output would be:

milk
sugar
vanilla extract
dough
chocolate
.

Infinite loops: We’ve iterated through lists that have a discrete


beginning and end. However, let’s consider this example:

my_favorite_numbers = [4, 8, 15, 16, 42]

for number in my_favorite_numbers:


my_favorite_numbers.append(1)

Take some time to ponder what happens with this code.

Click to see what would happen!

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.

Note: If you accidentally stumble into an infinite loop while developing on


your own machine, you can end the loop by using control + c to terminate the
program. If you’re writing code in our online editor, you’ll need to refresh the
page to get out of an infinite loop.

Let’s fix an infinite loop to see it in action.


30

Loops Controal (Break) : Loops in Python are very versatile.


Python provides a set of control statements that we can use to get even
more control out of our loops.

Let’s take a look at a common scenario that we may encounter to see a


use case for LOOP CONTROL STATEMENTS.

Take the following list items_on_sale as our example:

items_on_sale = ["blue shirt", "striped socks", "knit


dress", "red headband", "dinosaur onesie"]

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?

It would look something like this:

for item in items_on_sale:


if item == "knit dress":
print("Found it")

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?

Once "knit_dress" is found in the list items_on_sale, we don’t need


to go through the rest of the items_on_sale list. Unfortunately, our
loop will keep running until we reach the end of the list.

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!

Thankfully you can stop iteration from inside the loop by


using break loop control statement.

When the program hits a break statement it immediately terminates a


loop. For example:
31

items_on_sale = ["blue shirt", "striped socks", "knit


dress", "red headband", "dinosaur onesie"]

print("Checking the sale list!")

for item in items_on_sale:


print(item)
if item == "knit dress":
break

print("End of search!")

This would produce the output:

Checking the sale list!


blue shirt
striped socks
knit dress
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.

Loop Control (Continue): While the break control statement


will come in handy, there are other situations where we don’t want to
end the loop entirely. What if we only want to skip the current iteration
of the loop?

Let’s take this list of integers as our example:

big_number_list = [1, 2, -1, 4, -5, 5, 2, -9]

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)

This would produce the output:

1
2
4
5
2

Notice a few things:

1. Similar to when we were using the break control statement,


our continue control statement is usually paired with some form
of a conditional (if/elif/else).
2. When our loop first encountered an element (-1) that met the
conditions of the if statement, it checked the code inside the
block and saw the continue. When the loop then encounters
a continue statement it immediately skips the current iteration
and moves onto the next element in the list (4).
3. The output of the list only printed positive integers in the list
because every time our loop entered the if statement and saw
the continue statement it simply moved to the next iteration of
the list and thus never reached the print statement.

Nested Loops : Loops can be nested in Python, as they can with


other programming languages. We will find certain situations that
require nested loops.

Suppose we are in charge of a science class, that is split into three


project teams:

project_teams = [["Ava", "Samantha", "James"], ["Lucille",


"Zed"], ["Edgar", "Gabriel"]]

Using a for or while loop can be useful here to get each team:

for team in project_teams:


print(team)

Would output:
33

["Ava", "Samantha", "James"]


["Lucille", "Zed"]
["Edgar", "Gabriel"]

But what if we wanted to print each individual student? In this case, we


would actually need to NEST our loops to be able to loop through each
sub-list. Here is what it would look like:

# Loop through each sublist


for team in project_teams:
# Loop elements in each sublist
for student in team:
print(student)

This would output:

Ava
Samantha
James
Lucille
Zed
Edgar
Gabriel

List Comprehensions (Introduction) : So far we have seen


many of the ideas about using loops in our code. Python prides itself on
allowing programmers to write clean and elegant code. We have already
seen this with Python giving us the ability to write while and for loops
in a single line.

In this exercise, we are going to examine another way we can write


elegant loops in our programs using list comprehensions.

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

numbers = [2, -1, 79, 33, -45]


doubled = []

for number in numbers:


doubled.append(number * 2)

print(doubled)

Would output:

[4, -2, 158, 66, -90]

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:

numbers = [2, -1, 79, 33, -45]


doubled = [num * 2 for num in numbers]
print(doubled)

Let’s break down our example in a more general way:

new_list = [<expression> for <element> in <collection>]

In our doubled example, our list comprehension:

1. Takes an element in the list numbers


2. Assigns that element to a variable called num (our <element>)
3. Applies the <expression> on the element stored in num and adds
the result to a new list called doubled
4. Repeats steps 1-3 for every other element in the numbers list
(our <collection>)

Our result would be the same:

[4, -2, 158, 66, -90]

List Comprehensions (Conditionals) : List


Comprehensions are very flexible. We even can expand our examples to
incorporate conditional logic.
35

Suppose we wanted to double only our negative numbers from our


previous numbers list.

We will start by using a for loop and a list only_negative_doubled:

numbers = [2, -1, 79, 33, -45]


only_negative_doubled = []

for num in numbers:


if num < 0:
only_negative_doubled.append(num * 2)

print(only_negative_doubled)

Would output:

[-2, -90]

Now, here is what our code would look like using a list comprehension:

numbers = [2, -1, 79, 33, -45]


negative_doubled = [num * 2 for num in numbers if num < 0]
print(negative_doubled)

Would output the same result:

[-2, -90]

In our negative_doubled example, our list comprehension:

1. Takes an element in the list numbers.


2. Assigns that element to a variable called num.
3. Checks if the condition num < 0 is met by the element stored
in num. If so, it goes to step 4, otherwise it skips it and goes to the
next element in the list.
4. Applies the expression num * 2 on the element stored in num and
adds the result to a new list called negative_doubled
5. Repeats steps 1-3 (and sometimes 4) for each remaining element
in the numbers list.
36

We can also use If-Else conditions directly in our comprehensions. For


example, let’s say we wanted to double every negative number but triple
all positive numbers. Here is what our code might look like:

numbers = [2, -1, 79, 33, -45]


doubled = [num * 2 if num < 0 else num * 3 for num in numbers ]
print(doubled)

Would output:

[6, -2, 237, 99, -90]

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.

Here are a few list comprehensions in a single block. Take a moment to


compare how the syntax must change depending on whether or not
an else clause is included:

numbers = [2, -1, 79, 33, -45]

no_if = [num * 2 for num in numbers]


if_only = [num * 2 for num in numbers if num < 0]
if_else = [num * 2 if num < 0 else num * 3 for num in numbers]

 Functions: Functions are a convenient way to group our code


into reusable blocks. A function contains a sequence of steps that can
be performed repeatedly throughout a program without having to
repeat the process of writing the same code again.
37

A FUNCTION consists of many parts, so let’s first get familiar with its
core - a function definition.

Here’s an example of a function definition:

def function_name():
# functions tasks go here

There are some key components we want to note here:

 The def keyword indicates the beginning of a function (also known


as a function header). The function header is followed by a name in
snake_case format that describes the task the function performs.
It’s best practice to give your functions a descriptive yet concise
name.
 Following the function name is a pair of parenthesis ( ) that can
hold input values known as parameters (more on parameters later
in the lesson!). In this example function, we have no parameters.
 A colon : to mark the end of the function header.
 Lastly, we have one or more valid python statements that make up
the function body (where we have our python comment).
Notice we’ve indented our # function tasks go here comment.
Like loops and conditionals, code inside a function must be indented to
show that they are part of the function.

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.

Calling a function: The process of executing the code inside the


body of a function is known as calling it (This is also known as “executing
38

a function”). To call a function in Python, type out its name followed by


parentheses ( ).

Let’s revisit our directions_to_timesSq() 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:

Walk 4 mins to 34th St Herald Square train station.


Take the Northbound N, Q, R, or W train 1 stop.
Get off the Times Square 42nd Street stop.

Note that you can only call a function after it has been defined in your
code.

Parameters And Arguments: Our function does a really


good job of welcoming anyone who is traveling to Times Square but a
really poor job if they are going anywhere else. In order for us to make
our function a bit more dynamic, we are going to use the concept of
function parameters.

Function parameters allow our function to accept data as an input value.


We list the parameters a function takes as input between the
parentheses of a function ( ).

Here is a function that defines a single parameter:


39

def my_function(single_parameter)
# some code

In the context of our trip_welcome() function, it would look like this:

def trip_welcome(destination):
print("Welcome to Tripcademy!")
print("Looks like you're going to " + destination + "
today.")

In the above example, we define a single parameter


called destination and apply it in our function body in the
second print statement. We are telling our function it should expect
some data passed in for destination that it can apply to any statements
in the function body.

But how do we actually use this parameter? Our parameter


of destination is used by passing in an argument to the function when
we call it.

trip_welcome("Times Square")

This would output:

Welcome to Tripcademy!
Looks like you're going to Times Square today.

To summarize, here is a quick breakdown of the distinction between a


parameter and an argument:

 The parameter is the name defined in the parenthesis of the function


and can be used in the function body.

 The argument is the data that is passed in when we call the function,
which is then assigned to the parameter name.
40

Multiple Parameters: Using a single parameter is useful


but functions let us use as many parameters as we want! That way, we
can pass in more than one input to our functions.

We can write a function that takes in more than one parameter by using
commas:

def my_function(parameter1, parameter2, parameter3):


# Some code

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)

For example take our trip application’s trip_welcome() function that


has two parameters:

def trip_welcome(origin, destination):


print("Welcome to Tripcademy")
print("Looks like you are traveling from " + origin)
print("And you are heading to " + destination)

Our two parameters in this function are origin and destination. In


order to properly call our function, we need to pass argument values for
both of them.
41

The ordering of your parameters is important as their position will map


to the position of the arguments and will determine their assigned value
in the function body (more on this in the next exercise!).

Our function call could look like:

trip_welcome("Prospect Park", "Atlantic Terminal")

In this call, the argument value of "Prospect Park" is assigned to be


the origin parameter, and the argument value of"Atlantic
Terminal" is assigned to the destination parameter.

The output would be:

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.

Positional arguments: arguments that can be called by their


position in the function definition.
 Keyword arguments: arguments that can be called by their name.
 Default arguments: arguments that are given default values.
Positional Arguments are arguments we have already been using! Their
assignments depend on their positions in the function call. Let’s look at a
function called calculate_taxi_price() that allows our users to see

how much a taxi would cost to their destination 🚕.

def calculate_taxi_price(miles_to_travel, rate, discount):


print(miles_to_travel * rate - discount )

In this function, miles_to_travel is positioned as the first


parameter, rate is positioned as the second parameter, and discount is
the third. When we call our function, the position of the arguments will
be mapped to the positions defined in the function declaration.

# 100 is miles_to_travel
# 10 is rate
42

# 5 is discount
calculate_taxi_price(100, 10, 5)

Alternatively, we can use Keyword Arguments where we explicitly refer to


what each argument is assigned to in the function call. Notice in the
code example below that the arguments do not follow the same order as
defined in the function declaration.

calculate_taxi_price(rate=0.5, discount=10,
miles_to_travel=100)

Lastly, sometimes we want to give our function parameters default


values. We can provide a default value to a parameter by using the
assignment operator (=). This will happen in the function declaration
rather than the function call.

Here is an example where the discount argument in


our calculate_taxi_price function will always have a default value of
10:

def calculate_taxi_price(miles_to_travel, rate, discount


= 10):
print(miles_to_travel * rate - discount )

When using a default argument, we can either choose to call the


function without providing a value for a discount (and thus our function
will use the default value assigned) or overwrite the default argument by
providing our own:

# Using the default value of 10 for discount.


calculate_taxi_price(10, 0.5)

# Overwriting the default value of 10 with 20


calculate_taxi_price(10, 0.5, 20)

Built in Functions VS User Defined Functions : There


are two distinct categories for functions in the world of Python. What we
43

have been writing so far in our exercises are called USER DEFINED
FUNCTIONS - functions that are written by users (like us!).

There is another category called BUILT-IN FUNCTIONS - functions that


come built into Python for us to use. Remember when we were
using print or str? Both of these functions are built into the language
for us, which means we have been using built-in functions all along!

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"

# Built-in function: len()


length_of_destination = len(destination_name)

# Built-in function: print()


print(length_of_destination)

Would output the value of length_of_destination:

28

Here we are using a total of two built-in functions in our


example: print(), and len().

And yes, if you’re wondering, that is a real railway station in India!

There are even more obscure ones like help() where Python will print a
link to documentation for us and provide some details:

help("string")

Would output (shortened for readability):

NAME
string - A collection of string constants.

MODULE REFERENCE
https://docs.python.org/3.8/library/string
44

The following documentation is automatically generated


from the Python
source files. It may be incomplete, incorrect or
include features that
are considered implementation detail and may vary
between Python
implementations. When in doubt, consult the module
reference at the
location listed above.
.....

Check out all the latest built-in functions in the official Python docs.

You might also like