DM550/DM857 Introduction to Programming Peter Schneider-Kamp - - PowerPoint PPT Presentation

dm550 dm857 introduction to programming peter schneider
SMART_READER_LITE
LIVE PREVIEW

DM550/DM857 Introduction to Programming Peter Schneider-Kamp - - PowerPoint PPT Presentation

DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/DM550/ http://imada.sdu.dk/~petersk/DM857/ Operator Precedence expressions are evaluated left-to-right Example: 64 - 24 + 2


slide-1
SLIDE 1

DM550/DM857 Introduction to Programming Peter Schneider-Kamp

petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/DM550/ http://imada.sdu.dk/~petersk/DM857/

slide-2
SLIDE 2

Operator Precedence

§ expressions are evaluated left-to-right § Example: 64 - 24 + 2 == 42 § BUT: like in mathematics, “*” binds more strongly than “+” § Example: 2 + 8 * 5 == 42 § parentheses have highest precedence: 64 - (24 + 2) == 38 § PEMDAS rule: § Parentheses “( <expr> )” § Exponentiation “**” § Multiplication “*” and Division “/”, "//", "%" § Addition “+” and Subtraction “-”

June 2009 2

slide-3
SLIDE 3

String Operations

§ Addition “+” works on strings: § Example 1: print("Hello w" + "orld!") § Example 2: print("4" + "2") § Multiplication “*” works on strings, if 2nd operands is integer: § Example: print("Hej!" * 10) § Subtraction “-”, Division “/”, and Exponentiation “**” do NOT work on strings

June 2009 3

slide-4
SLIDE 4

Debugging Expressions

§ most beginners struggle with common Syntax Errors: § check that all parentheses and quotes are closed § check that operators have two operands § sequential instruction should start on the same column or be separated by a semicolon “;” § common Runtime Error due to misspelling variable names: § Example: a = float(input()); b = float(input()) reslut = a**b+b**a print(result)

June 2009 4

slide-5
SLIDE 5

Statements

§ instructions in Python are called statements § so far we know 2 different statements: § assignments “=”: c = a**2+b**2 § any expression is a statement § as a grammar rule: <stmt> => <var> = <expr> | <expr>

June 2009 5

slide-6
SLIDE 6

Comments

§ programs are not only written, they are also read § document program to provide intuition: § Example 1: c = sqrt(a**2+b**2) # use Pythagoras § Example 2: x, y = y, x # swap x and y § all characters after the comment symbol “#” are ignored § Example: x = 23 #+19 results in x referring to the value 23

June 2009 6

slide-7
SLIDE 7

Many Ways to Python Development

§ browser-based development: § https://trinket.io/features/python3 § browser-based visualization: § http://www.pythontutor.com/visualize.html § standard IDE for Python NOT recommend (IDLE) § other Python(-enabled) IDEs:

https://wiki.python.org/moin/IntegratedDevelopmentEnvironments § Thonny (incl. visualization): http://thonny.org/ § Pyzo + Miniconda/Anaconda: http://pyzo.org/ § or for something else: https://ipython.org/

§ hardcore: use command line and a text editor :)

June 2009 7

slide-8
SLIDE 8

Code Café

§ manned Code Cafe for students § first time Wednesday, September 6 § last time Wednesday, December 20 § closed in Week 42 (efterårsferie) § Mondays, 15.00 – 17.00, Nicky Cordua Mattsson § Wednesdays, 15.00 – 17.00, Troels RisumVigsøe Frimer § § Nicky and Troels can help with any coding related issues § issues have to be related to some IMADA course (fx this one)

June 2009 8

slide-9
SLIDE 9

CALLING FUNCTIONS

June 2009 9

slide-10
SLIDE 10

Calling Functions

§ so far we have seen four different function calls: § input(): reads a value from the keyboard § sqrt(x): computes the square root of x § type(x): returns the type of the value of x § print(x): prints argument and returns None § in general, a function call is also an expression: § <expr> => … | <function>(<arg1>, …, <argn>) § Example 1: x = input() print(type(x)) § Example 2: from math import log print(log(4398046511104, 2))

June 2009 10

slide-11
SLIDE 11

Importing Modules

§ we imported the sqrt function from the math module: from math import sqrt § alternatively, we can import the whole module: import math § using the built-in function “dir(x)” we see math’s functions:

acos ceil expm1 gamma ldexp pow trunc acosh cos fabs gcd lgamma radians asin cosh factorial hypot log sin asinh degrees floor isclose log10 sinh atan erf fmod isfinite log1p sqrt atan2 erfc frexp isinf log2 tan atanh exp fsum isnan modf tanh

§ access using “math.<function>”: c = math.sqrt(a**2+b**2)

June 2009 11

slide-12
SLIDE 12

The Math Module

§ contains 25 functions (trigonometric, logarithmic, …): § Example: x = input() print(math.sin(x)**2+math.cos(x)**2) § contains 2 constants (math.e and math.pi): § Example: print(math.sin(math.pi / 2)) § contains 3 meta data (__doc__, __file__, __name__): § print(math.__doc__) § print(math.frexp.__doc__) § print(type.__doc__)

June 2009 12

slide-13
SLIDE 13

Type Conversion Functions

§ Python has pre-defined functions for converting values § int(x): converts x into an integer § Example 1: int("1234") == int(1234.9999) § Example 2: int(-3.999) == -3 § float(x): converts x into a float § Example 1: float(42) == float("42") § Example 2: float("Hej!") results in Runtime Error § str(x): converts x into a string § Example 1: str(23+19) == "42" § Example 2: str(type(42)) == "<type 'int'>"

June 2009 13

slide-14
SLIDE 14

DEFINING FUNCTIONS

June 2009 14

slide-15
SLIDE 15

Function Definitions

§ functions are defined using the following grammar rule: <func.def> => def <function>(<arg1>, …, <argn>): <instr1>; …; <instrk> § can be used to reuse code: § Example: def pythagoras(): c = math.sqrt(a**2+b**2) print("Result:", c) a = 3; b = 4; pythagoras() a = 7; b = 15; pythagoras() § functions are values: type(pythagoras)

June 2009 15

slide-16
SLIDE 16

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 16

slide-17
SLIDE 17

Executing Programs (Revisited)

§ Program stored in a file (source code file) § Instructions in this file executed top-to-bottom § Interpreter executes each instruction

June 2009 17

Source Code Input Interpreter Output

slide-18
SLIDE 18

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 18

create new function variable “white”

slide-19
SLIDE 19

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 19

create new function variable “black”

slide-20
SLIDE 20

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 20

create new function variable “all”

slide-21
SLIDE 21

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 21

call function “all”

slide-22
SLIDE 22

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 22

call function “white”

slide-23
SLIDE 23

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 23

print " # # # # # # # #"

slide-24
SLIDE 24

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 24

call function “black”

slide-25
SLIDE 25

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 25

print "# # # # # # # # "

slide-26
SLIDE 26

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 26

call function “white”

slide-27
SLIDE 27

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 27

print " # # # # # # # #"

slide-28
SLIDE 28

Functions Calling Functions

§ functions can call other functions § Example: def white(): print(" #" * 8) def black(): print("# " * 8) def all(): white(); black(); white(); black() white(); black(); white(); black() all()

June 2009 28

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

slide-29
SLIDE 29

Parameters and Arguments

§ we have seen functions that need arguments: § math.sqrt(x) computes square root of x § math.log(x, base) computes logarithm of x w.r.t. base § arguments are assigned to parameters of the function § Example: def pythagoras(): c = math.sqrt(a**2+b**2) print("Result:", c) a = 3; b = 4; pythagoras() a = 7; b = 15; pythagoras()

June 2009 29

slide-30
SLIDE 30

Parameters and Arguments

§ we have seen functions that need arguments: § math.sqrt(x) computes square root of x § math.log(x, base) computes logarithm of x w.r.t. base § arguments are assigned to parameters of the function § Example: def pythagoras(a, b): c = math.sqrt(a**2+b**2) print("Result:", c) a = 3; b = 4; pythagoras(a, b) a = 7; b = 15; pythagoras(a, b)

June 2009 30

slide-31
SLIDE 31

Parameters and Arguments

§ we have seen functions that need arguments: § math.sqrt(x) computes square root of x § math.log(x, base) computes logarithm of x w.r.t. base § arguments are assigned to parameters of the function § Example: def pythagoras(a, b): c = math.sqrt(a**2+b**2) print("Result:", c) pythagoras(3, 4) pythagoras(7, 15)

June 2009 31

slide-32
SLIDE 32

Parameters and Arguments

§ we have seen functions that need arguments: § math.sqrt(x) computes square root of x § math.log(x, base) computes logarithm of x w.r.t. base § arguments are assigned to parameters of the function § Example: def pythagoras(a, b): c = math.sqrt(a**2+b**2) print("Result:", c) pythagoras(3, 4) pythagoras(2**3-1, 2**4-1)

June 2009 32

slide-33
SLIDE 33

Parameters and Arguments

§ we have seen functions that need arguments: § math.sqrt(x) computes square root of x § math.log(x, base) computes logarithm of x w.r.t. base § arguments are assigned to parameters of the function § Example: def pythagoras(a, b): c = math.sqrt(a**2+b**2) print("Result:", c) pythagoras(3, 4) x = 2**3-1; y = 2**4-1 pythagoras(x, y)

June 2009 33

slide-34
SLIDE 34

Variables are Local

§ parameters and variables are local § local =

  • nly available in the function defining them

§ Example: in module math: def sqrt(x): … in our program: def pythagoras(a, b): c = math.sqrt(a**2+b**2) print("Result:", c) x = 3; y =4; pythagoras(x, y)

June 2009 34

x local to math.sqrt a local to pythagora s b local to pythagora s c local to pythagora s x,y local to __main__

slide-35
SLIDE 35

Stack Diagrams

__main__ pythagoras math.sqrt

June 2009 35

x

è

3 y

è

4 a

è

3 b

è

4 x

è

25

slide-36
SLIDE 36

Tracebacks

§ stack structure printed on runtime error § Example: def broken(x): print(x / 0) def caller(a, b): broken(a**b) caller(2,5)

June 2009 36

Traceback (most recent call last): File "test.py", line 5, in <module> caller(2,5) File "test.py", line 4, in caller broken(a**b) File "test.py", line 2, in broken print(x/0) ZeroDivisionError: integer division or modulo by zero

slide-37
SLIDE 37

Return Values

§ we have seen functions that return values: § math.sqrt(x) returns the square root of x § math.log(x, base) returns the logarithm of x w.r.t. base § What is the return value of our function pythagoras(a, b)? § special value None returned, if no return value given (void) § declare return value using return statement: return <expr> § Example: def pythagoras(a, b): c = math.sqrt(a**2+b**2) return c print(pythagoras(3, 4))

June 2009 37

slide-38
SLIDE 38

Motivation for Functions

§ functions give names to blocks of code § easier to read § easier to debug § avoid repetition § easier to make changes § functions can be debugged separately § easier to test § easier to find errors § functions can be reused (for other programs) § easier to write new programs

June 2009 38

slide-39
SLIDE 39

Debugging Function Definitions

§ make sure you are using latest files (save, then run python -i) § biggest problem for beginners is indentation § all lines on the same level must have the same indentation § mixing spaces and tabs is very dangerous § try to use only spaces – a good editor helps! § do not forget to use “:” at end of first line § indent body of function definition by e.g. 4 spaces

June 2009 39

slide-40
SLIDE 40

June 2009 40

slide-41
SLIDE 41

TURTLE GRAPHICS & INTERFACE DESIGN

June 2009 41

slide-42
SLIDE 42

Turtle Module

§ available in most Python distributions § easy to use (although requires some faith at the moment) § can be imported using import turtle § t = turtle.Turtle() creates new turtle t § turtle.mainloop() can be used at the end of the program § two basic commands to the turtle § t.fd(x) advances turtle t by x units § t.lt(x) turns turtle t x degrees to the left

June 2009 42

slide-43
SLIDE 43

Simple Repetition

§ drawing a square by e.g. 4x drawing a line and turning left t.fd(100); t.lt(90); t.fd(100); t.lt(90); t.fd(100); t.lt(90); t.fd(100); t.lt(90) § simple repetition using for-loop for <var> in range(<expr>): <instr1>; <instr2> § Example: for i in range(4): print(i)

June 2009 43

slide-44
SLIDE 44

Simple Repetition

§ drawing a square by e.g. 4x drawing a line and turning left t.fd(100); t.lt(90); t.fd(100); t.lt(90); t.fd(100); t.lt(90); t.fd(100); t.lt(90) § simple repetition using for-loop for <var> in range(<expr>): <instr1>; <instr2> § Example: for i in range(4): t.fd(100) t.lt(90)

June 2009 44

slide-45
SLIDE 45

Encapsulation

§ Idea: wrap up a block of code in a function § documents use of this block of code § allows reuse of code by using parameters § Example: def square(t): for i in range(4): t.fd(100) t.lt(90) square(t) u = turtle.Turtle(); u.rt(90); u.fd(10); u.lt(90); square(u)

June 2009 45

slide-46
SLIDE 46

Generalization

§ square(t) can be reused, but size of square is fixed § Idea: generalize function by adding parameters § more flexible functionality § more possibilities for reuse § Example 1: def square(t, length): for i in range(4): t.fd(length) t.lt(90) square(t, 100) square(t, 50)

June 2009 46

slide-47
SLIDE 47

Generalization

§ Example 2: replace square by regular polygon with n sides def square(t, length): for i in range(4): t.fd(length) t.lt(90)

June 2009 47

slide-48
SLIDE 48

Generalization

§ Example 2: replace square by regular polygon with n sides def polygon(t, length): for i in range(4): t.fd(length) t.lt(90)

June 2009 48

slide-49
SLIDE 49

Generalization

§ Example 2: replace square by regular polygon with n sides def polygon(t, n, length): for i in range(n): t.fd(length) t.lt(90)

June 2009 49

slide-50
SLIDE 50

Generalization

§ Example 2: replace square by regular polygon with n sides def polygon(t, n, length): for i in range(n): t.fd(length) t.lt(360/n)

June 2009 50

slide-51
SLIDE 51

Generalization

§ Example 2: replace square by regular polygon with n sides def polygon(t, n, length): angle = 360/n for i in range(n): t.fd(length) t.lt(angle)

June 2009 51

slide-52
SLIDE 52

Generalization

§ Example 2: replace square by regular polygon with n sides def polygon(t, n, length): angle = 360/n for i in range(n): t.fd(length) t.lt(angle) polygon(t, 4, 100) polygon(t, 6, 50)

June 2009 52

slide-53
SLIDE 53

Generalization

§ Example 2: replace square by regular polygon with n sides def polygon(t, n, length): angle = 360/n for i in range(n): t.fd(length) t.lt(angle) polygon(t, n=4, length=100) polygon(t, n=6, length=50)

June 2009 53

slide-54
SLIDE 54

Generalization

§ Example 2: replace square by regular polygon with n sides def polygon(t, n, length): angle = 360/n for i in range(n): t.fd(length) t.lt(angle) square(t, 100)

June 2009 54

slide-55
SLIDE 55

Generalization

§ Example 2: replace square by regular polygon with n sides def polygon(t, n, length): angle = 360/n for i in range(n): t.fd(length) t.lt(angle) def square(t, length): polygon(t, 4, length) square(t, 100)

June 2009 55

slide-56
SLIDE 56

Interface Design

§ Idea: interface = parameters + semantics + return value § should be general (= easy to reuse) § but as simple as possible (= easy to read and debug) § Example: def circle(t, r): circumference = 2*math.pi*r n = 10 length = circumference / n polygon(t, n, length) circle(t, 10) circle(t, 100)

June 2009 56

slide-57
SLIDE 57

Interface Design

§ Idea: interface = parameters + semantics + return value § should be general (= easy to reuse) § but as simple as possible (= easy to read and debug) § Example: def circle(t, r, n): circumference = 2*math.pi*r # n = 10 length = circumference / n polygon(t, n, length) circle(t, 10, 10) circle(t, 100, 40)

June 2009 57

slide-58
SLIDE 58

Interface Design

§ Idea: interface = parameters + semantics + return value § should be general (= easy to reuse) § but as simple as possible (= easy to read and debug) § Example: def circle(t, r): circumference = 2*math.pi*r n = int(circumference // 3) + 1 length = circumference / n polygon(t, n, length) circle(t, 10) circle(t, 100)

June 2009 58

slide-59
SLIDE 59

Refactoring

§ we want to be able to draw arcs § Example: def arc(t, r, angle): arc_length = 2*math.pi*r*angle/360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = float(angle) / n for i in range(n): t.fd(step_length) t.lt(step_angle)

June 2009 59

slide-60
SLIDE 60

Refactoring

§ we want to be able to draw arcs § Example: def arc(t, r, angle): arc_length = 2*math.pi*r*angle/360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = float(angle) / n def polyline(t, n, length, angle): for i in range(n): t.fd(length) t.lt(angle)

June 2009 60

slide-61
SLIDE 61

Refactoring

§ we want to be able to draw arcs § Example: def arc(t, r, angle): arc_length = 2*math.pi*r*angle/360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = float(angle) / n polyline(t, n, step_length, step_angle) def polyline(t, n, length, angle): for i in range(n): t.fd(length) t.lt(angle)

June 2009 61

slide-62
SLIDE 62

Refactoring

§ we want to be able to draw arcs § Example: def polyline(t, n, length, angle): for i in range(n): t.fd(length) t.lt(angle)

June 2009 62

slide-63
SLIDE 63

Refactoring

§ we want to be able to draw arcs § Example: def polyline(t, n, length, angle): for i in range(n): t.fd(length) t.lt(angle) def polygon(t, n, length): angle = 360/n polyline(t, n, length, angle):

June 2009 63

slide-64
SLIDE 64

Refactoring

§ we want to be able to draw arcs § Example: def arc(t, r, angle): arc_length = 2*math.pi*r*angle/360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = float(angle) / n polyline(t, n, step_length, step_angle)

June 2009 64

slide-65
SLIDE 65

Refactoring

§ we want to be able to draw arcs § Example: def arc(t, r, angle): arc_length = 2*math.pi*r*angle/360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = float(angle) / n polyline(t, n, step_length, step_angle) def circle(t, r): arc(t, r, 360)

June 2009 65

slide-66
SLIDE 66

Simple Iterative Development

§ first structured approach to develop programs:

  • 1. write small program without functions
  • 2. encapsulate code in functions
  • 3. generalize functions (by adding parameters)
  • 4. repeat steps 1–3 until functions work
  • 5. refactor program (e.g. by finding similar code)

§ copy & paste helpful § reduces amount of typing § no need to debug same code twice

June 2009 66

slide-67
SLIDE 67

Debugging Interfaces

§ interfaces simplify testing and debugging

  • 1. test if pre-conditions are given:

§ do the arguments have the right type? § are the values of the arguments ok?

  • 1. test if the post-conditions are given:

§ does the return value have the right type? § is the return value computed correctly?

  • 1. debug function, if pre- or post-conditions violated

June 2009 67

slide-68
SLIDE 68

GETTING YOUR HANDS DIRTY

June 2009 68

slide-69
SLIDE 69

Programming by Checklist J

  • 1. Do you have an editor installed? (Preferably with syntax

highlighting!)

  • 2. Do you have a Python distribution installed?
  • 3. Test the following programs:

a. print("My name is Slartibartfast!")

  • b. import turtle; t = turtle.Turtle()

for i in range(4): t.fd(10); t.lt(270) c. import turtle; t = turtle.Turtle() list(map(lambda x:(t.fd(5*x),t.lt(120)),range(20)))

  • 4. Extend to a meaningful program and save it !

June 2009 69