Professional Documents
Culture Documents
Python
Python
Chapter 4
© 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
© 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
© 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
© 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!")
© 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)
© 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)
© 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
© 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.
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.
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
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
© 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.
© 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()
© 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
© 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
print(strangeFunction(2))
print(strangeFunction(1))
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Effects and results: lists and functions
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
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")
© 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)
def myFunction():
print("Do I know variable var? ", var)
var = 1
myFunction()
print(var)
© 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)
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)
© 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
print(imc(52.5, 1.65))
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Compacting the code
print(esUnTriangulo(1, 1, 1))
print(esUnTriangulo(1, 1, 3))
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Compacting the code
print(esUnTriangulo(1, 1, 1))
print(esUnTriangulo(1, 1, 3))
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Compacting the code
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))
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.
© 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']
print(dict.keys())
dict_keys(['dog', 'horse', 'cat'])
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'])
© 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)
© 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)
© 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)
dict.popitem()
print(dict) # outputs: {'cat' : 'chat', 'dog' : 'chien'}
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Public
Lab
{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
© 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
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