Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Programación
con 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:
1 History
iStockphoto
- 4
- 5
6
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas OPEN ONLINE AFI. PYTHON.
2 Characteristics
iStockphoto
- 8
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
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
3 Installation
iStockphoto
- 12
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/)
- 13
Installing Anaconda
Installing Anaconda is straightforward: download it here: https://www.anaconda.com/distribution/
and follow the instructions
Important points:
• If you are asked during the installation process whether you’d like to make Anaconda your default
Python installation, say yes
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.
• Open up a terminal
Vídeo:
Instalación
• Type “conda update anaconda”
Python
- 14
- 16
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
• IPython will, in almost all cases, help you get the job done faster (tab
completition, integrated plots, magic comands, ...
- 18
- 19
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
- 23
Running Python
1. Interactive Interpreter
Launch Python, IPython and Jupyter; and work with Python in a interactive way
- 24
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
- 27
• 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:
Example:
Var_number = 10
Myvar_text = ” H i ! ”
My_sum = 1+1 +Var_number
- 28
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.
- 31
• 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
• 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
- 35
• 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.
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.
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
• 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
– int (signedintegers)
– float (floating point realvalues)
– complex (complexnumbers)
- 39
• 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
• 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
• 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:
42
• 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
- 45
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.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.
47
-
© Afi Escuela de Finanzas, S.A. Todos los derechos reservados
Escuela de
finanzas Stringmethods OPEN ONLINE AFI. PYTHON.
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
- 50
• 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.
- 52
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
Notebook:
Practicing Python
- 54
11 Tuples
iStockphoto
- 56
• 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
- 58
Notebook:
Practicing Python
- 59
12 Dictionaries
iStockphoto
- 61
• 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
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
Notebook:
Practicing Python
Notebook:
Data structures
- 64
13 Common operators
iStockphoto
- 66
Most commonconversions:
int(x) Converts x t o an i n t e g e r
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 .
chr( x ) Converts an i n t e g e r t o a c h a r a c t e r.
- 67
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
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
- 72
- 74
• Example: IFcondition
- 75
- 76
Notebook:
Practicing
Python
More practice:
Notebook
Control structures
77
- 79
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
# 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()
# 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
• 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
break
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
continue
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
15 Functions
iStockphoto
- 86
• 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
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
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
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
• 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 )
Vídeo:
Errores Python
Ejercicios #1
92