Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 78

Python Essentials

Chapter 4

Jonathan Aguilar Pascoe


America Digital
20 mayo 2020
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
• Functions
• Parametrized functions
• Returning a result from a function
• The none value
• Functions and list
• Functions and scopes
• Tuples
• Dictionaries

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
4.1 Functions

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
What is a function
• A function is a block of code that performs a specific task when the
function is called (invoked).
• You can use functions to make your code reusable, better organized,
and more readable.
• Functions can have parameters and return values.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Types of functions
There are at least four basic types of functions in Python:
1. Built-in functions which are an integral part of Python (such as the
print() function). You can see a complete list of Python built-in
functions at https://docs.python.org/3/library/functions.html
2. The ones that come from pre-installed modules (you'll learn about
them in Module 5 of this course)
3. User-defined functions which are written by users for users
4. The lambda functions

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to create a Function
• It always starts with the keyword def (for define)
• Next after def goes the name of the function (the rules for naming
functions are exactly the same as for naming variables)
• After the function name, there's a place for a pair of parentheses
• The line has to be ended with a colon;
• The line directly after def begins the function body - a couple (at
least one) of necessarily nested instructions, which will be executed
every time the function is invoked; note: the function ends where the
nesting ends, so you have to be careful.
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Basic function

print("Enter a value: ") def message():


a = int(input()) print("Enter a value: ")

print("Enter a value: ") message()


b = int(input()) a = int(input())
message()
print("Enter a value: ") b = int(input())
c = int(input()) message()
c = int(input())

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How functions work

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How functions work

There are two, very important, catches.


• You mustn't invoke a function which is not known at the
moment of invocation.
• You mustn't have a function and a variable of the same
name.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
La función input() es un ejemplo de:
a) una función definida por el usuario
b) una función integrada

R: b) Es una función integrada

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
¿Qué es lo que ocurre cuando se invoca una función antes de ser
definida? Ejemplo:
hola()

def hola():
print("hola!")

Se genera una excepción (la excepción NameError)

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
¿Qué es lo que ocurrirá cuando se ejecute el siguiente código?
def hola():
print("hola")

hola(5)

Se genera una excepción (la excepción TypeError) - la función


hola() no toma argumentos.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
4.2 Parametrized Functions

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Parametrized functions
A parameter is actually a variable, but there are two important factors
that make parameters different and special:
• Parameters exist only inside functions in which they have been
defined, and the only place where the parameter can be defined is a
space between a pair of parentheses in the def statement;
• Assigning a value to the parameter is done at the time of the
function's invocation, by specifying the corresponding argument.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Parametrized functions

def message(number):
print(number)

• The definition specifies that our function operates on just one


parameter named number.
• You can use it as an ordinary variable, but only inside the function - it
isn't visible anywhere else.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Parametrized functions: continued

Parameter
def message(number):
print("Enter a number:", number)

message(1)
Argument

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Parametrized functions: continued

def message(number):
print("Enter a number:", number)

number = 1234
message(1)
print(number)

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Parametrized functions: two parameters

def message(what, number):


print("Enter", what, "number", number)

message("telephone", 11) Enter telephone number 11


message("price", 5) Enter price number 5
message("number", "number") Enter number number number

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Positional Parameter passing
A technique which assigns the ith (first, second, and so on) argument to
the ith (first, second, and so on) function parameter is called positional
parameter passing, while arguments passed in this way are named
positional arguments.

def myFunction(a, b, c):


print(a, b, c)

myFunction(1, 2, 3)

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Keyword argument passing
Python offers another convention for passing arguments, where the
meaning of the argument is dictated by its name, not by its position
- it's called keyword argument passing.

def introduction(firstName, lastName):


print("Hello, my name is", firstName, lastName)

introduction(firstName = "James", lastName = "Bond")


introduction(lastName = "Skywalker", firstName = "Luke")

You can’t use a non-existent parameter name


© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Mixing positional and keyword arguments

def sum(a, b, c):


print(a, "+", b, "+", c, "=", a + b + c)

sum(1, 2, 3)
sum(c = 1, a = 2, b = 3)
sum(3, c = 1, b = 2)
sum(3, a = 1, b = 2)
sum(4, 3, c = 2)

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Parametrized functions: default (predefined) values

def introduction(firstName, lastName="Smith"):


print("Hello, my name is", firstName, lastName)

introduction("John", "Doe")
introduction("John")

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
4.3 Returning a result

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Effects and results: the return instruction

To get functions to return a value you use the return


instruction.
The return instruction has two different variants:
• return without an expression
• return with an expression

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
return without an expression
When used inside a function, it causes the immediate termination of
the function's execution, and an instant return (hence the name)
to the point of invocation.

Note: if a function is not intended to produce a result, using the


return instruction is not obligatory - it will be executed implicitly at
the end of the function.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
return without an expression
def happyNewYear(wishes = True):
print("Three...")
print("Two...")
print("One...")
if not wishes:
return
print("Happy New Year!")

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
return with an expression
The second return variant is extended with an expression:
function():
return expression
There are two consequences of using it:
1. It causes the immediate termination of the function's execution
2. The function will evaluate the expression's value and will return
(hence the name once again) it as the function's result.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
return with an expression
def boringFunction():
return 123

x = boringFunction()

print("The boringFunction has returned: ", x)

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
return with an expression [Ignore function result]
def boringFunction():
print("'Boredom Mode' ON.")
return 123

print("This lesson is interesting!")


boringFunction()
print("This lesson is boring...")

This lesson is interesting!


'Boredom Mode' ON.
This lesson is boring...
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
return with an expression

• You are always allowed to ignore the function's result,


and be satisfied with the function's effect (if the function
has any)
• If a function is intended to return a useful result, it must
contain the second variant of the return instruction.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
None is a keyword
Its data doesn't represent any reasonable value - actually,
it's not a value at all; hence, it mustn't take part in any
expressions.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
The none value
There are only two kinds of circumstances when None can be safely
used:
• When you assign it to a variable (or return it as a function's result)
• When you compare it with a variable to diagnose its internal state.

value = None
if value == None:
print("Sorry, you don't carry any value")

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
The none value

If a function doesn't return a certain value using a return


expression clause, it is assumed that it implicitly returns
None.
def strangeFunction(n):
if(n % 2 == 0):
return True

print(strangeFunction(2))
print(strangeFunction(1))

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Effects and results: lists and functions

We can sent a list to a function as an argument


def sumOfList(lst):
sum = 0
for elem in lst:
sum += elem
return sum

print(sumOfList([5, 4, 3])) 12
print(sumOfList(5)) TypeError: 'int' object
is not iterable
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Effects and results: lists and functions

We can receive a list as a function result


def strangeListFunction(n):
strangeList = []
for i in range(0, n):
strangeList.insert(0, i)
return strangeList

print(strangeListFunction(5)) [4, 3, 2, 1, 0]

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
4.1.3.6: Lab. Leap Year: Write your own functions
def isYearLeap(year): testData = [1900, 2000, 2016, 1987]
testResults = [False, True, True,
# False]
# coloca tu código for i in range(len(testData)):
aquí yr = testData[i]
print(yr,"->",end="")
# result = isYearLeap(yr)
if result == testResults[i]:
print("OK")
else:
print("Error")

Prerequisite: Lab 3.1.1.13

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
• ¿Cuál es la salida del siguiente fragmento de código?
def hola():
return
print("¡Hola!")
hola()

None

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
def isInt(data):
if type(data) == int:
True
return True
False
elif type(data) == float: None
return False

print(isInt(5))
print(isInt(5.0))
print(isInt("5"))

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
def evenNumLst(ran):
lst = []
[0, 2, 4, 6, 8, 10]
for num in range(ran):
if num % 2 == 0:
lst.append(num)
return lst

print(evenNumLst(11))

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
4.4 Scopes in Python

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Functions and scopes

def scopeTest():
x = 123

scopeTest()
print(x)

Traceback (most recent call last):


File ".main.py", line 4, in <module>
print(x)
NameError: name 'x' is not defined
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Functions and scopes

def myFunction():
print("Do I know variable var? ", var)

var = 1
myFunction()
print(var)

Let’s see a demo on Python

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Functions and scopes: the global keyword

def myFunction():
global var
var = 2
print("Do I know var variable?", var)

var = 1
myFunction()
print(var)

Do I know var variable? 2


2
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How the function interacts with its arguments

def myFunction(myList1):
print(myList1)
myList1 = [0, 1]

myList2 = [2, 3]
myFunction(myList2) [2, 3]
print(myList2) [2, 3]

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How the function interacts with its arguments

def myFunction(myList1):
print(myList1)
myList1.append(7)

myList2 = [2, 3]
myFunction(myList2) [2, 3]
print(myList2) [2, 3, 7]

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
• ¿Qué ocurrirá cuando se intente ejecutar el siguiente código?
def message():
alt = 1
print("Hola, mundo!")

print(alt)

NameError(NameError: name 'alt' is not defined)

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
a = 1 2
1
def fun():
a = 2
print(a)

fun()
print(a)

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
a = 1
2
2
def fun():
global a
a = 2
print(a)

a = 3
fun()
print(a)
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
5. Funciones con dos
parámetros

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Funciones Simples

def imc(peso, altura):


return peso / altura ** 2

print(imc(52.5, 1.65))

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Compacting the code

def esUnTriangulo (a, b, c):


if a + b <= c:
return False
if b + c <= a:
return False
if c + a <= b:
return False
return True

print(esUnTriangulo(1, 1, 1))
print(esUnTriangulo(1, 1, 3))
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Compacting the code

def esUnTriangulo (a, b, c):


if a + b <= c or b + c <= a or c + a <= b:
return False
return True

print(esUnTriangulo(1, 1, 1))
print(esUnTriangulo(1, 1, 3))

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Compacting the code

def esUnTriangulo (a, b, c):


if a + b > c and b + c > a and c + a > b:
return True

print(esUnTriangulo(1, 1, 1))
print(esUnTriangulo(1, 1, 3))

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Recursion
• Recursion is a technique where a function invokes itself

def countdown(n):
if n == 0:
return
print(n)
countdown(n-1)

countdown(4)

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Recursion : factorial
0! = 1 def factorialFun(n):
if n < 0:
1! = 1
return None
2! = 1 * 2 if n < 2:
return 1
3! = 1 * 2 * 3
return n * factorialFun(n - 1)
4! = 1 * 2 * 3 * 4

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
¿Qué ocurrirá al intentar ejecutar el siguiente fragmento de código y
porque?

def factorial(n):
return n * factorial(n - 1)

print(factorial(4))

RecursionError: maximum recursion depth exceeded


© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Quiz
¿Cuál es la salida del siguiente fragmento de código?
def fun(a):
if a > 30:
return 3 56
else:
return a + fun(a + 3)

print(fun(25))
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
4.6 Tuples

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Sequence types and mutability
• A sequence type - is a type of data in Python which is able to store
more than one value (or less than one, as a sequence may be
empty), and these values can be sequentially (hence the name)
browsed, element by element.
• Mutability - is a property of any of Python's data that describes its
readiness to be freely changed during program execution. There are
two kinds of Python data: mutable and immutable.
• Mutable data can be freely updated at any time – in situ
list.append(1)
• Immutable data cannot be modified in this way

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Tuples
A tuple is an immutable sequence type. It can behave like a list, but it
can't be modified in situ.
Tuples use parenthesis, whereas lists like to see brackets, although it's
also possible to create a tuple just from a set of values separated by
commas.

tuple1 = (1, 2, 4, 8) emptyTuple = ()


tuple2 = 1., .5, .25, .125
oneElementTuple1 = (1, )
oneElementTuple2 = 1.,
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Tuples: examples
myTuple = (1, 10, 100, 1000) myTuple.append(10000)
del myTuple[0]
print(myTuple[0]) 1 myTuple[1] = -10
print(myTuple[-1]) 1000
print(myTuple[1:]) (10, 100, 1000)
print(myTuple[:-1]) (1, 10, 100)
print(myTuple[:3])

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to use a tuple
myTuple = (1, 10, 100)
myTuple = myTuple + (1000, 10000)
myTuple.append(1000)
t2 = myTuple * 3

print(len(t2)) 9
print(t1) (1, 10, 100, 1000, 10000)
print(t2) (1, 10, 100, 1, 10, 100, 1, 10, 100)
print(10 in myTuple) True
print(-10 not in myTuple) True

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
4.6 Dictionaries

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
What is a dictionary?
The dictionary is another Python data structure. It's not a sequence type (but can
be easily adapted to sequence processing) and it is mutable.
A dictionary is a set of key-value pairs. Note:
• each key must be unique - it's not possible to have more than one key of the same value;
• a key may be data of any type: it may be a number (integer or float), or even a string;
• a dictionary is not a list - a list contains a set of numbered values, while a dictionary holds
pairs of values;
• the len() function works for dictionaries, too - it returns the numbers of key-value elements
in the dictionary;
• a dictionary is a one-way tool - if you have an English-French dictionary, you can look for
French equivalents of English terms, but not vice versa.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to make a dictionary?
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}
phoneNumbers = {'boss' : 5551234567, 'Suzy' : 22657854310}
emptyDictionary = {}

Dictionaries are not lists - they don't preserve the order of their data, as the order is
completely meaningless. The order in which a dictionary stores its data is completely
out of your control, and your expectations.

NOTE
In Python 3.6x dictionaries have become ordered collections by default. Your results may
vary depending on what Python version you're using.

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to use a dictionary?
If you want to get any of the values, you have to deliver a valid key value:
• print(dict['cat'])
• print(phoneNumbers['Suzy'])
Getting a dictionary's value resembles indexing, especially thanks to the
brackets surrounding the key's value.
Note:
• if the key is a string, you have to specify it as a string;
• keys are case-sensitive: 'Suzy' is something different from 'suzy'.
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to use a dictionary?
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}
words = ['cat', 'lion', 'horse']

for word in words:


if word in dict:
print(word, "->", dict[word])
else:
print(word, "is not in dictionary")

cat -> chat


lion is not in dictionary
horse -> cheval
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to use a dictionary: the keys()
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}

print(dict.keys())
dict_keys(['dog', 'horse', 'cat'])

for key in dict.keys():


print(key, "->", dict[key])
horse -> cheval
dog -> chien
cat -> chat
print(sorted(dict.keys()))
['cat', 'dog', 'horse']
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to use a dictionary: the items() method
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}

print(dict.items())
dict_items([('cat', 'chat'), ('dog', 'chien'), ('horse', 'cheval')])

print(dict)
{'cat': 'chat', 'horse': 'cheval', 'dog': 'chien'}
for english, french in dict.items():
print(english, "->", french) cat -> chat
dog -> chien
horse -> cheval

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to use a dictionary: values() method
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}

print(dict.values())
dict_values(['chat','chien', 'cheval'])

for french in dict.values():


print(french)
chat
chien
cheval

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to use a dictionary: modifying values
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}

dict['cat'] = 'minou'
print(dict)

{'cat': 'minou', 'dog': 'chien', 'horse': 'cheval'}

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to use a dictionary: adding new values
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}

dict['swan'] = 'cygne'
print(dict)

{'cat': 'minou', 'dog': 'chien', 'horse': 'cheval',


'swan': 'cygne', }

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
How to use a dictionary: removing values
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}
del dict['dog']
print(dict)

{'cat': 'minou', 'horse': 'cheval'}

dict.popitem()
print(dict) # outputs: {'cat' : 'chat', 'dog' : 'chien'}

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Lab

Escribe un código para crear un diccionario en donde las llaves son


números entre 1 y 15 (ambos incluidos) y que los valores sean el
cuadrado de la llave

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121,
12: 144, 13: 169, 14: 196, 15: 225}

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Lab

Escriba un código que combine dos diccionarios sumando los


valores de llaves repetidas
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}

{'a': 400, 'b': 400, 'd': 400, 'c': 300}

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Recaudado: 0
Pendiente de cobro: 0

Lab ¿Quieres añadir una nueva factura (A), pagarla (P) o terminar (T)? A
Introduce el número de la factura: 1
Introduce el coste de la factura: 150

Recaudado: 0
Pendiente de cobro: 150.0
Escribir un programa que gestione las facturas
¿Quieres añadir una nueva factura (A), pagarla (P) o terminar (T)? A
pendientes de cobro de una empresa. Las facturas Introduce el número de la factura: 2
Introduce el coste de la factura: 300
se almacenarán en un diccionario donde la clave de
cada factura será el número de factura y el valor el Recaudado: 0
Pendiente de cobro: 450.0
coste de la factura. El programa debe preguntar al ¿Quieres añadir una nueva factura (A), pagarla (P) o terminar (T)? P
usuario si quiere añadir una nueva factura, pagar Introduce el número de la factura a pagar: 2

una existente o terminar. Si desea añadir una nueva Recaudado: 300.0


Pendiente de cobro: 150.0
factura se preguntará por el número de factura y su ¿Quieres añadir una nueva factura (A), pagarla (P) o terminar (T)? A
coste y se añadirá al diccionario. Si se desea pagar Introduce el número de la factura: 3
Introduce el coste de la factura: 85
una factura se preguntará por el número de factura
Recaudado: 300.0
y se eliminará del diccionario. Después de cada Pendiente de cobro: 235.0

operación el programa debe mostrar por pantalla la ¿Quieres añadir una nueva factura (A), pagarla (P) o terminar (T)? P
Introduce el número de la factura a pagar: 1
cantidad cobrada hasta el momento y la cantidad
pendiente de cobro. Recaudado: 450.0
Pendiente de cobro: 85.0

¿Quieres añadir una nueva factura (A), pagarla (P) o terminar (T)? T
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
• La casa es roja
• La manzana esta rica
• El perro esta bonito
• Mi mama me ama mucho

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public

You might also like