Está en la página 1de 92

Escuela de

finanzas OPEN ONLINE AFI. PYTHON.

Programación
con Python

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

• Dentro del tema encontrarás los epígrafes de contenido, con subepígrafes para una mejor
comprensión.
• Todos los temas han sido elaborados siguiendo el criterio de facilidad de exposición.
• Los contenidos incluyen, en este sentido, cinco tipo de llamadas de atención que agilizan y
facilitan la comprensión de los mismos:

Ejemplo Tenga en cuenta Recuerde Definición Ley


que….

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

1 History
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, notebooks) 13. Common operators
5. Running Pythonprograms 14. if,elif, else conditional
6. Identifiers and reservedworks statements
7. Indentation andmulti-line statements 15. Loops: for, while, break,continue
8. Variables andtypes 16. Functions
9. Strings

- 4

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
OPEN ONLINE AFI. PYTHON.
finanzas
History

This notes are mostly based on the following books:


• “Official Python tutorial”, Guido vanRossum
• “Python for Data Analysis”, WesMcKinney

- 5

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
OPEN ONLINE AFI. PYTHON.
finanzas
History

• Python official website:https://www.python.org/


• Python was created by Guido van Rossum at the National
Research Institute for Mathematics and Computer Science in
theNetherlands
• Python is maintained by a core development team at the institute
• The “Python” name comes from the Monty Python group
• Python is derived from many other languages, including
ABC, C,…
• Python is copyrighted and open-source; code is now
available under the GNU General Public License (GPL).
• Python 1.0 was released in November 1994.
• Python 3.0 was released in2008.
• Last version (mar'17) Python3.6.1

6
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

2 Characteristics
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 8

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Characteristics OPEN ONLINE AFI. PYTHON.

1. Interpreted
– No need to compile programs before running them
2. Interactive
– Get direct answer to your Python instructions
3. Objectoriented
4. Open-source
5. Alive
– Large community ofdevelopers
6. Portable
– “*.py” files run in any computer with Python installed
7. Powerful (manylibraries/modules)
– Maths,communications, web development, machine learning, databases, GUI, ..
8. Easy to learn and use (read, develop, maintain, ...)

- 9

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Characteristics OPEN ONLINE AFI. PYTHON.

Pros:
• It is common to do research, prototype, and test new ideas using domain- specific computing
language like MATLAB or R. Then later port those ideas to be part of a larger production system
written in,say, Java,C#,or C++.
• Python is increasingly being use for creating production tools and not only for prototyping; with the
huge benefit of having both scientists and technologists using the same set of programmatic tools
• Open-source, many modules,…
Cons:
• Slower than compiled languages (Java, C++, etc.)
• It is not an ideal language for concurrent, multithreaded applications

- 10

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

3 Installation
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 12

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas InstallingPython OPEN ONLINE AFI. PYTHON.

 Official site
 https://www.python.org/downloads/
 This Includes Python and the base modules and the IDLE environment for programming

 Anaconda distribution
 https://www.anaconda.com/distribution/
 Includes Python, IPython, the most important/used modules, the Spyder IDE, and Jupyter
notebook

 Many others
 Enthought Python Distribution:(http://www.enthought.com)
 Python(x,y) (http://pythonxy.googlecode.com)
 JetBrains PyCharm (https://www.jetbrains.com/pycharm/)

We will be using Python Anaconda distribution

- 13

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas InstallingPython OPEN ONLINE AFI. PYTHON.

Installing Anaconda
Installing Anaconda is straightforward: download it here: https://www.anaconda.com/distribution/
and follow the instructions

Important points:

• Install the latest version

• If you are asked during the installation process whether you’d like to make Anaconda your default
Python installation, say yes

• Otherwise you can accept all of the defaults

Updating Anaconda

Anaconda supplies a tool called conda to manage and upgrade your Anaconda packages

One conda command you should execute regularly is the one that updates the whole Anaconda
distribution.

As a practice run, please execute the following

• Open up a terminal
Vídeo:
Instalación
• Type “conda update anaconda”
Python
- 14

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

Working with Python


4 (IDEs, notebooks)
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 16

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

Working withPython

There are several environments to work with Python. Some of the most well known are (once you have
Anaconda installed):
• Python:
– Shell /terminal /cmd. Type “python” in a terminalwindow
– IDLE: Type “idle” on a terminal window
• IPython:
– Shell /terminal /cmd. Type “ipython” in a terminalwindow
• Notebooks (Jupyter).
– Type “Jupyter notebook” on a terminal widow. Jupyter will apear in your web browser
• Spyder IDE:
– Type Spyder in a terminal window or click on the Spyder icon(inside Anaconda set of
applications)

17

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas IPython OPEN ONLINE AFI. PYTHON.

• The IPython project began in 2001 as Fernando Pérez's side project to


make a better interactive Python interpreter

• The IPython project now encompasses many things: the interactive


Python shell, a rich GUI console with inline plotting, a web-based
interactive notebook format, and a lightweight, fast parallel computing
engine, tab completition, …

• Many IDEs have integration with the IPython terminal

• IPython will, in almost all cases, help you get the job done faster (tab
completition, integrated plots, magic comands, ...

- 18

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Notebooks OPEN ONLINE AFI. PYTHON.

• Notebook-style development provides a more exploratory way to write


code than with traditional IDEs.

• Notebook interfaces are comprised of a series of code blocks, called


cells, which can stand alone or act in unison.

• The development process is one of discovery, where a developer


experiments in one cell, then can continue to write code in a
subsequent cell depending on results from the first. Particularly when
analyzing large datasets, this conversational approach allows
researchers to quickly discover patterns or other artifacts of the data.
• Jupyter notebook was designed to enable sharing of notebooks with
other people. The idea is that you can write some code, mix some text
with the code, and publish this as a notebook. In the notebook they can
see the code as well as the actual results of running the code.

• This is a nice way of sharing little experimental snippets, but also to


publish more detailed reports with explanations and full codesets.

- 19

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
OPEN ONLINE AFI. PYTHON.
finanzas
Working with Python

Python shell

IPython shell

20
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
OPEN ONLINE AFI. PYTHON.
finanzas
Working with Python

Jupyter

Spyder

21
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

Running Python
5 programs
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 23

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

Running Python

There are three different ways to start Python:

1. Interactive Interpreter
Launch Python, IPython and Jupyter; and work with Python in a interactive way

2. Script from theCommand-line


A Python script (*.py file) can be executed at the command; “python file.py”

3. Integrated DevelopmentEnvironment IDLE,


Spyder, Pycharm,...

- 24

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.
Starting Jupyter notebooks

Once you have installed Anaconda, you can start the Jupyter notebook

Either Vídeo:
• search for Jupyter in your applications menu, or Notebook_
• open up a terminal and type jupyter notebook
Jupiter
• In a Windows environment open up a folder and type jupyter notebook and press
Enter like this:

Hopefully your default browser has opened up with a web page that looks something like
this:

Notebook:
Intro to
notebooks
- 25

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

Identifiers and reserved


6 words
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedwords 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 27

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Identifiers and reservedwords OPEN ONLINE AFI. PYTHON.

• A Python identifier is a name used to identify a variable, function, class, module or any other
object.
• An identifier starts witha letterA to Zor a to zor an underscore (_)followed by zeroor more letters,
underscores and digits (0 to 9)
• Python distinguished between lower and capital letters
• The following are reserved words in Python:

and exec Not as finally or


assert for pass break from print
class global raise continue if return
def import try del in while
elif is with else lambda yield
excep Tru Fals
t e e

Example:
Var_number = 10
Myvar_text = ” H i ! ”
My_sum = 1+1 +Var_number

- 28

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

Notebook:
Practicing
Python

More practice:
Notebook Syntax and
basic elements

29
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

Indentation and multi-line


7 statements
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 31

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Indentation OPEN ONLINE AFI. PYTHON.

• Python does not use braces {}or parenthesis ()to indicate blocks of code for class and function
definitions or flow control

• Blocks of code are denoted by line indentation,which is rigidly enforced. The number of spaces in
the indentation is variable, but all statements within the block must be indented the same amount
ofspaces

if Tr u e : if Tr u e :

p r i n t ( 'True’) p r i n t ( 'True')

else: p r i n t ( 'Wrong')

print('False') else:
print('False')

- 32

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Multi-Line Statements OPEN ONLINE AFI. PYTHON.

• Statements in Python typically end with a new line. Python, however, allows the use of the line
continuation character (\) to denote that the line should continue.
To t a l = item_one + \
item_two + \
item_three

• The statements contained within the [],{},or ()brackets do not need to use the line continuationcharacter.
Days = [ 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']

• The semicolon (;)allows multiple statements on a single line given that no statement starts a new
codeblock
import sys; x = 'foo'; s ys . s t d o u t . wr i t e ( x + '\n')

Notebook:
Practicing Python
- 33

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

8 Variables and types


iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 35

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Variables OPEN ONLINE AFI. PYTHON.

• Variables are nothing but reserved memory locations to store values. It means that when you create a
variable, you reserve some space in the memory.

• There is no need to declare the variable type. Based on the data type of a variable, the interpreter
allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning
different data types to the variables, you can store integers, decimals or characters in these variables.

counter = 100 # An i n t e g e r assignment

miles = 1000.0 # A f l o a t i n g point

name = "John" # A s t r i n g

• Multiple assignment
a = b = c = 1
d, e, f = 1, 2, "john“ # multi assignment

36
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas Strings andcomments OPEN ONLINE AFI. PYTHON.

Strings • sentence0 = 'my words'


• Python accepts single ('), double (") and triple (''' or
• sentence1 = " T h i s i s a
""") quotes to denote string literals, as long as the sentence. "
same type of quote starts and endsthe string.
• The triple quotes are used to span the string • paragraph = " " " T h i s i s a paragraph.
across multiplelines I t i s made up o f m u l t i p l e l i n e s
and s e n t e n c e s . " " "

Comments
• A hash sign (#) that is not inside a string literal is the
• # Firstcomment
beginning of a comment.All characters after the #, up
to the end of the physical line, are part of the
• print("Hello, Python!") # secondcomment
comment and the Python interpreter ignores them
• A multiple-line comment is done using 3 double
quotes “””multilinecomments like this oneare done using 3

double quotes”””

37

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Datatypes OPEN ONLINE AFI. PYTHON.

• The data stored in memory can be of many types. For example, a person's age is stored as
a numeric value and his or her address is stored as alphanumeric characters.Python has
various standard data types that are used to define the operations possible on them and
the storage method for each ofthem.
• Python has five standard datatypes:

– Numbers My_Number = 1
– String My_String = “ H e l l o w o r l d ”
My_List = [ 0 , 1 , 2 , 3 , “ a ” ]
– List
My_Tuple = ( “ a ” , 1 , 1 2 . 3 )
– Tuple
My_Dictionary = { " a " : 1 2 , " b " : " 2 3 " , 1=12}
– Dictionary

• Boolean:
– True or False.
– When evaluating expressions, Python programming language assumes any non-
zero and non-null values as True,and any zero or null values as Falsevalue

- 38

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Numbers OPEN ONLINE AFI. PYTHON.

• Number data types store numeric values. Var1 = 1


Number objects arecreated when you assign a
value to them Var2 = 22

• You can also delete the referenceto a number


d e l Var1, Var2
object by using the del statement
• Python supports threedifferent numerical
types:

– int (signedintegers)
– float (floating point realvalues)
– complex (complexnumbers)

- 39

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.
Strings

• Strings in Python are identified as a contiguous set of characters represented in the quotation marks.
Python allows either pair of single or double quotes. Subsets of strings can be taken using the slice
operator ([ ] and [:] )with indexes starting at 0 in the beginning of the string and working their way from -1
to the end
• Strings areimmutable
• The plus (+)sign is the string concatenation operator and the asterisk (*) is the repetition
operator. Forexample:

s t r = 'Hello World!'
p r i n t ( s t r ) # p r i n t s complete s t r i n g
p r i n t ( s t r [ 0 ] ) # p r i n t s f i r s t c h a r ac t er o f t h e s t r i n g p r i n t ( s t r [ 2 : 5 ] ) #
p r i n t s c h a r a c t ers s t a r t i n g from 3rd t o 5 t h p r i n t ( s t r [ 2 : ] ) # p r i n t s s t r i n g
s t a r t i n g from 3rd c h a r ac t er p r i n t ( s t r * 2 ) # p r i n t s s t r i n g two times
p r i n t ( s t r + "TEST") # p r i n t s concatenated s t r i n g

40

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Lists OPEN ONLINE AFI. PYTHON.

• Lists are the most versatile of Python's compound data types.A list contains items separated by
commas and enclosed within square brackets [ ].The items belonging to a list can be of different
data type.
• The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at
0 in the beginning of the list and working their way to end -1. The plus (+)sign is the list concatenation
operator,and the asterisk (*) is the repetition operator. Forexample:
m y l i s t = [ 'abcd', 786 , 2 . 2 3 , ' j ohn' , 70.2 ]
t i n y l i s t = [ 1 2 3 , ' j ohn' ]
p r i n t ( m y l i s t ) # p r i n t s complete l i s t
p r i n t ( m y l i s t [ 0 ] ) # p r i n t s f i r s t element o f t h e l i s t
p r i n t ( m y l i s t [ 1 : 3 ] ) # p r i n t s elements s t a r t i n g from 2nd t i l l 3rd
p r i n t ( m y l i s t [ 2 : ] ) # p r i n t s elements s t a r t i n g from 3rd element
p r i n t ( t i n y l i s t * 2 ) # p r i n t s l i s t two times
p r i n t ( m y l i s t + t i n y l i s t ) # p r i n t s concatenated l i s t s

- 41

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.
Tuples

• A tuple is another sequence data type that is similar to the list.A tuple consists of a number of values
separated by commas. Unlike lists, however, tuples are enclosed withinparenthesis.
• Tuples are inmutable: cannot be updated. Tuples can be thought of as read-only lists. For example:

t u p l e = ( 'abcd', 786 , 2 . 2 3 , ' j ohn' , 70.2 )


t i n y t u p l e = ( 1 2 3 , 'john')
p r i n t ( t u p l e ) # p r i n t s complete t u p l e
p r i n t ( t u p l e [ 0 ] ) # p r i n t s f i r s t element o f t h e t u p l e
p r i n t ( t u p l e [ 1 : 3 ] ) # p r i n t s elements s t a r t i n g from 2nd t i l l 3rd
p r i n t ( t u p l e [ 2 : ] ) # p r i n t s elements s t a r t i n g from 3rd element
p r i n t ( t i n y t u p l e * 2 ) # p r i n t s t u p l e two times
p r i n t ( t u p l e + t i n y t u p l e ) # p r i n t s concatenated t u p l e

42

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Dictionaries OPEN ONLINE AFI. PYTHON.

• Python's dictionaries are kind of hash-table type; and consist of key-value pairs. A dictionary key can
be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
• Dictionaries are enclosed by curly braces { } and values can be assigned and accessed using
square braces []. Forexample:

dict = { }
d i c t [ ' o n e ' ] = " T h i s i s one"
d i c t [ 2 ] = " T h i s i s two"
t i n y d i c t = {'name': 'john','code':6734, 'dept': 'sales'}
p r i n t ( d i c t [ ' o n e ' ] ) # p r i n t s value f o r 'one' key
p r i n t ( d i c t [ 2 ] ) # p r i n t s value f o r 2 key
p r i n t ( t i n y d i c t ) # p r i n t s complete d i c t i o n a r y
p r i n t ( t i n y d i c t . k e y s ( ) ) # p r i n t s a l l t h e keys
p r i n t ( t i n y d i c t . v a l u e s ( ) ) # p r i n t s a l l t h e values

Notebook:
Practicing Python
43
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

9 Strings
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 45

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
OPEN ONLINE AFI. PYTHON.
finanzas
String operators

s t = ' h e l l o myname i s Sam'


st+st # concatenates
st[2:5] # substring
'hello ' i n s t # i s 'hello ' i n s t
'Hello' not i n s t # i s 'hello ' i n s t

# appying s t r i n g methods: strinGVar.method()

s t . l o w e r ( ) # transform t o no c a p i t a l l e t t e r s

st.upper() # capital l e t t e r s

m y_ l i s t = s t . s p l i t ( ) # s p l i t into a l i s t

tweet = 'Go S p o r t s ! #Sports'

tweet.split('#')
tweet.split('#')[1]

a='10'
a.isdigit()
46
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas Stringmethods OPEN ONLINE AFI. PYTHON.

The most commonare:


• capitalize() Capitalizes first letter ofstring
• count(str, beg= 0,end=len(string)) Counts how many times str occurs in string or in a
substring of string if starting index beg and ending index end are given
• find(str, beg=0 end=len(string)) Determine if str occurs in string or in a substring of
string if starting index beg and ending index end are given returns index if found and -1
otherwise
• index(str, beg=0, end=len(string)) Same as find(), but raises anexception if str not found
• isalpha() Returns true if string has at least 1 character and all characters are alphabetic
and falseotherwise
• isdigit() Returns true if the string contains only digits and false otherwise
• isnumeric() Returns true if a unicode string contains only numeric characters and
falseotherwise
• join(seq) Merges (concatenates) the string representations of elements in sequence seq
into a string, with separator string
• len(string) Returns the length of thestring

47
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas Stringmethods OPEN ONLINE AFI. PYTHON.

The most commonare:


• lower() Converts all uppercase letters in string to lowercase
• replace(old,new[,max])Replaces all occurrences of old in string with new or at most max
occurrences if max given
• split(str="", num=string.count(str)) Splits string according to delimiter str (space if not
provided) and returns list of substrings; split into at most num substrings if given
• upper() Converts lowercase letters in string to uppercase

Format method
num = 12
name = 'Sam'
print('My number i s : {one}, and my name is: \
{two}'.format(one=num,two=name))

Notebook:
Practicing Python
48
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

10 Lists
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 50

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Lists OPEN ONLINE AFI. PYTHON.

• The list is the most versatile datatype available in Python, which can be written as a list of
comma-separated values (items) between square brackets.
• Important thing about a list is that the items in a list need not be of the sametype
• Creating a list is as simple as putting different comma-separated values between square
brackets. Forexample:
List1 = [ ' p h ys i c s ' , 'c hemis try', 1997, 2 000] ;
list2 = [ 1 , 2, 3, 4, 5 ] ;
list3 = ["a", "b", "c", "d"];
• List indices start at 0, and lists can be sliced, concatenated and so on

51
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas Lists OPEN ONLINE AFI. PYTHON.

Accessing Values inLists


• To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index. For example:
l i s t 1 = ['physics', 'c hemis try', 1997, 2000]
l i s t 2 = [ 1 , 2, 3, 4, 5, 6, 7 ]
print("list1[0]: ", list1[0])
print("list1[1:5]: " , list1[1:5])
Updating Lists
• You can update single or multiple elements of lists by giving the slice on the left-hand side
of the assignment operator, and you can add to elements in a list with the append() method.
For example-
list = [ ' p h ys i c s ' , 'chemistry', 1997, 2000]
p r i n t ( " Va l u e a v a i l a b l e a t index 2 : " , l i s t [ 2 ] )
l i s t [ 2 ] = 2001
pri nt ("New value a v a i l a b l e a t index 2 : " , l i s t [ 2 ] )

- 52

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Lists OPEN ONLINE AFI. PYTHON.

Remove a listelement
• To remove a list element, you can use either the del statement if you know exactly
which element(s) you are deleting. You can use the remove() method if you do not
know exactly which items to delete. For example:
list = [ 'physics', 'chemistry', 1997, 2000]
print(list)
del l i s t [ 2 ]
print("After deleting value a t index 2 : ", list)
Basic list operators

- 53

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.
Lists

Mostcommon functions and methods for lists


• len(list) Gives the total length of the list.
• max(list) Returns item from the list with max value.
• min(list) Returns item from the list with min value.
• list(seq) Converts a tuple intolist.
• list.append(obj) Appends object obj tolist
• list.count(obj) Returns count of how many times obj occurs in list
• list.extend(seq) Appends the contents of seq to list
• list.index(obj) Returns the lowest index in list that obj appears
• list.insert(index, obj) Insertsobject obj into list at offset index
• list.pop(obj=list[-1]) Removes and returns last object or obj from list
• list.remove(obj) Removes object obj fromlist
• list.reverse() Reverses objects of list inplace
• list.sort([func]) Sorts objects of list, use compare func if given

Notebook:
Practicing Python
- 54

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

11 Tuples
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 56

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Tuples OPEN ONLINE AFI. PYTHON.

• A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
The main difference between the tuples and the lists is that the tuples cannot be
changed unlike lists. Tuplesuse parentheses, whereas lists use square brackets.
• Creating a tuple is as simple as putting different comma-separated values. Optionally, you
can put these comma-separated values between parenthesesalso.
tup1 =('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5)
tup3 = ("a", "b", "c", "d“)
• Accessing values is similar to lists and strings.
tup1 =('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])

- 57

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Tuples OPEN ONLINE AFI. PYTHON.

• Tuplesare immutable,so they can not be updated


• They can be deleted similarly to other objects tup = ('physics',
'chemistry', 1997, 2000); print(tup)
del tup;
print("After deleting tup :“)
print(tup)
• Basic tuplesoperations

- 58

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Tuples OPEN ONLINE AFI. PYTHON.

Common functions andmethods


• len(tuple)Gives the totallength of the tuple.
• max(tuple) Returns item from the tuple with max value.
• min(tuple) Returns item from the tuple with min value.
• tuple(seq) Converts a list intotuple.

Notebook:
Practicing Python

- 59

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

12 Dictionaries
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 61

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Dictionary OPEN ONLINE AFI. PYTHON.

• Dictionary are a useful form of data types. They are set of key-value pairs.
• Each key is separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces. An empty dictionary without any items is
written with just two curly braces, like this: {}.
• Keys are unique within a dictionary while values may not be. The values of a dictionary
can be of any type, but the keys are inmutable
mydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print("mydict['Name']: ", mydict['Name'])
print("mydict['Age']: ", mydict['Age'])
• You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry
mydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
mydict['Age'] = 8; # update existing entry mydict['School']
= "DPS School" # Add new entry
print("mydict['Age']: ", mydict['Age'])
print("mydict['School']: ", mydict['School'])

- 62

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Dictionary OPEN ONLINE AFI. PYTHON.

Deleting dictionaries:
del mydict['Name'] # remove entry with key 'Name'
dict.clear() #remove all entries in mydict del
mydict # delete entiredictionary
Properties of dictionarykeys:
• More than one entry per key is not allowed. This means no duplicate key is allowed.
When duplicate keys areencountered during assignment, the last assignmentwins
• Keys must beimmutable
Functions:
• len(dict) Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.
• str(dict) Produces a printable string representation of a dictionary.
• type(variable) Returns the type of the passed variable.If passed variable is dictionary,
then it would return a dictionary type.

- 63

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Dictionary OPEN ONLINE AFI. PYTHON.

• dict.clear() Removes all elements of dictionarydict.


• dict.copy() Returns a shallow copy of dictionary dict.
• dict.fromkeys() Create a new dictionary with keys from seq and values set tovalue.
• dict.get(key, default=None) For key key, returns value or defaultif key not indictionary
• dict.items()Returns a list of dict's (key,value) tuplepairs.
• dict.keys() Returns list of dictionary dict'skeys
• dict.setdefault(key, default=None) Similar to get(), but willset dict[key]=default if key
is not already indict.
• dict.update(dict2) Adds dictionary dict2's key-values pairsto dict.
• dict.values() Returns list of dictionary dict'svalues.

Notebook:
Practicing Python
Notebook:
Data structures
- 64

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

13 Common operators
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 66

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Data typeconversion OPEN ONLINE AFI. PYTHON.

Most commonconversions:
int(x) Converts x t o an i n t e g e r

float(x) Converts x t o a f l o a t i n g - p o i n t number.

str(x) Converts o b j e c t x t o a s t r i n g r e p r e s e n t a t i o n . e v a l ( s t r )

Evaluates a s t r i n g and r e t u r n s an o b j e c t .

tuple(s) Converts s t o a tuple.

list(s) Converts s t o a list.

set(s) Converts s t o a set.

dict(d) Creates a d i c t i o n a r y. d must be a sequence o f


( k e y, v a l u e ) t u p l e s .

chr( x ) Converts an i n t e g e r t o a c h a r a c t e r.

- 67

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Arithmeticoperators OPEN ONLINE AFI. PYTHON.

68
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas Comparison Operators OPEN ONLINE AFI. PYTHON.

69
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas Assignment operators OPEN ONLINE AFI. PYTHON.

70
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas Logical operators OPEN ONLINE AFI. PYTHON.

Logical

Menbership

- 71

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Mathematical operators and randomfunctions OPEN ONLINE AFI. PYTHON.

i m p o r t math # i m p o r t mathematical module


abs(-5) # a b s o l u t e value
math.ceil(0.1) # s m a l l e s t i n t e g e r g r e a t e r than 0 . 1
m a t h . e xp ( 2. 3) # exponenial o f 2 . 3
math.floor(9.9) # l a r g e s t i n t e g e r s m a l l e r than 9 . 9
m a t h . l o g ( 11 ) # base e l o g a r i t h o f 11
math.log10(100) # base 10 l o g a r i t h o f 100

m a x ( 1 , 2 , 4 , 5 , 7 , 8 , 1 2 , 1 , 3 4 , 2 , 0 ) # f i n d t h e maximun Notebook:
m i n ( 1 , 2 , 4 , 5 , 7 , 8 , 1 2 , 1 , 3 4 , 2 , 0 ) # f i n d t h e minimun
Practicing
math.sqrt(81) # squared r o o t o f 81 Python
round(2.371, 2 ) # round t o 2 numbers

i m p o r t random # i m p or t random number generator module


random.seed(1) # s e t t h e s t a r t i n g number i n t h e random generating f u n c t i o n
r a n d o m . c h o i c e ( [ 1 , 2 , 3 , 4 , 5 ] ) # choose randomly a muber from a l i s t
random.uniform(0,1) # generate a random number between 0 and 1

- 72

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

if, elif, else conditional


14 statements
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 74

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas If statement OPEN ONLINE AFI. PYTHON.

• The if statement contains alogical expression


using which the data is compared and a
decision is made based on the result of the
comparison. True

• Example: IFcondition

var1 = 321 i f False …


var1:
p r i n t ( “ t h e stament was t r u e " )
print(var1)

- 75

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas If .. elif … elsestatements OPEN ONLINE AFI. PYTHON.

• An else statement can be combined with an if


statement. An else statement contains a block of code True

that executes if the conditional expression in the if IFcondition


statement resolves to 0 or a FALSEvalue.
• The else statement is an optional statement and there False …
could be at the most only one else statement following
if.
True
• Example: ELIFcondition

a m o u n t = i n t ( i n p u t ( " E n t e r amount: " ) ) if


amount<1000: False …
discount=amount*0.05
print("Discount",discount) True
e l i f amount<5000: ELIFcondition
discount=amount*0.10
print("Discount",discount) False …
else:
discount=amount*0.15
print("Discount",discount)
p r i n t ( " N e t p a ya b l e : " , a m ou nt - di s c ou n t )

- 76

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

Notebook:
Practicing
Python

More practice:
Notebook
Control structures

77

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

Loops: for, while,


14 break, continue
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 79

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Loops OPEN ONLINE AFI. PYTHON.

Python programming language provides the following types of loops to handle looping
requirements.
• for: Executes a sequence of statements multiple times and abbreviates the code that manages the loop
variable
• while: Repeats a statement or group of statements while a given condition is True. It tests the
condition before executing the loop body
You can use one or more loop inside any another while, or for loop: nestedd loops.

fordiagram whilediagram

- 80

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Loops OPEN ONLINE AFI. PYTHON.

# f o r loop example
f o r l e t t e r i n 'Europe': # l e t t e r o f a s t r i n g sequence
print('Current Letter : ' , letter)
print()

sp_numbers= ['uno', 'dos', ' t r e s ' ]


f o r numero i n sp_numbers: # t r a v e r s a l o f L i s t sequence
p r i n t ( ' C u r r e n t number : ' , numero)
p r i n t ( " G ood b y e ! " )

# w h i l e loop example
count = 0
w h i l e ( c o unt <9 ) :
p r i n t ( ' T h e count i s : ' , c o u n t ) count
= count + 1
print("Cheers!")

- 81

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Loop controlstatement OPEN ONLINE AFI. PYTHON.

• The Loop control statements change the execution from its normal sequence.
• Python supportsthe following control statements:
– break statement:Terminates the loop statement and transfers execution to the
statement immediately following the loop.
– continuestatement:Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
– pass statement:The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code toexecute

- 82

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Loop controlstatement OPEN ONLINE AFI. PYTHON.

break

for letter in 'Europa': # First Example


i f letter == ' r ' :
break
print('Current Letter :', letter)

var = 10 wh i l e
var > 0:
p r i n t ( 'Current variable value : ', var)
var = var -1
if
var == 5 :
break
print("Cheers!")

- 83

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Loop controlstatement OPEN ONLINE AFI. PYTHON.

continue

for letter in 'Python': # First Example


i f letter == 'h':
continue
print('Current Letter :', letter)

v a r = 10 # Second Example
wh i l e v a r > 0 :
v a r =v a r - 1 i f
v a r == 5:
continue
p r i n t ( 'Current variable value : ', var)
print("Good bye!")

Notebook:
Practicing
Python
- 84

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

15 Functions
iStockphoto

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Contents OPEN ONLINE AFI. PYTHON.

1. History 10. Lists


2. Characteristics 11. Tuples
3. Installation 12. Dictionaries
4. Working with Python(IDEs, 13. Common operators
notebooks) 14. if,elif, else conditional
5. Running Pythonprograms statements
6. Identifiers and reservedworks 15. Loops: for, while, break,continue
7. Indentation andmulti-line 16. Functions
statements
8. Variables andtypes
9. Strings

- 86

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Functions OPEN ONLINE AFI. PYTHON.

• A function is a block of organized, reusable code that is used to perform some actions.
• Python gives you many built-in functions like print(), etc.but you can also create your ownfunctions. These
functions are called user-defined functions
• Here are simple rules to define a function in Python.
1. Function blocks begin with the keyword def followed by the function name and parentheses ( ).
2. Any input parameters or arguments should be placed within these parentheses.
3. You can also define parameters inside these parentheses.
4. The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
5. The code block within every function starts with a colon (:) and is indented.
6. The statement return [expression] exits a function, optionally passing back an expression to the
caller.A return statement with no arguments is the same as return None.
def printme( str):
"This prints a passed string into this function" print(str)

87

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Functions OPEN ONLINE AFI. PYTHON.

Calling a function
• When not using the keyword argument name, the number of arguments in the function
call should match exactly with the function definition; and the arguments must be passed
in correct position order
• When you use keyword arguments in a function call, the caller identifies the arguments by
the parameter name. This allows you to skip arguments or place them out of order
because the Python interpreter is able to use the keywords provided to match the values
with parameters
# Function d e f i n i t i o n i s here d e f
p r i n t i n f o ( name, age ) :
" T h i s p r i n t s a passed i n f o i n t o t h i s function"
pr i nt ("N ame: " , name)
p r i n t ( " A g e " , age)
return
# Nowyou can c a l l p r i n t i n f o f u n c t i o n
p r i n t i n f o ( age=50, name="miki" )
• Default arguments:
d e f p r i n t i n f o ( name, age = 35 ) :
" T h i s p r i n t s a passed i n f o i n t o t h i s f u n c t i o n "
p r i n t ( " N a m e : " , name)

- 88

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Functions OPEN ONLINE AFI. PYTHON.

Local vs global variables: Variables that are defined inside a function body have a local scope, and
those defined outside have a global scope
Variable lengtharguments:
• You may need to process a function for more arguments than you specified while defining
the function.These arguments are called variable-length arguments
• Syntax for a function with non-keyword variable arguments is:
# Function d e f i n i t i o n i s here d e f
p r i n t i n f o ( arg1, *vartuple ) :
" T h i s p r i n t s a v a r i a b l e passed arguments"
print("Output i s : " )
print(arg1)
f o r var i n v a r t u p l e :
print(var)
return
# Nowyou can c a l l p r i n t i n f o f u n c t i o n
p r i n t i n f o ( 10 )
p r i n t i n f o ( 7 0 , 6 0 , 50 )

- 89

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Lambda or anonymousfunction OPEN ONLINE AFI. PYTHON.

These functions are called anonymous because they are not declared in the standard manner by
using the def keyword.You can use the lambda keyword to create small anonymousfunctions:
• Lambda forms can take any number of arguments but return just one value in the form
of an expression. They cannot contain commands or multipleexpressions.
• An anonymous function cannot be a directcallto print because lambda requires an
expression.
• Lambda functions have their own local namespace and cannot access variables other than
those in their parameter list and those in the globalnamespace.
# Function d e f i n i t i o n i s here
My_sum = lambda a r g 1 , a r g 2 : arg1 + arg2 # Nowyou can
c a l l sum as a f u n c t i o n
p r i n t ( " Va l u e o f t o t a l : " , My_sum( 1 0 , 20 ) )
p r i n t ( " Va l u e o f t o t a l : " , My_sum( 2 0 , 20 ) )

- 90

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas Functions: Returnstatement OPEN ONLINE AFI. PYTHON.

• The statement return [expression] exits a function, optionally passing back an expression
to the caller.A return statement with no arguments is the same as return None.
• All the examples given above are not returning any value. You can return a value from a
function as follows:
# Function d e f i n i t i o n i s here d e f
Mysum( a r g 1 , arg2 ) :
# Add both t h e parameters and r e t u r n them." t o t a l = arg1 +
arg2
p r i n t ( " I n s i d e the function : " , t o t a l )
return t o t a l
# Nowyou can c a l l sum f u n c t i o n t o t a l =
Mysum( 1 0 , 20 )
print("Outside the function : " , t o t a l )

Notebook: More practice:


Practicing Python Notebook
Functions and modules
- 91

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados


Escuela de
finanzas OPEN ONLINE AFI. PYTHON.

Vídeo:
Errores Python

Ejercicios #1

92

© Afi Escuela de Finanzas, S.A. Todos los derechos reservados

También podría gustarte