Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python_enap

This document outlines the first two modules of a Python programming course, focusing on variables, operators, conditions, loops, and functions. It includes learning objectives, variable assignment rules, type casting, mathematical and comparison operators, conditional statements, and loop structures. Additionally, it provides code examples and exercises for practical understanding in a Google Colab environment.

Uploaded by

maganeu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python_enap

This document outlines the first two modules of a Python programming course, focusing on variables, operators, conditions, loops, and functions. It includes learning objectives, variable assignment rules, type casting, mathematical and comparison operators, conditional statements, and loop structures. Additionally, it provides code examples and exercises for practical understanding in a Google Colab environment.

Uploaded by

maganeu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

18/05/2021 module1_python

Module 1: Variables, Operators, Conditions


Logistics:

Press Shift + Enter keys to run each block of code on Google Colab environment or copy and paste the
codes/comments into a python file.
Conceptual introductions and explanations are provided in text blocks. Code-related explanations are
included as comments above the codes.
Exercises/practice problems are labeled in each module. For coding exercises, you could download an
external Python IDE (e.g. Anaconda) to program and test your implementation. One possible
implementation of the exercise are provided under the problem.

Learning Objectives:

1. Define and modify variables of various data types. Convert between data types.
2. Understand the characteristics and uses of each operation and the corresponding output.
3. Understand and correctly these statements for checking conditions.

1.1: Variables

1.1.1: Variable Assignment


Variables are the same as variables in math, except math variables are often letters, but programming
variables could be words.

Variable: a container that holds some information.

Note about variable declaration:

Case-sensitive
MUST start with either a letter or underscore; CANNOT start with numbers.
CANNOT be the same name as Python keywords (e.g. class, finally, etc.)
do NOT specify type of information stored in the variable. (Refer to the following codes for an example.)

In [ ]:

# Examples of variable declarations


width = 10

# Notice the "H" is capitalized


Height = 5

area = 0

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 1/12
18/05/2021 module1_python

In [ ]:

width

Out[ ]:

10

In [ ]:

# Expect an ERROR because the "height" variable is case-sensitive.


# ERROR CODE: "height" is not defined.

height

--------------------------------------------------------------------------
-
NameError Traceback (most recent call las
t)
<ipython-input-6-d56756f3e5e3> in <module>()
2 # ERROR CODE: "height" is not defined.
3
----> 4 height

NameError: name 'height' is not defined

In [ ]:

Height

Out[ ]:

In [ ]:

# Using a python keyword as a variable name


# ERROR CODE: invalid syntax

global = 1

global

File "<ipython-input-8-4909dc42d849>", line 4


global = 1
^
SyntaxError: invalid syntax

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 2/12
18/05/2021 module1_python

In [ ]:

# More declarations for different variable types

# storing a string
helloMessage = "Hello World!"
first_name = "John"

# storing a char
character_example = 'a'

# storing a float
_newFloat = 1.0

# storing a boolean value


bool_Condition = True

In [ ]:

helloMessage

Out[ ]:

'Hello World!'

In [ ]:

character_example

Out[ ]:

'a'

In [ ]:

_newFloat

Out[ ]:

1.0

In [ ]:

bool_Condition

Out[ ]:

True

1.1.2: Type Casting


From Topic 1.1.1, we learned how to properly declare a variable name for different date types. In this topic,
we will explore how to "cast" or convert data type between one another.

Helpful function: type() defines the type of the data

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 3/12
18/05/2021 module1_python

In [ ]:

# From declaration above, width = 10 and 10 is an int, so we expects the function to re


turn int
type(width)

Out[ ]:

int

In [ ]:

type(helloMessage)

Out[ ]:

str

In [ ]:

type(bool_Condition)

Out[ ]:

bool

In [ ]:

# Let's cast a float into an int and vice verse


# We will cast the type and the store it in a new variable
width_float = float(width)

type(width_float)

Out[ ]:

float

In [ ]:

# Cast from float to int


width_int = int(width_float)

type(width_int)

Out[ ]:

int

In [ ]:

# Cast between string and int


# Recall that width stores an int

# convert width to string


width_string = str(width)
type(width_string)

Out[ ]:

str

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 4/12
18/05/2021 module1_python

In [ ]:

# convert width_string back to an int


type(int(width_string))

Out[ ]:

int

1.2: Operators

1.1.1 Mathematical Operators

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 5/12
18/05/2021 module1_python

In [ ]:

# Basic mathematical operations with Numbers

# Addition
print(5+23)

# Subtraction
print(100-25)

# Multiplication
print(5*10)

# Power/Exponent
# ** operator is equivalent to exponent
print(5**2)

# 5*5 = 5^2 = 5**2


print(5*5)

# Division (float)
# Return the actual decimal value of division
print(36/4)
print(10/3)

# Division (int)
# Return an int. If the actual quotient is a decimal value, only whole number is return
ed
print(10//3)
print(19//6)

# Modular Division: return the remainder of division


print(10%3)

28
75
50
25
25
9.0
3.3333333333333335
3
3
1

In [ ]:

# Operations with Strings and Characters


print("foo" * 5)
print('x'*3)

foofoofoofoofoo
xxx

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 6/12
18/05/2021 module1_python

In [ ]:

# ERROR: compiler treats x as a variable, not a character


print(x*3)

--------------------------------------------------------------------------
-
NameError Traceback (most recent call las
t)
<ipython-input-23-47a2cb16f654> in <module>()
1 # ERROR: compiler treats x as a variable, not a character
----> 2 print(x*3)

NameError: name 'x' is not defined

In [ ]:

# ERROR: cannot concatenate an int to a string --> need to cast int to string
print("hello" + 5)

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
<ipython-input-24-8beae78f288a> in <module>()
1 # ERROR: cannot concatenate an int to a string --> need to cast in
t to string
----> 2 print("hello" + 5)

TypeError: must be str, not int

In [ ]:

# Fix
print("hello " + str(5))

hello 5

In [ ]:

# String addition = concatenation


print("hello " + "world")

hello world

1.1.2: Other Operators

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 7/12
18/05/2021 module1_python

In [ ]:

# Comparators: return boolean value

# Equality ==
# Note: MUST be Double equal signs, single equal sign is assignment
print(5 == 5.0)

# Greater than >


print(7 > 1)

# Less than <


print(1.5 < 90)

# Greater than or equal to >=


print(5.0 >= 5)
print(5.0 >= 4)
print(5 >= 13)

# Less than or equal to <=


print(10 <= 10.0)
print(10 <= 20)
print(8 <= 3)

True
True
True
True
True
False
True
True
False

In [ ]:

# Comparators on Strings

print("hello" < "world")


print("hello" == "world")
print("hello" > "world")

print("hello" == "hello")

print("cat" < "dog")

True
False
False
True
True

1.3: Conditional Statements

1.3.1: If Conditions

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 8/12
18/05/2021 module1_python

Important Notices:

Order of the conditions matter!


If more than one conditions are satified, then the actions associated with the first satifying condition
will execute and skip the remaining conditions and codes.
"elif" = "else if"
"elif" denotes the same meaning as "else if"
At least one condition MUST be provided for both if and elif clauses, else ERROR!
Parentheses for if and elif is optional. Your code will work with or without the ().

In [ ]:

x = 7
y = 14

if (2*x == y):
print("y is double of x")
elif (x**2 == y):
print("y is the squared of x")
else:
print("y is NOT double of x")

y is double of x

In [ ]:

x = 7
y = 49

if (2*x == y):
print("y is double of x")
elif (x**2 == y):
print("y is the squared of x")
else:
print("y is NOT related to x")

y is the squared of x

In [ ]:

x = 7
y = 50

if (2*x == y):
print("y is double of x")
elif (x**2 == y):
print("y is the squared of x")
else:
print("y is NOT double nor squared of x")

y is NOT double nor squared of x

1.3.2: Switch Cases

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 9/12
18/05/2021 module1_python

Python does NOT have an implementation for the switch cases, but one way to implement the switch case is
with the dictionary, a data structure that stores the key-value pair (Module 3).

The switch conditions are stored as keys in the dictionary, and actions stored as the value.
If there is a series of actions for each case, then consider writing a function for each case and use
the function calls as the value.
The default condition is manually listed as a key-value in the get().

In [ ]:

def switcher(number):

# dictionary (from Module 3) to store switch cases


# If not found, then get() the default value
return {
'0':"Entered 0",
'1':"Entered 1",
'2':"Entered 2",
'3':"Entered 3",
'4':"Entered 4",
'5':"Entered 5",
'6':"Entered 6",
'7':"Entered 7",
'8':"Entered 8",
'9':"Entered 9",
}.get(number,"Invalid number!")

# input() reads in an user input from stdin


number = input("Dial a number")
switcher(number)

Dial a number9

Out[ ]:

'Entered 9'

In [ ]:

"""
EXERCISE: implement the above switch case example using if/else conditions

Prompt: For each digit between 0-9, the program will print a confirmation
for the entered value or print "invalid inputs" for all other numbers.
"""

Out[ ]:

'\nEXERCISE: implement the above switch case example using if/else conditi
ons\n\nPrompt: For each digit between 0-9, the program will print a confir
mation \nfor the entered value or print "invalid inputs" for all other num
bers.\n'

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 10/12
18/05/2021 module1_python

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 11/12
18/05/2021 module1_python

In [ ]:

number = input("Dial a number")

if number == '0':
print("Entered 0")
elif number == '1':
print("Entered 1")
elif number == '2':
print("Entered 2")
elif number == '3':
print("Entered 3")
elif number == '4':
print("Entered 4")
elif number == '5':
print("Entered 5")
elif number == '6':
print("Entered 6")
elif number == '7':
print("Entered 7")
elif number == '8':
print("Entered 8")
elif number == '9':
print("Entered 9")
else:
print("Invalid number!")

Dial a number9
Entered 9

In [ ]:

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 12/12
18/05/2021 module2_python

Module 2: Loops, Functions


Learning Objectives:

1. Understand the structure of the for and while loops and the difference between iterate over index vs.
element. Recognize the effects of break and continue keywords.
2. Construct new functions and make function calls. Understanding the role of parameter.

2.1: Loops

2.1.1: For/While Loops

Python has one implementation/structure of the FOR loop that works for both the regular for loop and the
forEach loop from other programming languages.

There are a few structural differences for the Python FOR loop. Consider them in the examples below.

In [ ]:

"""
The variable i serves as the counter over the RANGE of [0,10),
inclusive of lower but exclusive of upper bound.

The lower bound of 0 does NOT need to be specify;


it is implemented by default unless another lower bound is specified.

Also by default, if there does NOT exists a third parameter for range(),
then i increments by 1.
"""
for i in range(10):
print(i)

0
1
2
3
4
5
6
7
8
9

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 1/12
18/05/2021 module2_python

In [ ]:

"""
This examples specifies a lower bound that differs from the default value of 0.

The order of the parameter is ALWAYS:


1. Starting position, inclusive
2. Stopping position, exclusive
3. Incremental value

In this example, x starts at the value of 2 and stops at 9 inclusively, or 10 exclusiv


e,
with x increments by 1 with each iteration.
"""
for x in range(2, 10):
print(i)

9
9
9
9
9
9
9
9

In [ ]:

"""
The third parameter in range() defines the number of steps to increment the counter.

In this example, x starts at the value of 0 and stops at 9 inclusively, or 10 exclusiv


e,
with x increments by 3 with each iteration.
"""

for i in range(0, 10, 3):


print(i)

0
3
6
9

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 2/12
18/05/2021 module2_python

In [ ]:

"""
forEeach loop over the each character in a string.

In this example, the variable 'i' represents every element/character of 'hello.'


"""

for i in "hello!":
print(i)

h
e
l
l
o
!

In [ ]:

"""
We could also iterate over the string by index.

Consider the following example that iterates over the string by index,
starting at index 0 and ending at the last element, with the counter increments by 2,
so ONLY printing every other element in the string.
"""

string = "hello world!"


for i in range(0, len(string), 2):
print(str(i) + "th letter is "+ string[i])

0th letter is h
2th letter is l
4th letter is o
6th letter is w
8th letter is r
10th letter is d

The structure of the WHILE loop remains mostly identical to other programming languages.

Take a look at the example below

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 3/12
18/05/2021 module2_python

In [ ]:

# Note: without updating the variable in the while loop, this will be an INFINITE loo
p!!

count = 0
while (count < 10):
print(count)

# IMPORTANT!!! Updating the counter!


count += 1

0
1
2
3
4
5
6
7
8
9

2.1.2: Continue/Break Keywords

How to maniputate loops (FOR and WHILE):

Break: skip the remaining codes in the loop and the remanining iterations, break out of the innnermost
loop.
Continue : skip the remaining codes in the loop and continue to the next iteration of the loop

In [ ]:

# Consider a program that echos the user input, except for "end"
# This program runs infinity, except when the user input "end" to terminate it

while True:
user = input("Enter something to be repeated: ")

## When break is triggered, the print() below will NOT run


## The program will break out of the loop when this keyword is read.
if user=="end":
print("Terminate the program!!!")
break
print(user)

Enter something to be repeated: a


a
Enter something to be repeated: g
g
Enter something to be repeated: end
Terminate the program!!!

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 4/12
18/05/2021 module2_python

In [ ]:

# Without using the keyword "break," this is another implementation of the same program
from above using a variable.

end = False
while end == False:
user = input("Enter something to be repeated: ")
if user=="end":
print("Program Ended!!!")
end = True
else:
print(user)

Enter something to be repeated: a


a
Enter something to be repeated: f
f
Enter something to be repeated: h
h
Enter something to be repeated: d
d
Enter something to be repeated: end
Program Ended!!!

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 5/12
18/05/2021 module2_python

In [ ]:

"""
Let's consider a loop that counts from 1-20, but skip all numbers that are mulitple of
5.
In this case, we could NOT use the break keyword, because that will terminate the loop.
We want to "continue" the loop except for a few numbers.

We will implement this with both a while and a for loop.


"""

count = 1

# WHILE loop implementation


while count + 1 <= 20:
if count % 5 == 0:
print("SKIP")
count += 1
continue
print(count)
count += 1

1
2
3
4
SKIP
6
7
8
9
SKIP
11
12
13
14
SKIP
16
17
18
19

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 6/12
18/05/2021 module2_python

In [ ]:

# FOR loop implementation

for i in range (1, 20):


if i % 5 == 0:
print("SKIP")
continue
print(i)

1
2
3
4
SKIP
6
7
8
9
SKIP
11
12
13
14
SKIP
16
17
18
19

2.2: Functions

Functions are useful when you are given a problem that could be broken down into multiple steps and some
steps are used repetitively. Then, having a function for those steps are convenient because it reduces code
repetition and makes code more organized.

Notes about defining a new function:

1. Define/initialize a new function with the def keyword before the function name
2. Do NO define the return type in the function declaration.
3. Do NOT forget about the function parameter if your function needs information from the main() or
other functions.
4. RETURN statement is NOT required, depending on the functions.

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 7/12
18/05/2021 module2_python

In [ ]:

"""
We will write our own function that tests whether a traingle of 3 sides is a right tria
ngle.
Since we could not control the order the sides that user gives us (such that c is the l
ongest length),
we need to need to manually check if c is the longest length (length a and b can be any
order).
Otherwise, our Pythagorean Theorem will failed.
"""

def isRightTriangle(a, b, c):

# Reassign variable values to ensure c is the longest length


if (max(a,b,c) != c):

# tmp stores the previous c values, that's not the longest length
tmp = c
c = max(a,b,c)

if a == c:
a = tmp
elif b == c:
b = tmp

# Apply the formula


if a**2 + b**2 == c**2:
print("Right Triangle")

# If the program sees a return statement, this is the END of the program/function
return True

# These two lines will ONLY run when the IF condition is false
print("NOT a right triangle")
return False

# Prompt the user to enter 3 lengths


def main():
a = input("Enter the length for the first edge of the traingle:")
b = input("Enter the length for the second edge of the traingle:")
c = input("Enter the length for the last edge of the traingle:")

# User inputs are stored as a string, so we cast them to be int


return isRightTriangle(int(a), int(b), int(c))

if __name__ == "__main__":
main()

Enter the length for the first edge of the traingle:5


Enter the length for the second edge of the traingle:4
Enter the length for the last edge of the traingle:3
Right Triangle

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 8/12
18/05/2021 module2_python

In [ ]:

"""
Another example: determine if the user input is a palindrome.

Palindrome: If a word/sentence is spelled the same way when it is reversed.


EX: racecar

For this example, let's make this more involved.


In stead checking if a word is a palindrome, we will test if a sentence is a palindrom
e.

In order to write this program, we will set a few specifications:


- Treat capitalized letters as lowercase
- Ignore all white spaces and punctuations
- An empty sentence/string IS consider to be a palindrome.
"""

# import the string package


# We will go over packages/libraries more in Module 5
import string

# This implementation of the function RETURN a boolean value, True/False


def isPalindrome(str):

# Since we could not control what user enters for the sentence, let's sanitize the se
ntence first.
# We will remove all punctuations and white spaces from the sentence, make all letter
s lowercase
exclude = set(string.punctuation)
str = ''.join(ch for ch in str if ch not in exclude)
str = str.replace(" ", "").lower()

# Compare the original string with the string in reversed order


# Notation of str[::-1]: first 2 numbers define the start and end of string, last n
umber of -1 means in reversed order

# Check if the string is the same in reversed order as the original order
if str == str[::-1]:
return True
else:
return False

# Prompt the user to enter the sentence


def main():
userSentence = input("Enter a sentence to be tested as a palindrome:")

if (isPalindrome(userSentence)):
print(userSentence + " is a palindrome!")
else:
print(userSentence + " is NOT a palindrome!")

if __name__ == "__main__":
main()

Enter a sentence to be tested as a palindrome:racecar


racecar is a palindrome!

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 9/12
18/05/2021 module2_python

In [ ]:

# Consider this implementation of the function that RETURN a string.


# Take note of the difference between the main() and isPalindrom() following this chang
e.

import string

def isPalindrome(str):
exclude = set(string.punctuation)
str = ''.join(ch for ch in str if ch not in exclude)
str = str.replace(" ", "").lower()
if str == str[::-1]:
return str + " is a palindrome!"
else:
return str + " is NOT a palindrome!"

def main():
userSentence = input("Enter a sentence to be tested as a palindrome:")
print(isPalindrome(userSentence))

if __name__ == "__main__":
main()

Enter a sentence to be tested as a palindrome:hello


hello is NOT a palindrome!

In [ ]:

"""
Above we worked through an example that test whether a sentence is a palindrome.
Now it's your turn.

Exercise: write a function to test if a word from the user is a palindrome.

Function declarations are provided for you.


"""

def isPalindrome(str):

# Prompt the user to enter the sentence


def main():
userInput = input("Enter a WORD to be tested as a palindrome:")

if (isPalindrome(userInput)):
print(userInput + " is a palindrome!")
else:
print(userInput + " is NOT a palindrome!")

if __name__ == "__main__":
main()

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 10/12
18/05/2021 module2_python

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

DO NOT LOOK AT THE SOLUTION BELOW BEFORE YOU TRY THE EXERCISE!

In [ ]:

# One implementation of solution for above exercise.

def isPalindrome(str):
str = str.lower()
if (str == str[::-1]):
return True
else:
return False

# Prompt the user to enter the sentence


def main():
userInput = input("Enter a WORD to be tested as a palindrome:")

if (isPalindrome(userInput)):
print(userInput + " is a palindrome!")
else:
print(userInput + " is NOT a palindrome!")

if __name__ == "__main__":
main()

Enter a WORD to be tested as a palindrome:racecar


racecar is a palindrome!

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 11/12
18/05/2021 module2_python

In [ ]:

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 12/12
18/05/2021 module3_python

Unit 3: Basic Data Structures


Learning Objective:

1. Recognize the key characteristics of each structure. Correctly utilize each structure when appropriate
and access the corresponding data stored on the structure.

Refer to this Doc (https://docs.python.org/3/tutorial/datastructures.html) for additional information on each


data structure.

3.1: List

List: a mutable data structure that stores elements in an unordered format, like an array.

In [ ]:

# Initiate an empty list


list1 = []
# OR
list1 = list()

# Initiate a list with elements


list2 = ['hello', 'hola', 'olá']

"""
Elements in list does NOT have to be the same type, but this is uncommon.
In this case, each list could represent the series of information about a person,
but you will need to remember what information is stored at each index. ---> There is a
better option for this purpose - dictionary.
"""
list3 = ["John", "male", 20, False]

In [ ]:

# Accessing information stored in the list by position ("index")


# Note: in CS, first position is ALWAYS 0
print("First element in list2 : "+ list2[0])
print("Second element in list2 : "+ list2[1])

First element in list2 : hello


Second element in list2 : hola

In [ ]:

# Insert a new element as a specific location, at index 1


list2.insert(1,'hallo')
list2[1]

Out[ ]:

'hallo'

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 1/12
18/05/2021 module3_python

In [ ]:

# Append a new element at the END of the list


list2.append('bye')
list2

Out[ ]:

['hello', 'hallo', 'hola', 'olá', 'bye']

In [ ]:

# Remove an element from the list by specifying the element that you want to remove
list2.remove('hello')

In [ ]:

# list2 after 'hello' is REMOVED


list2

Out[ ]:

['hallo', 'hola', 'olá', 'bye']

In [ ]:

"""
Another way to remove an element: pop()
pop() allows you to identify the position you
"""

list2.append("hello")

list2.pop()

list2

Out[ ]:

['hallo', 'hola', 'olá', 'bye']

In [ ]:

"""
Lists could also be sorted.
Method of sorting depends on how the comparable interface is implemented for the object
s in the list.

In this case of list2, sort() works by sorting individual characters in the string acco
rding to the ASCII code.
"""
list2.sort()
list2

Out[ ]:

['bye', 'hallo', 'hola', 'olá']

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 2/12
18/05/2021 module3_python

In [ ]:

"""
Since list is dynamic, meaning that the size of the list grow or shrink as we insert or
remove elements,
we could call len() to find the size of the list at a given time.
"""

# Since len() returns an int, in order to concatenate it to a string, we need to cast i


t.
print("size of list1 = " + str(len(list1)))
print("size of list2 = " + str(len(list2)))

size of list1 = 0
size of list2 = 4

In [ ]:

# Print items in list as a string, separated by a comma


",".join(list2)

Out[ ]:

'bye,hallo,hola,olá'

In [ ]:

# You could also have a list of lists. For example:

lists = []
lists.append([1,2,3])
lists.append(['a','b','c'])

lists

Out[ ]:

[[1, 2, 3], ['a', 'b', 'c']]

In [ ]:

# Similarly, you could index the over multi-dimensional lists

lists[1]

Out[ ]:

['a', 'b', 'c']

In [ ]:

lists[1][0]

Out[ ]:

'a'

3.2: Tuple

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 3/12
18/05/2021 module3_python

Tuple: immutable "list" which cannot be manipulated once created.

They support all the operations lists supports, except for those that modify the list.

In [ ]:

# Initialize an empty tuple


y = tuple()
y

# Create a new tuple of elements


x = (1,2,3)

In [ ]:

# ERROR: canot add to a tuple


x.append(4)

--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
<ipython-input-30-89cbd0c10841> in <module>()
1 # ERROR: canot add to a tuple
----> 2 x.append(4)

AttributeError: 'tuple' object has no attribute 'append'

In [ ]:

# This is OK because creating a new tuple with x and (4,5,6) added at the end
x + (4,5,6)

Out[ ]:

(1, 2, 3, 4, 5, 6)

In [ ]:

# x is NOT modified by the previous line


x

Out[ ]:

(1, 2, 3)

In [ ]:

# Create a new tuple with x apearing twice


x * 2

Out[ ]:

(1, 2, 3, 1, 2, 3)

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 4/12
18/05/2021 module3_python

In [ ]:

# Index on the elements in the tuple


x.index(3)

Out[ ]:

In [ ]:

# shorthand for
# (a,b,c) = (1,2,3)

# This also assigns a = 1, b = 2, c = 3

a,b,c = 1,2,3

In [ ]:

Out[ ]:

In [ ]:

Out[ ]:

In [ ]:

Out[ ]:

In [ ]:

# Convert a tuple into a list


x = (1,2,3,4)
list(x)

Out[ ]:

[1, 2, 3, 4]

In [ ]:

# Convert a list into a tuple


x = [1,2,3,4]
tuple(x)

Out[ ]:

(1, 2, 3, 4)

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 5/12
18/05/2021 module3_python

In [ ]:

# Declare a new tuple, name "person"


person = ('Jane','Doe', 21)

# "Pack"/associate each element of the tuple with a label. Note the order of labels.
first, last, age = person

In [ ]:

first

Out[ ]:

'Jane'

In [ ]:

last

Out[ ]:

'Doe'

In [ ]:

age

Out[ ]:

21

In [ ]:

# ERROR: x is a tuple is 4 values but ONLY trying to unpack 3 elements.


# Mismatch on the size of tuple
x = (1,2,3,4)

a,b,c = x

--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
<ipython-input-45-4acb77e9e93d> in <module>()
3 x = (1,2,3,4)
4
----> 5 a,b,c = x

ValueError: too many values to unpack (expected 3)

In [ ]:

# This is OK!
x = [1,2,3,4]
a,b,c,d = x

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 6/12
18/05/2021 module3_python

In [ ]:

Out[ ]:

In [ ]:

Out[ ]:

In [ ]:

Out[ ]:

In [ ]:

Out[ ]:

3.3: Set

Set: a mutable data structure that stores non-duplicated, immutable objects and sorts the elements in
ascending order. Every element in the set is unique.

In [ ]:

# Initialize an empty set


newSet = set()
newSet

Out[ ]:

set()

In [ ]:

# A set with elements


ex1 = {1, 2, 2, 1, 1}

ex1

Out[ ]:

{1, 2}

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 7/12
18/05/2021 module3_python

In [ ]:

ex2 = {j for j in range(10)}


ex2

Out[ ]:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

In [ ]:

# 2 already exists in the ex2. What happen if we want to add 2 again?


# Note: The implementation for set did NOT define append(), so we will use add().
# add() will insert the new element in the correct position with the sorting of the
set
ex2.add(2)
ex2.add(100)
ex2.add(50)
ex2

Out[ ]:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 100}

In [ ]:

# mutable objects can't go in a set


d_set = {[1,2,3]}

d_set

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
<ipython-input-55-6b6994b2706f> in <module>()
1 # mutable objects can't go in a set
----> 2 d_set = {[1,2,3]}
3
4 d_set

TypeError: unhashable type: 'list'

In [ ]:

# Convert a list to a set


ages = [10, 5, 4, 5, 2, 1, 5]

set_of_ages = set(ages)

set_of_ages

Out[ ]:

{1, 2, 4, 5, 10}

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 8/12
18/05/2021 module3_python

In [ ]:

# Convert a set to a list


list_of_ages = list(set_of_ages)

list_of_ages

Out[ ]:

[1, 2, 4, 5, 10]

In [ ]:

# Convert a set to a tuple


tuple_of_ages = tuple(list_of_ages)

tuple_of_ages

Out[ ]:

(1, 2, 4, 5, 10)

In [ ]:

# Order is irrelevant in set comparison since elements are sorted

{1,2,3} == {2,1,3}

Out[ ]:

True

3.4: Dictionary

Dictionary: a data structure that stores key-value pairs in which the keys MUST be immutatble objects.

In [ ]:

# Initiate an empty dictionary


# Same as set, but with :
dict = {}

# Declare a dictionary with key/value pairs


dict2 = {'a': 5, 'b': 10, 'c': 100, 'd': 9.5}

In [ ]:

# Accessing data in a dictionary with a key


dict2['b']

Out[ ]:

10

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 9/12
18/05/2021 module3_python

In [ ]:

# Update value of an existing key


dict2['b'] = 50

dict2['b']

Out[ ]:

50

In [ ]:

# What happen if we want to access the value for a non-existing key? (e.g. 'z')

# We might expect an ERROR because this key doesn't exist, so it doesn't have a value.
# That is a correct assumption.
dict2['z']

--------------------------------------------------------------------------
-
KeyError Traceback (most recent call las
t)
<ipython-input-63-ddfe9c24c2d2> in <module>()
4 # We might expect an ERROR because this key doesn't exist, so it d
oesn't have a value.
5 # That is a correct assumption.
----> 6 dict2['z']

KeyError: 'z'

In [ ]:

# But if what if we do this, will this still return an ERROR?


dict2['z'] = 999

dict2['z']

Out[ ]:

999

WHY??

The previous block of code works because we "update" the value of the key first, update = insert (in this
case), and by the time we want to access the value of this key, this key already exists in the dictionary for the
assigned mapping.

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 10/12
18/05/2021 module3_python

In [ ]:

# Values in the dictionary can be mix-typed


# Let's look at an example with dict{}, an empty dictionary initiated above.
# Fist, we will insert some key/value pairs into the program.

dict["greeting"] = "hello message"


dict["alphabet"] = ['a', 'b', 'c', 'd', 'e']
dict["check-in"] = False
dict["phoneNumber"] = 8007782346

dict

Out[ ]:

{'alphabet': ['a', 'b', 'c', 'd', 'e'],


'check-in': False,
'greeting': 'hello message',
'phoneNumber': 8007782346}

In [ ]:

# IMPORTANT Note: key must be immutatble objects (something that cannot be changed)
# String is immutable, because you could not just delete a character in a string. A str
ing is a string, the way it is.

# From above, we see that a list can be a value in the dictionary.


# What happen when we try to make it a key?

# ERROR: unhashable type of list

# Because we could modify the list by inserting new element, sorting elements, deleting
elements, or other ways of modifying it, it CANNOT be a key

dict[['a','b', 'c']] = [False, True, False]

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
<ipython-input-66-7e50947ec831> in <module>()
9 # Because we could modify the list by inserting new element, sorti
ng elements, deleting elements, or other ways of modifying it, it CANNOT b
e a key
10
---> 11 dict[['a','b', 'c']] = [False, True, False]

TypeError: unhashable type: 'list'

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 11/12
18/05/2021 module3_python

In [ ]:

# But since tuple is immutatble, we could replace the list with a tuple
dict[('a','b', 'c')] = [False, True, False]

dict

Out[ ]:

{('a', 'b', 'c'): [False, True, False],


'alphabet': ['a', 'b', 'c', 'd', 'e'],
'check-in': False,
'greeting': 'hello message',
'phoneNumber': 8007782346}

In [ ]:

# We could also retrieve all the keys


dict.keys()

Out[ ]:

dict_keys(['greeting', 'alphabet', 'check-in', 'phoneNumber', ('a', 'b',


'c')])

In [ ]:

# Or all values
dict.values()

Out[ ]:

dict_values(['hello message', ['a', 'b', 'c', 'd', 'e'], False, 800778234


6, [False, True, False]])

In [ ]:

# Elements in a dictionary could also be returned as a pair.


dict.items()

Out[ ]:

dict_items([('greeting', 'hello message'), ('alphabet', ['a', 'b', 'c',


'd', 'e']), ('check-in', False), ('phoneNumber', 8007782346), (('a', 'b',
'c'), [False, True, False])])

In [ ]:

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 12/12
18/05/2021 module4_python

Module 4: Object-Oriented Programming


Learning Objectives:

1. Understand the use of init () method and the self parameter. Correctly declare a class object.
2. Recognize the difference between functions and methods and the scope of methods, and make method
calls.
3. Understand how the level of inheritance affect method calls and variables.

Let's consider the library system as an example of Object-Oriented Programming.

A library has a number of books.

What should the data associated with each book be?


Are there any operations that a book should support?

So, we will build the LibraryBook class to store data about each book and support methods/operations
needed in the Library System.

Classes are blueprints or designs or templates for instances. The relationship between a class and an
instance is similar to the one between a cookie cutter and a cookie.

A single cookie cutter can make any number of cookies. The cutter defines the shape of the cookie.
The cookies are edible, but the cookie cutter is not.

References from Columbia University Professor Daniel Bauer's ENGI1006 Lectures

In [ ]:

# LibraryBook is the name of the class


class LibraryBook:
"""
A library book
"""

# pass indicates that the body/suit of the class definition is empty.


pass

In [ ]:

# This will create an instance of the class.


my_book = LibraryBook()
my_book

Out[ ]:

<__main__.LibraryBook at 0x7fca565e5d30>

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 1/11
18/05/2021 module4_python

In [ ]:

type(my_book)

Out[ ]:

__main__.LibraryBook

In [ ]:

# Another way to check the type of some object


isinstance(my_book, LibraryBook)

Out[ ]:

True

Why use classes and when??

Objects simplify problems by providing an abstraction over certain data types and their functionality.

Instead of thinking of the problem in terms of individual strings, integers, etc. we can now
think in terms of LibraryBooks (or other objects).

Encapsulation

Data and functionality is bundled in objects.


The methods provide an interface to the object. Ideally the individual data are only written and read
through methods.
This means that details about how the functionality is implemented is hidden from the programmer. For
example, we don't know how the append method on lists is implemented.
This idea allow classes to be shared (in libraries) and used by others (or re-used by you) without having
to read through the source code for the class.

4.1: init, Self Parameter

Data fields - Each instance owns its own data (the class can define what names the data fields have).

The init(self, ...) method is automatically called by Python when a new instance is created. This method is
called the class constructor; it initialize the data values in the class.

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 2/11
18/05/2021 module4_python

In [ ]:

"""
A library book.
"""
class LibraryBook (object):

"""
The self parameter is REQUIRED within the class,
because it tells the program to retrieve/act on the instance object
that called it.
"""
def __init__(self, title, author, pub_year, call_no):
self.title = title
self.author = author
self.year = pub_year
self.call_number = call_no
self.checked_out = False

In [ ]:

"""
Since we have already created my_book as a LibraryBook object,
we could now manually add the title, author,... information associated with the book.
"""

my_book.title = "Harry Potter and the Philosopher's Stone"


my_book.author = ('Rowling', 'J.K.')
my_book.year = 1998
my_book.call_number = "PZ7.R79835"

In [ ]:

# Retrieve a specific data field of an instance by calling instance name and the field
name
my_book.author

Out[ ]:

('Rowling', 'J.K.')

In [ ]:

"""
Or we could pass all the information into the __init__ to set up the fields
when creating the new instance.
"""

new_book = LibraryBook("Harry Potter and the Sorcerer's Stone",


("Rowling","J.K."), 1998, "PZ7.R79835")

new_book.author

Out[ ]:

('Rowling', 'J.K.')

4.2: Methods

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 3/11
18/05/2021 module4_python

Methods contain the functionality of the object.

These are defined in the class.

4.2.1: Writing a Method

In [ ]:

class LibraryBook(object):
"""
A library book.
"""

def __init__(self, title, author, pub_year, call_no):


self.title = title
self.author = author
self.year = pub_year
self.call_number = call_no

"""
Methods for LibraryBook
"""

# Returns the title and author information of the book as a string


def title_and_author(self):
return "{} {}: {}".format(self.author[1], self.author[0], self.title)

# Prints all information associated with a book in this format


def __str__(self): #make sure that __str__ returns a string!
return "{} {} ({}): {}".format(self.author[1], self.author[0], self.year, self.
title)

# Returns a string representation of the book with it' title and call_number
def __repr__(self):
return "<Book: {} ({})>".format(self.title, self.call_number)

In [ ]:

# Simply calling the instance itself is triggering __repr__()


new_book

Out[ ]:

<__main__.LibraryBook at 0x7fca565db278>

In [ ]:

# print is triggering the __string__()


print(new_book)

<__main__.LibraryBook object at 0x7fca565db278>

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 4/11
18/05/2021 module4_python

In [ ]:

new_book = LibraryBook("Harry Potter and the Sorcerer's Stone",


("Rowling","J.K."), 1998, "PZ7.R79835")

new_book.title_and_author()

Out[ ]:

"J.K. Rowling: Harry Potter and the Sorcerer's Stone"

4.2.2: Internal/External Method Calls

The ONLY differce is:

Externally/outside the class, you would simply call instanceName.method(), like


new_book.title_and_author()
Internally/within the class, you would use the self to points to that specific instance of the class, like
self.title_and_author()

4.3: Inheritance

Example of instance-of relationship.

nemo is an instance of ClownFish.

In [ ]:

class ClownFish(object):
pass

nemo = ClownFish()

In [ ]:

type(nemo)

Out[ ]:

__main__.ClownFish

In [ ]:

isinstance(nemo, ClownFish)

Out[ ]:

True

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 5/11
18/05/2021 module4_python

But ClownFish is also a fish, a vertebrate, and an animal, and each could a separate class.

In this case, we need to have relationships between class.

The ClownFish class could have the parent class Fish,


which could have a parent class Vertebrate,
which could have a parent class Animal...

This relationship is called the is-a relationship. It holds between a child class and its parent class. Every
class in Python has at least one parent class.

(Note that the is-a relationship is transitive, so every ClownFish is also an Animal.)

There is a top-most class in Python called object. So far, when we defined classes, we always made object
the direct parent of the class.

In [ ]:

class Animal(object):
pass

class Vertebrate(Animal):
pass

class Fish(Vertebrate):
pass

class ClownFish(Fish):
pass

class TangFish(Fish):
pass

In [ ]:

nemo = ClownFish()

In [ ]:

isinstance(nemo, ClownFish)

Out[ ]:

True

In [ ]:

isinstance(nemo, TangFish)

Out[ ]:

False

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 6/11
18/05/2021 module4_python

In [ ]:

# the is-a relationship is transitive


isinstance(nemo, Animal)

Out[ ]:

True

In [ ]:

# All classes have a parent class of Object.


isinstance(nemo, object)

Out[ ]:

True

4.3.1: Inherited Methods

Why use inheritance?

Every class also has access to the class attributes of the parent class. In particular, methods defined on the
parent class can be called on instances of their "decendants".

In [ ]:

class Fish(Animal):
def speak(self):
return "Blub"

class ClownFish(Fish):
pass

class TangFish(Fish):
pass

In [ ]:

dory = TangFish()

"""
TangFish is a child class of Fish, so it can access the speak() from Fish class.
It will first look for the method call within its class, and if not found, then repeat
the search for each parent level up.
"""
dory.speak()

Out[ ]:

'Blub'

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 7/11
18/05/2021 module4_python

In [ ]:

nemo = ClownFish()

# ClownFish is a child class of Fish, so it can access the speak() from Fish class

nemo.speak()

Out[ ]:

'Blub'

What if we want different functionality for a child class? We can override the method (by writing a new one
with the same name).

In [ ]:

class TangFish(Fish):
def speak(self):
return "Hello, I'm a TangFish instance."

In [ ]:

dory = TangFish()

# this speak() is from the TangFish class


dory.speak()

Out[ ]:

"Hello, I'm a TangFish instance."

In [ ]:

"""
On the other hand, since the ClownFish class still does NOT
define the speak(), instances of ClownFish are still using the
speak() from the parent class of Fish.
"""

nemo = ClownFish()
nemo.speak()

Out[ ]:

'Blub'

In [ ]:

# What happen when we want to print the nemo instance?


print(nemo)

<__main__.ClownFish object at 0x7fca565dbf60>

When you write your own special method (like str). You are overriding the method of the same name defined
in object.

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 8/11
18/05/2021 module4_python

In [ ]:

# The print statement is not easy to understand, so we will override it.

class ClownFish(Fish):
def __init__(self, name):
self.name = name
def __str__(self):
return "A ClownFish named "+self.name

In [ ]:

nemo = ClownFish('Nemo')

print(nemo)

A ClownFish named Nemo

4.3.2: Accessing Variable with Inheritance

In a is-a relationship, the child classe could access the parent class's attributes if not defined in the child
class, or override the attribute value of same attribute exists in the child class.

However, if an instance is defined at one of the parent class levels, then it could NOT access the attributes
that are defined in any of the lower child class level.

In [ ]:

class Fish(Vertebrate):

# self.name is not defined in Fish class, but is defined in the ClownFish class.
def __str__(self):
return "Hello, my name is {}".format(self.name)

class ClownFish(Fish):
def __init__(self, name):
self.name = name

In [ ]:

nemo = ClownFish("nemo")

# The self.name attribute for the __str__() is from the ClownFish class
# but the __str__() is from the Fish class
print(nemo)

Hello, my name is nemo

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 9/11
18/05/2021 module4_python

In [ ]:

"""
ERROR, because if nemo is an instance of fish class,
then it does NOT have the name attribute.
"""
nemo = Fish()
print(nemo)

--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
<ipython-input-33-3dff370cc698> in <module>()
4 """
5 nemo = Fish()
----> 6 print(nemo)

<ipython-input-31-b5476c627494> in __str__(self)
3 # self.name is not defined in Fish class, but is defined in th
e ClownFish class.
4 def __str__(self):
----> 5 return "Hello, my name is {}".format(self.name)
6
7 class ClownFish(Fish):

AttributeError: 'Fish' object has no attribute 'name'

In [ ]:

class Fish(Vertebrate):
def __init__(self, name):
self.name = name

# self.name is not defined in Fish class, but is defined in the ClownFish class.
def __str__(self):
return "Hello, my name is {}".format(self.name)

class ClownFish(Fish):
def __init__(self, name):
self.name = name

In [ ]:

nemo = ClownFish("Nemo")

# __str__() is accessing the self.name from the child level


print(nemo)

Hello, my name is Nemo

In [ ]:

nemo = Fish("clown_fish")

# __str__ ia accessing the self.name attribute from Fish class


print(nemo)

Hello, my name is clown_fish

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 10/11
18/05/2021 module4_python

In [ ]:

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 11/11
18/05/2021 module5_python

Module 5: Uses and Applications of Libraries


Learning Objectives:

1. Apply the Math library to solve computation problems.


2. Apply the Numpy, Scipy, Matplotlib libraries for data analysis and graph generation.
3. Apply the Flask framework for web development and understand the relationship with HTML.

5.1: Math

Common mathematical functions, such as absolute value, exponential, or log, are defined within the Math
library.

Additional functions and spec of the Math Library can be found HERE
(https://docs.python.org/3/library/math.html)

Take below for examples of how to use the Math library.

In [ ]:

import math

# Power function
print("2^5 = " + str(math.pow(2,5)))

2^5 = 32.0

In [ ]:

# Ceiling function
print(math.ceil(3.45))

print(math.ceil(10.01))

4
11

In [ ]:

# Floor function
print(math.floor(5.25))

print(math.floor(11.01))

5
11

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 1/11
18/05/2021 module5_python

In [ ]:

# Absolute Value
print(math.fabs(-10.33))

print(math.fabs(5.25))

10.33
5.25

In [ ]:

# Log with base e, or natural log


print(math.log(1000))

6.907755278982137

In [ ]:

# Log with a specified base of 10


print(math.log(1000,10))

2.9999999999999996

5.2: Data Analysis with Numpy, Matplotlib, Scipy

Numpy is a package for numeric computing in python.

It provides an efficient data structure for numeric, n-dimensional arrays (ndarray)


Supports vector and matrix operations.
Numpy is implemented in C, so it is really fast and efficient.

The basic data type in numpy is the numpy n-dimensional array. These can be used to represent vectors
(1D) matrices (2D) or tensors (nD).

1 dimensions numpy arrays are often used to represent a series of data.


n-dimensional arrays often represent complete data sets (each column is a type of measurement).

Numpy arrays are very similar to Python lists. Indexing and slicing works the same way
(including assingments). However, all cells in the same array must contain the same data
type.

Operators don't work the same for lists and arrays and there are many additional methods defined on them.

Referenced from Columbia University CS Professor Daniel Bauer ENGI1006 Lecture

In [ ]:

# Let's see what happen if we use a list to represent a vector?


[1,2,3] * 3

Out[ ]:

[1, 2, 3, 1, 2, 3, 1, 2, 3]

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 2/11
18/05/2021 module5_python

In [ ]:

# Previous was NOT the expected output with vector multiplication by a scalar

# Need to do this
[i*3 for i in [1,2,3]]

Out[ ]:

[3, 6, 9]

In [ ]:

# What about summing two vectors?

# Treated as list concatenation


[1,2,3]+[4,5,6]

Out[ ]:

[1, 2, 3, 4, 5, 6]

In [ ]:

# Sum two vectors


a = [1,2,3]
b = [4,5,6]
[a[i] + b[i] for i in range(len(a))]

Out[ ]:

[5, 7, 9]

In [ ]:

# cross product or dot product?


[1,2,3] * [4,5,6]

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
<ipython-input-6-a661702feff9> in <module>()
1 # cross product or dot product?
----> 2 [1,2,3] * [4,5,6]

TypeError: can't multiply sequence by non-int of type 'list'

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 3/11
18/05/2021 module5_python

In [ ]:

# We could compute the dot product like this:

u = [1,2,3]
v = [4,5,6]

total = 0
for i in range(len(u)):
total += u[i] * v[i]
total

Out[ ]:

32

In [ ]:

# Let's see what happens if we use Numpy

# np is a common convention to refer to numpy throughout the code


import numpy as np
u = np.array([1,2,3])
v = np.array([4,5,6])

# dot() calculates the dot product of two vectors


np.dot(u,v)

Out[ ]:

32

In [ ]:

type(u)

Out[ ]:

numpy.ndarray

In [ ]:

print(u)

[1 2 3]

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 4/11
18/05/2021 module5_python

In [ ]:

# Some more operations on 1D-arrays:

import numpy as np
u = np.array([1,2,3])
v = np.array([4,5,6])

print("Vector addition with another vector ---> " + str(u+v))


print("Vector addition with a scalar ---> " + str(u+4))
print("Vector multiplication by a scalar ---> " + str(u * 4))
print("Vector multiplication (NOT dot nor cross product) ---> " + str(u * v))
print("Vector sum ---> " + str(np.sum(u * v)))
print("Dot product ---> " + str(np.dot(u,v)))

Vector addition with another vector ---> [5 7 9]


Vector addition with a scalar ---> [5 6 7]
Vector multiplication by a scalar ---> [ 4 8 12]
Vector multiplication (NOT dot nor cross product) ---> [ 4 10 18]
Vector sum ---> 32
Dot product ---> 32

In [ ]:

"""
Let's look at multi-dimensional arrays: 'arrays within arrays'

The following code creates a total of three 3*3 matrices with all ones
"""
u = np.ones((3,3,3))
u

Out[ ]:

array([[[1., 1., 1.],


[1., 1., 1.],
[1., 1., 1.]],

[[1., 1., 1.],


[1., 1., 1.],
[1., 1., 1.]],

[[1., 1., 1.],


[1., 1., 1.],
[1., 1., 1.]]])

In [ ]:

# Return the shape/dimension of array


u.shape

Out[ ]:

(3, 3, 3)

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 5/11
18/05/2021 module5_python

In [ ]:

np.ones((2,3))

Out[ ]:

array([[1., 1., 1.],


[1., 1., 1.]])

In [ ]:

np.ones((3, 2))

Out[ ]:

array([[1., 1.],
[1., 1.],
[1., 1.]])

Scipy is a package to analyze the curve fit.

Matplotlib is a package for graphing data.

See the follow for an example of how scipy, numpy, and matplotlib could be used together in data analysis.

Documentations for Scipy, Matplotlib, and Numpy can be access HERE (https://www.scipy.org/docs.html)

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 6/11
18/05/2021 module5_python

In [ ]:

# import different packages used for data analysis


# .. "as opt" means that the programmer could use the shorthand of "opt" to refer to th
is library, instead of typing the entire name
import scipy.optimize as opt
import numpy as np
import matplotlib.pyplot as plt

# Raw data manually entered by user


I =[4.0, 3.5, 3.0, 2.5, 2.0]
B =[1.31, 1.14, 0.97 ,0.81, 0.76]
IError = [0.2, 0.2, 0.2, 0.2, 0.2]
BError = [0.03, 0.02, 0.04, 0.02, 0.05]

print("estimated B for each error \n")


for i in range (5) :
print(str(I[i]) + "+-" + str(IError[i]) + ": " + str(B[i]) + "+-" + str(BError[i]))

# Apply Numpy library to format the list of raw data into a multi-dimensional matrix
# This is necessary for function optimization and in order to properly use the Scipy pa
ckage
xdata = np.array(I)
ydata = np.array(B)
xerror = np.array(IError)
yerror= np.array(BError)

# Define linear function for fitting,


def func(h, m, b):
return m*h + b

# w gives the estimated parameter for m and b, stored in the square matrix of w and u
# the missing _ return info about variance and covariance

# w is a matrix with information about the value of slope and y-intercept


w, u = opt.curve_fit(func, xdata, ydata)

# Apply x coordinates and optimized result about curve fit to find the "Line of the Bes
t Fit"
yfit = func(xdata,*w)

# Use Matplotlib package to graph data


# 1. Graph the error bars for each x-value
# 2. Graph the "Line of the Best Fit"

# Note: there are options to customize the look of your graph with different parameters
plt.errorbar(I, B, xerr=IError, yerr = BError, fmt='o', ms = 3)
plt.plot(xdata,yfit,label="Fit", linewidth=1.5, linestyle='dashed')

# Add title and labels to the graph


plt.title('I vs. B of the Electromagnet')
plt.xlabel('Electromagnet Current I (A)')
plt.ylabel('Magnetic Field B (T)')

print("\n Estimated parameters of m and b: ", w)


print("\n Estimated variance of m & b: ", np.sqrt(np.diag(u)))

# If necessary, this is how you could save the graph to your local machine.
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 7/11
18/05/2021 module5_python

# But here we do NOT need to save the graph, so we will comment out this line.

# Specify the image name as the parameter


### plt.savefig('IvsB.jpg')

# Note: if you are showing and storing the graph, make sure you SAVE before SHOW.
plt.show()

estimated B for each error

4.0+-0.2: 1.31+-0.03
3.5+-0.2: 1.14+-0.02
3.0+-0.2: 0.97+-0.04
2.5+-0.2: 0.81+-0.02
2.0+-0.2: 0.76+-0.05

Estimated parameters of m and b: [0.286 0.14 ]

Estimated variance of m & b: [0.02778489 0.08563877]

5.3: Web Development with Flask

Flask is a Python framework for building a web application.

Watch this Intro to Flask (https://www.youtube.com/watch?v=mqhxxeeTbu0&list=PLzMcBGfZo4-


n4vJJybUVV3Un_NFS5EOgX) video for How-To build a basic website with Flask.

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 8/11
18/05/2021 module5_python

In [ ]:

"""
app.route defines the URL and what function to run for each URL.

When only '/' is specified in the URL, it is assumed to be the home page.
This web application will serve the text '<h1>WELCOME to My Home Page</h1>'
in header 1 style.

When the URL contains a name in the URL, the name from the URL is parsed to be used
in the function that serves the web page. This is known as a "dynamic webpage."

When admin is specific in the URL, the admin() will run to


redirects the page to show the home page.

Refer to the images below for a view of how each page.


"""

# Import packages
from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route("/")
def home():
return "<h1>WELCOME to My Home Page</h1>"

@app.route("/<name>")
def user(name):
return f"<h3>Hello, nice to meet you {name}!</h3>"

@app.route("/admin")
def admin():
return redirect(url_for("home"))

if __name__ == "__main__":
app.run()

* Serving Flask app "__main__" (lazy loading)


* Environment: production
WARNING: This is a development server. Do not use it in a production de
ployment.
Use a production WSGI server instead.
* Debug mode: off

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Home page view

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 9/11
18/05/2021 module5_python

Dynamic page view with the name "Mary" in the URL

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 10/11
18/05/2021 module5_python

Admin page view is the SAME as the home page, because the admin page is redirected to the home page.

In [ ]:

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 11/11

You might also like