Introduction to Programming Languages - Illinoishrtdmrt2/Teaching/NM_2017_Fall/L2/L2.pdf ·...

45
Introduction to Programming Languages Carlos Hurtado Department of Economics University of Illinois at Urbana-Champaign [email protected] Sep 12th, 2017 C. Hurtado (UIUC - Economics) Numerical Methods

Transcript of Introduction to Programming Languages - Illinoishrtdmrt2/Teaching/NM_2017_Fall/L2/L2.pdf ·...

Introduction to Programming Languages

Carlos Hurtado

Department of EconomicsUniversity of Illinois at Urbana-Champaign

[email protected]

Sep 12th, 2017

C. Hurtado (UIUC - Economics) Numerical Methods

On the Agenda

1 Python

2 A Powerful Calculator

3 Data Types

4 Defining a Function in Python

5 Using Modules

6 Boolean Expressions

7 Conditional Statements

8 Recursive Functions

C. Hurtado (UIUC - Economics) Numerical Methods

Python

On the Agenda

1 Python

2 A Powerful Calculator

3 Data Types

4 Defining a Function in Python

5 Using Modules

6 Boolean Expressions

7 Conditional Statements

8 Recursive Functions

C. Hurtado (UIUC - Economics) Numerical Methods

Python

Python

I There are several interpreted programming languages:Implementations execute instructions directly (line by line)

I Examples of interpreted programming languages:- JavaScript- Python- Matlab- Stata

I There are several compiled programming languages: Implementationsrequire a compiler to generate machine code that is executed directlyby the computer’s central processing unit (CPU).

I Examples of compiled programming languages:- C- C++- Fortran- Pascal

C. Hurtado (UIUC - Economics) Numerical Methods 1 / 34

Python

Python

I Advantages of Python?- Interactive console (Dynamically Typed Language)- Clear, readable syntax- Full modularity- Exception-based error handling- Dynamic data types, and automatic memory management

I disadvantages of Python?- Is ”slower” than compiled code performing computations

I There are two replies to this criticism:- Implementation time versus execution time- Well-written Python code can be very fast

C. Hurtado (UIUC - Economics) Numerical Methods 2 / 34

Python

Python Version

I There are two version of the Python language out there: Python 2.xand Python 3.x.

I The changes in Python 3.x were introduced to address problems in thedesign of the language that were identified since Python’s inception.

I A decision has been made that some incompatibility should beaccepted to achieve the higher goal of a better language for thefuture.

I For scientific computation, it is crucial to make use of numericallibraries.

I All of these are available for Python 2.x, and increasingly they arealso available for Python 3. (but not all yet)

I We will use Python 2.x, but wi will write code that is as much aspossible in the Python 3 style.

C. Hurtado (UIUC - Economics) Numerical Methods 3 / 34

Python

Python Version

I A simple example of incompatibility: In Python 2.x, the printcommand is special where as in Python 3.x it is an ordinary function.

I In Python 2.7, we can write1 """2 Python 2.73 """4 print "Hello World"

In Python 3, this would cause a SyntaxError.I The right way to use print in Python 3 would be as a function:1 """2 Python 3.x3 """4 print ("Hello World")

C. Hurtado (UIUC - Economics) Numerical Methods 4 / 34

A Powerful Calculator

On the Agenda

1 Python

2 A Powerful Calculator

3 Data Types

4 Defining a Function in Python

5 Using Modules

6 Boolean Expressions

7 Conditional Statements

8 Recursive Functions

C. Hurtado (UIUC - Economics) Numerical Methods

A Powerful Calculator

A Powerful Calculator

I We can either collect sequences of commands into text files and savethis to file as a Python program. (”.py”)

I We can also enter individual commands at the Python prompt whichare immediately evaluated and carried out by the Python interpreter.

I Basic operations such as addition (+), subtraction (-), multiplication(*), division (/) and exponentiation (**) work (mostly) as expected:

1 >>> 47*112 5173 >>> 10/0.54 20.05 >>> 2**46 167 >>> 3**0.58 1.73205080756887729 >>> 2*10+5

10 2511 >>> 2*(10+5)12 30

C. Hurtado (UIUC - Economics) Numerical Methods 5 / 34

A Powerful Calculator

Integer division

I Unexpected behavior can occur when dividing two integer numbers:1 >>> 15/62 2

I This phenomenon is known as integer division.

I Because we provide two integer numbers (15 and 6) to the divisionoperator (/), the assumption that Python makes is that we seek areturn value of type integer.

I The mathematically correct answer is (the floating point number) 2.5.

C. Hurtado (UIUC - Economics) Numerical Methods 6 / 34

A Powerful Calculator

How to avoid integer division?

I If we ensure that at least one number (numerator or denominator) isof type float, the division operator will return a floating point number:

1 >>> 15/62 23 >>> 15./64 2.55 >>> 15.0/66 2.57 >>> float (15) /68 2.59 >>> 15/6.

10 2.511 >>> 15/ float (6)12 2.513 >>> 15./6.14 2.5

C. Hurtado (UIUC - Economics) Numerical Methods 7 / 34

A Powerful Calculator

Mathematical functions

I Commonly used mathematical functions such as sin, cos, exp, log andmany others are located in the mathematics module with name math.

1 >>> import math2 >>> math.exp (1.0)3 2.7182818284590451

I Using the dir function, we can see the directory of objects available inthe math module:

1 >>> dir(math)2 [ ’__doc__ ’,’__file__ ’,’__name__ ’,’acos ’,’asin ’,’atan ’,’

atan2 ’,’ceil ’,’cos ’,’cosh ’,’degrees ’,’e’,’exp ’,’fabs’,’floor ’,’fmod ’,’frexp ’,’hypot ’,’ldexp ’,’log ’,’log10 ’,’modf ’,’pi’,’pow ’,’radians ’,’sin ’,’sinh ’,’sqrt ’,’tan ’,’tanh ’]

I The help function provides more information about the module onindividual objects:

1 >>> help(math.ceil)

C. Hurtado (UIUC - Economics) Numerical Methods 8 / 34

A Powerful Calculator

Variables

I A variable can be used to store a certain value or object.

I In Python, all numbers (and everything else, including functions andmodules) are objects.

I A variable is created through assignment:1 >>> x=0.5

I Once the variable x has been created through assignment of 0.5 inthis example, we can make use of it:

1 >>> x*32 1.53 >>> x**24 0.25

C. Hurtado (UIUC - Economics) Numerical Methods 9 / 34

A Powerful Calculator

Variables

I A value can be assigned to several variables simultaneously:1 >>> x = y = z = 1 # initialise x , y and z with 12 >>> x3 14 >>> y5 16 >>> z7 1

I Variables must be created (assigned a value) before they can be used,or an error will occur

I Strictly speaking, Python creates the object 1. This object is storedsomewhere in memory.

I When we type x = 1, Python binds a name to the object. The nameis x , and we often refer casually to x as a variable.

I Technically, x is a name that is bound to the object 1. Another wayto say this is that x is a reference to the object.

C. Hurtado (UIUC - Economics) Numerical Methods 10 / 34

A Powerful Calculator

Variables

I While it is often sufficient to think about assigning 1 to a variable x ,there are situations where we need to remember what actuallyhappens.

I When we operate using a reference to an object, we operate theobject, rather than a copy of the object.

1 >>> a = [1 ,2 ,3]2 >>> b=a3 >>> id(a)4 1404200603916165 >>> id(b)6 1404200603916167 >>> a [0]=998 >>> b9 [99 ,2 ,3]

C. Hurtado (UIUC - Economics) Numerical Methods 11 / 34

A Powerful Calculator

Variables

I The common operation of increase a variable x by a fixed amount 1can be written as:

1 >>> x=102 >>> x=x+13 >>> print x4 11

I Not to be confused to a math equation. This operation evaluates thevalue on the right hand side of the equal sign, and assign this value tothe variable name shown on the left hand side.

I Because it is a quite a common operation to increase a variable x bysome fixed amount c, we can write

1 >>> x+=12 >>> print x3 12

I The same operators are defined for multiplication with a constant(*=), subtraction of a constant (-=) and division by a constant (/=)

C. Hurtado (UIUC - Economics) Numerical Methods 12 / 34

Data Types

On the Agenda

1 Python

2 A Powerful Calculator

3 Data Types

4 Defining a Function in Python

5 Using Modules

6 Boolean Expressions

7 Conditional Statements

8 Recursive Functions

C. Hurtado (UIUC - Economics) Numerical Methods

Data Types

Data Types

I Python knows different data types. To find the type of a variable, usethe type() function:

1 >>> a = 452 >>> type (a)3 ’int ’4 >>> b = ’This is a string ’5 >>> type (b)6 ’str ’7 >>> c = 2 + 1j8 >>> type (c)9 ’complex ’

10 >>> d = [1 , 3 , 56]11 >>> type (d)12 ’list ’

C. Hurtado (UIUC - Economics) Numerical Methods 13 / 34

Data Types

Data Types

I Different data types can not be added together.

I But Python is a Strongly Typed Language, we have a semantic error1 >>> 2000 + 0502 2040

I By convention, any number starting with 0 is an integer base 8.

I We can use the function int() to transform some types to integer.1 >>> int (050)2 403 >>> int(’230 ’)4 230

C. Hurtado (UIUC - Economics) Numerical Methods 14 / 34

Data Types

Data Types

I To know information about the system, such as the maximum integerthat can be represented by the OS, we can use the module sys.

1 >>> import sys2 >>> sys. maxint3 9223372036854775807

I If this range is exceeded, then Python will change the type of thenumber from int to long :

1 >>> type(sys. maxint )2 ’int ’3 >>> sys. maxint +14 9223372036854775808 L5 >>> type(sys. maxint +1)6 ’long ’

I To get relevant system info we can use the method float info1 >>> sys. float_info

C. Hurtado (UIUC - Economics) Numerical Methods 15 / 34

Data Types

Data Types

I Python defines as floating point number any number containing adecimal point

1 >>> type (1.)2 ’float ’

I A string containing a floating point number can be converted into afloat using the float() command:

1 >>> float (’35.67 ’)2 35.67

C. Hurtado (UIUC - Economics) Numerical Methods 16 / 34

Data Types

Data Types

I Strings, lists and tuples are sequences. They can be indexed andsliced in the same way.

I Sequences share the following operations:

a[i] returns i-th element of a (starting in zero)a[i:j] returns elements i up to j − 1

len(a) returns number of elements in sequencemin(a) returns smallest value in sequencemax(a) returns largest value in sequencex in a returns True if x is element in aa + b concatenates a and bn * a creates n copies of sequence a

C. Hurtado (UIUC - Economics) Numerical Methods 17 / 34

Data Types

Data Types

I Consider the following example:1 >>> a="Hello World"2 >>> a[0]3 ’H’4 >>> a[0:5]5 ’Hello ’6 >>> len(a)7 118 >>> min(a)9 ’ ’

10 >>> max(a)11 ’r’12 >>> ’z’ in a13 False14 >>> a + ’ and Moon ’15 ’Hello World and Moon ’16 >>> 5*’ok ’17 ’ok ok ok ok ok ’

C. Hurtado (UIUC - Economics) Numerical Methods 18 / 34

Data Types

Data Types

I Strings have a number of useful methods, including for exampleupper() which returns the string in upper case:

1 >>> a="Hello World"2 >>> a.upper ()3 ’HELLO WORLD ’

I A list of available string methods can be found in the Pythonreference documentation.

I Other method is split(), which converts a string into a list of strings:(help(a.split))

1 >>> a.split ()2 [’Hello ’, ’World ’]3 >>> a.split("o")4 [’Hell ’, ’ W’, ’rld ’]

C. Hurtado (UIUC - Economics) Numerical Methods 19 / 34

Data Types

Data Types

I A list is a sequence of objects. The objects can be of any type, forexample integers or strings:

1 >>> a = [34 , 12 , 54]2 >>> a = [’dog ’,’cat ’,’mouse ’]

I An empty list may also be represented:1 >>> b=[]

I The number of elements in a list can be obtained using the len()function:

1 >>> len(a)2 3

I It is also possible to mix different types in the same list:1 >>> a=[123 , ’duck ’ ,[4 ,3 ,2 ,2]]

C. Hurtado (UIUC - Economics) Numerical Methods 20 / 34

Data Types

Data Types

I You can combine (”concatenate”) two lists using the + operator:1 >>> a = [34 , 12 , 54] + [4, 2] + []2 [34, 12, 54, 4, 2]

I the range(n) command generates a list of integers starting from 0 andgoing up to, but not including n.

1 >>> range (3)2 [0, 1, 2]3 >>> range (3 , 10)4 [3, 4, 5, 6, 7, 8, 9]5 >>> range (3 , 10 , 2)6 [3, 5, 7, 9]7 >>> range (10 , 0 , -1)8 [10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1]

C. Hurtado (UIUC - Economics) Numerical Methods 21 / 34

Defining a Function in Python

On the Agenda

1 Python

2 A Powerful Calculator

3 Data Types

4 Defining a Function in Python

5 Using Modules

6 Boolean Expressions

7 Conditional Statements

8 Recursive Functions

C. Hurtado (UIUC - Economics) Numerical Methods

Defining a Function in Python

Defining a Function in Python

I We can define functions to provide a particular functionality.I Here are simple rules to define a function in Python.

- Function blocks begin with the keyword def followed by the functionname and parentheses.

- Any input parameters or arguments should be placed within theseparentheses.

- The first statement of a function is an optional statement - thedocumentation string of the function (a.k.a. docstring).

- The code block within every function starts with a colon (:) and isindented (four spaces).

- The statement return [expression] exits a function, optionally passingback an expression to the caller. A return statement with no argumentsis the same as return None.

C. Hurtado (UIUC - Economics) Numerical Methods 22 / 34

Defining a Function in Python

Defining a Function in Python

I We can define functions to provide a particular functionality.I Here are simple rules to define a function in Python.1 def functionname ( parameters ):2 " function_docstring "3 function_suite4 return [ expression ]

I By default, parameters have a positional behavior and you need toinform them in the same order that they were defined.

I Once the basic structure of a function is finalized, you can execute itby calling it from another function or directly from the Pythonprompt.

I All parameters (arguments) in the Python are passed by reference. Ifyou change what a parameter refers to within a function, the changealso reflects back in the calling function.

C. Hurtado (UIUC - Economics) Numerical Methods 22 / 34

Defining a Function in Python

Defining a Function in Python

I We need to be careful not to operate an object instead of a copy ofthe object

1 def changeme ( mylist ):2 "This changes a passed list into this function "3 mylist . append ([1 ,2 ,3 ,4]);4 print ( " Values inside the function : %s" % mylist )5 return

I What happens if we use the method append over a list? The methodwill change the object itself.

I We will change the value of the list ”in place”.I In python an object is immutable only if none of its methods can

mutate the underlying data.I In python, lists and user-defined classes (unless specifically made

immutable) are examples of types that are mutableC. Hurtado (UIUC - Economics) Numerical Methods 23 / 34

Defining a Function in Python

Defining a Function in Python

I Let us exemplify:1 >>> mylist = [10 ,20 ,30]2 >>> changeme ( mylist )3 Values inside the function : [10 , 20, 30, [1, 2, 3, 4]]4 >>> print " Values outside the function : ", mylist5 Values outside the function : [10, 20, 30, [1, 2, 3, 4]]

I Most of the built-in objects (data types) in python are immutable:int, float, complex, string.

1 def ref_demo (x):2 print "x=",x," id=",id(x)3 x=424 print ("x= %s id= %s" %(x,id(x)) )5 >>> x=96 >>> id(x)7 182150648 >>> ref_demo (x)9 x= 9 id= 18215064

10 x= 42 id= 18216264C. Hurtado (UIUC - Economics) Numerical Methods 24 / 34

Defining a Function in Python

Defining a Function in Python

I We can define functions that take more than one argument:1 def norm(x,y):2 n=(x**2+y**2) **(0.5)3 return n

and will produce:1 >>> norm (3 ,4):2 5.0

I It is also possible to return more than one argument.1 def upperAndLower ( string ):2 return string .upper () , string .lower ()

I What happens if we execute the following?1 upp ,low = upperAndLower (’pen ’)2 uff = upperAndLower (’uff ’)

C. Hurtado (UIUC - Economics) Numerical Methods 25 / 34

Using Modules

On the Agenda

1 Python

2 A Powerful Calculator

3 Data Types

4 Defining a Function in Python

5 Using Modules

6 Boolean Expressions

7 Conditional Statements

8 Recursive Functions

C. Hurtado (UIUC - Economics) Numerical Methods

Using Modules

Using Modules

I Modules group together functionality and extend Python.I You can import a module by typing the key word import and then the

module name:1 import math

I This will introduce the name math into the working space (not as avariable)

I To access the functions and modules within the math module weneed to use the object-dot notation

I For example math.sin will access the function sin in the module math.I The name by which the module is known locally can be different from

its calling name.1 import numpy as np

C. Hurtado (UIUC - Economics) Numerical Methods 26 / 34

Using Modules

Using Modules

I We can import particular functions or modules from a module, forexample

1 from scipy.stats import norm

I This will import the module norm from the module stats in the scipymodule.

I We can get different functions from the module norm, for example1 >>> norm.cdf (0)2 0.5

I However, the previously defined norm function has been overwritten

C. Hurtado (UIUC - Economics) Numerical Methods 27 / 34

Boolean Expressions

On the Agenda

1 Python

2 A Powerful Calculator

3 Data Types

4 Defining a Function in Python

5 Using Modules

6 Boolean Expressions

7 Conditional Statements

8 Recursive Functions

C. Hurtado (UIUC - Economics) Numerical Methods

Boolean Expressions

Boolean Expressions

I The python values True and False are special inbuilt objects.I We can operate with these two logical values using boolean logic and

the operators and , or , not.1 >>> True and False2 False3 >>> True or False4 True5 >>> not True6 False

I We can also use the special characters & and |1 >>> True & False2 False3 >>> True | False4 True

C. Hurtado (UIUC - Economics) Numerical Methods 28 / 34

Boolean Expressions

Boolean Expressions

I However, empty objects are treated as logically False while non-emptyare logically True. (recommendation: learn exactly what & and |do before using those)

1 >>> [False] and True2 True3 >>> [False] & True4 Error: unsupported operand types

I we often need to evaluate some expression that is either true or false1 >>> x = 302 >>> x > 303 False4 >>> x==305 True6 >>> x!=307 False8 >>> x >=309 True

10 >>> x <=1511 False

C. Hurtado (UIUC - Economics) Numerical Methods 29 / 34

Conditional Statements

On the Agenda

1 Python

2 A Powerful Calculator

3 Data Types

4 Defining a Function in Python

5 Using Modules

6 Boolean Expressions

7 Conditional Statements

8 Recursive Functions

C. Hurtado (UIUC - Economics) Numerical Methods

Conditional Statements

Conditional Statements

I Conditional statements perform different computations depending ona programmer-specified boolean condition

I The If-then-else1 a = 342 if a > 0:3 print " a is positive "4 else :5 print " a is non - positive "

I there is the elif (read as ’else if’) keyword that allows checking forseveral (exclusive) possibilities:

1 a = -172 if a == 0:3 print " a is zero "4 elif a < 0:5 print " a is negative "6 else :7 print " a is positive "

C. Hurtado (UIUC - Economics) Numerical Methods 30 / 34

Conditional Statements

Conditional Statements

I The for-loop allows to iterate over a sequence, for example, a stringor a list.

I For example:1 >>> for animal in [ ’dog ’ , ’cat ’ , ’mouse ’ ]:2 ... print "small ", animal ," - BIG", animal .upper ()3 small dog - BIG DOG4 small cat - BIG CAT5 small mouse - BIG MOUSE

I We can have a good use for the function range:1 >>> for i in range (5 ,10):2 ... print i3 54 65 76 87 9

C. Hurtado (UIUC - Economics) Numerical Methods 31 / 34

Conditional Statements

Conditional Statements

I The While loop allow us to repeat an operation while a condition istrue.

I Suppose we would like to know for how many years we have to keep$100 on a savings account to reach at least $200 due to annualinterest rate of 5%.

I We can use the computer to find the solution:1 money = 1002 rate = 1.053 years = 04 while money < 200:5 money = money*rate6 years = years + 17 print "We need", years , "years to get %3.2f" %money

That will produce:1 We need 15 years to get 207.89

C. Hurtado (UIUC - Economics) Numerical Methods 32 / 34

Recursive Functions

On the Agenda

1 Python

2 A Powerful Calculator

3 Data Types

4 Defining a Function in Python

5 Using Modules

6 Boolean Expressions

7 Conditional Statements

8 Recursive Functions

C. Hurtado (UIUC - Economics) Numerical Methods

Recursive Functions

Recursive Functions

I Recursion is a way of programming or coding a problem, in which afunction calls itself one or more times in its body.

I Example of recursion: The Fibonacci numbers

I The definition is as follows:

Fn = Fn−1 + Fn−2

andF0 = 0, F1 = 1

I We get an infinite sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...

C. Hurtado (UIUC - Economics) Numerical Methods 33 / 34

Recursive Functions

Recursive Functions

I A function that will produce the Fibonacci numbers is:1 def fib(n):2 if n == 0:3 return 04 elif n == 1:5 return 16 else:7 return fib(n -1) + fib(n -2)

I We can compute some of the numbers as follows:1 >>> fib (10)2 553 >>> fib (20)4 67655 >>> fib (30)6 8320407 >>> fib (35)8 9227465

C. Hurtado (UIUC - Economics) Numerical Methods 34 / 34