Python_enap
Python_enap
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
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 [ ]:
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 [ ]:
height
--------------------------------------------------------------------------
-
NameError Traceback (most recent call las
t)
<ipython-input-6-d56756f3e5e3> in <module>()
2 # ERROR CODE: "height" is not defined.
3
----> 4 height
In [ ]:
Height
Out[ ]:
In [ ]:
global = 1
global
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 2/12
18/05/2021 module1_python
In [ ]:
# storing a string
helloMessage = "Hello World!"
first_name = "John"
# storing a char
character_example = 'a'
# storing a float
_newFloat = 1.0
In [ ]:
helloMessage
Out[ ]:
'Hello World!'
In [ ]:
character_example
Out[ ]:
'a'
In [ ]:
_newFloat
Out[ ]:
1.0
In [ ]:
bool_Condition
Out[ ]:
True
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 3/12
18/05/2021 module1_python
In [ ]:
Out[ ]:
int
In [ ]:
type(helloMessage)
Out[ ]:
str
In [ ]:
type(bool_Condition)
Out[ ]:
bool
In [ ]:
type(width_float)
Out[ ]:
float
In [ ]:
type(width_int)
Out[ ]:
int
In [ ]:
Out[ ]:
str
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 4/12
18/05/2021 module1_python
In [ ]:
Out[ ]:
int
1.2: Operators
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 5/12
18/05/2021 module1_python
In [ ]:
# Addition
print(5+23)
# Subtraction
print(100-25)
# Multiplication
print(5*10)
# Power/Exponent
# ** operator is equivalent to exponent
print(5**2)
# 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)
28
75
50
25
25
9.0
3.3333333333333335
3
3
1
In [ ]:
foofoofoofoofoo
xxx
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 6/12
18/05/2021 module1_python
In [ ]:
--------------------------------------------------------------------------
-
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)
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)
In [ ]:
# Fix
print("hello " + str(5))
hello 5
In [ ]:
hello world
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo01_html01.html 7/12
18/05/2021 module1_python
In [ ]:
# Equality ==
# Note: MUST be Double equal signs, single equal sign is assignment
print(5 == 5.0)
True
True
True
True
True
False
True
True
False
In [ ]:
# Comparators on Strings
print("hello" == "hello")
True
False
False
True
True
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:
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")
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):
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 [ ]:
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
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
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.
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.
9
9
9
9
9
9
9
9
In [ ]:
"""
The third parameter in range() defines the number of steps to increment the counter.
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.
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.
"""
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.
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)
0
1
2
3
4
5
6
7
8
9
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: ")
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)
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.
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 [ ]:
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.
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.
"""
# 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
# 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
if __name__ == "__main__":
main()
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.
# 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()
# Check if the string is the same in reversed order as the original order
if str == str[::-1]:
return True
else:
return False
if (isPalindrome(userSentence)):
print(userSentence + " is a palindrome!")
else:
print(userSentence + " is NOT a palindrome!")
if __name__ == "__main__":
main()
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo02_html01.html 9/12
18/05/2021 module2_python
In [ ]:
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()
In [ ]:
"""
Above we worked through an example that test whether a sentence is a palindrome.
Now it's your turn.
def isPalindrome(str):
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 [ ]:
def isPalindrome(str):
str = str.lower()
if (str == str[::-1]):
return True
else:
return False
if (isPalindrome(userInput)):
print(userInput + " is a palindrome!")
else:
print(userInput + " is NOT a palindrome!")
if __name__ == "__main__":
main()
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
1. Recognize the key characteristics of each structure. Correctly utilize each structure when appropriate
and access the corresponding data stored on the structure.
3.1: List
List: a mutable data structure that stores elements in an unordered format, like an array.
In [ ]:
"""
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 [ ]:
In [ ]:
Out[ ]:
'hallo'
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 1/12
18/05/2021 module3_python
In [ ]:
Out[ ]:
In [ ]:
# Remove an element from the list by specifying the element that you want to remove
list2.remove('hello')
In [ ]:
Out[ ]:
In [ ]:
"""
Another way to remove an element: pop()
pop() allows you to identify the position you
"""
list2.append("hello")
list2.pop()
list2
Out[ ]:
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[ ]:
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.
"""
size of list1 = 0
size of list2 = 4
In [ ]:
Out[ ]:
'bye,hallo,hola,olá'
In [ ]:
lists = []
lists.append([1,2,3])
lists.append(['a','b','c'])
lists
Out[ ]:
In [ ]:
lists[1]
Out[ ]:
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
They support all the operations lists supports, except for those that modify the list.
In [ ]:
In [ ]:
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
<ipython-input-30-89cbd0c10841> in <module>()
1 # ERROR: canot add to a tuple
----> 2 x.append(4)
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 [ ]:
Out[ ]:
(1, 2, 3)
In [ ]:
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 [ ]:
Out[ ]:
In [ ]:
# shorthand for
# (a,b,c) = (1,2,3)
a,b,c = 1,2,3
In [ ]:
Out[ ]:
In [ ]:
Out[ ]:
In [ ]:
Out[ ]:
In [ ]:
Out[ ]:
[1, 2, 3, 4]
In [ ]:
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 [ ]:
# "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 [ ]:
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
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 [ ]:
Out[ ]:
set()
In [ ]:
ex1
Out[ ]:
{1, 2}
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 7/12
18/05/2021 module3_python
In [ ]:
Out[ ]:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
In [ ]:
Out[ ]:
In [ ]:
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
In [ ]:
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 [ ]:
list_of_ages
Out[ ]:
[1, 2, 4, 5, 10]
In [ ]:
tuple_of_ages
Out[ ]:
(1, 2, 4, 5, 10)
In [ ]:
{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 [ ]:
In [ ]:
Out[ ]:
10
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 9/12
18/05/2021 module3_python
In [ ]:
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 [ ]:
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 [ ]:
dict
Out[ ]:
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.
# 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
--------------------------------------------------------------------------
-
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]
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[ ]:
In [ ]:
Out[ ]:
In [ ]:
# Or all values
dict.values()
Out[ ]:
In [ ]:
Out[ ]:
In [ ]:
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 12/12
18/05/2021 module4_python
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.
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.
In [ ]:
In [ ]:
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 [ ]:
Out[ ]:
True
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 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.
"""
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.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
In [ ]:
class LibraryBook(object):
"""
A library book.
"""
"""
Methods for LibraryBook
"""
# 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 [ ]:
Out[ ]:
<__main__.LibraryBook at 0x7fca565db278>
In [ ]:
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo04_html01.html 4/11
18/05/2021 module4_python
In [ ]:
new_book.title_and_author()
Out[ ]:
4.3: Inheritance
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.
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 [ ]:
Out[ ]:
True
In [ ]:
Out[ ]:
True
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()
Out[ ]:
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 [ ]:
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 [ ]:
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)
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)
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):
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")
In [ ]:
nemo = Fish("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
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)
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 [ ]:
6.907755278982137
In [ ]:
2.9999999999999996
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).
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.
In [ ]:
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 [ ]:
Out[ ]:
[1, 2, 3, 4, 5, 6]
In [ ]:
Out[ ]:
[5, 7, 9]
In [ ]:
--------------------------------------------------------------------------
-
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]
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 3/11
18/05/2021 module5_python
In [ ]:
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 [ ]:
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 [ ]:
import numpy as np
u = np.array([1,2,3])
v = np.array([4,5,6])
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[ ]:
In [ ]:
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[ ]:
In [ ]:
np.ones((3, 2))
Out[ ]:
array([[1., 1.],
[1., 1.],
[1., 1.]])
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 [ ]:
# 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)
# 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
# Apply x coordinates and optimized result about curve fit to find the "Line of the Bes
t Fit"
yfit = func(xdata,*w)
# 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')
# 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.
# Note: if you are showing and storing the graph, make sure you SAVE before SHOW.
plt.show()
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
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."
# 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()
https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo05_html01.html 9/11
18/05/2021 module5_python
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