DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

Similar documents
DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM502 Programming A. Peter Schneider-Kamp.

Built-in Types of Data

Python. Olmo Zavala R. Python Exercises. Center of Atmospheric Sciences, UNAM. August 24, 2016

Programming for Engineers in Python. Recitation 2

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

Programming for Engineers in Python. Recitation 3 Functions

Functions. Systems Programming Concepts

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

DM502 Programming A. Peter Schneider-Kamp.

Chap 6 Function Define a function, which can reuse a piece of code, just with a few different values.

Module 01: Introduction to Programming in Python

1001ICT Introduction To Programming Lecture Notes

High Level Scripting. Gino Tosti University & INFN Perugia. 06/09/2010 SciNeGhe Data Analysis Tutorial

Introduction to Programming

Computational Physics

Programming for Engineers in Python. Recitation 3

Object-Based Programming. Programming with Objects

Methods: A Deeper Look

DM503 Programming B. Peter Schneider-Kamp.

C Functions. 5.2 Program Modules in C

DM536 Introduction to Programming. Peter Schneider-Kamp.

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Variables. location where in memory is the information stored type what sort of information is stored in that memory

Downloaded from Chapter 2. Functions

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Getting Started Values, Expressions, and Statements CS GMU

Lab 7: Reading Files, Importing, Bigram Function. Ling 1330/2330: Computational Linguistics Na-Rae Han

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Mentor Graphics Predefined Packages

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Excel R Tips. is used for multiplication. + is used for addition. is used for subtraction. / is used for division

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Functions with Parameters and Return Values

CT 229 Java Syntax Continued

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

ECET 264 C Programming Language with Applications

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 Introduction to Programming part 2. Jan Baumbach.

The return Statement

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

PyCUDA. Continued...

Chapter 3 Mathematical Functions, Strings, and Objects

Fixed point algorithmic math package user s guide By David Bishop

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

>>> * *(25**0.16) *10*(25**0.16)

Single row numeric functions

Script started on Thu 25 Aug :00:40 PM CDT

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

C Programs: Simple Statements and Expressions

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Numerical Modelling in Fortran: day 2. Paul Tackley, 2017

4. Modules and Functions

Computing and Statistical Data Analysis Lecture 3

JUN / 04 VERSION 7.0

Chapter 3 - Functions

Variable and Data Type 2

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Problem 1 (a): List Operations

LAB 7 FUNCTION PART 2

COMP1730/COMP6730 Programming for Scientists. Functions

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in 1 of 29 Thursday 16 October :50 PM

MATLAB Constants, Variables & Expression. 9/12/2015 By: Nafees Ahmed

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

CSE123. Program Design and Modular Programming Functions 1-1

By the end of this section of the practical, the students should be able to:

Subroutines I Computers and Programming

Python. Objects. Geog 271 Geographic Data Analysis Fall 2010

Here n is a variable name. The value of that variable is 176.

MaSH Environment nxt. Contents

Dr Richard Greenaway

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

SECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING

LAB 1 General MATLAB Information 1

FUNCTION PARAMETER AND ARGUMENT

Functions and Recursion

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

CS110: PROGRAMMING LANGUAGE I

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Scheme Quick Reference

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

Chapter 5 C Functions

Arithmetic and Logic Blocks

Using Free Functions

Chapter 7. Iteration. 7.1 Multiple assignment

Com S 127 Lab 2. For the first two parts of the lab, start up Wing 101 and use the Python shell window to try everything out.

CS 1301 CS1 with Robots Summer 2007 Exam 1

Basic types and definitions. Chapter 3 of Thompson

A. Matrix-wise and element-wise operations

Transcription:

DM536 / DM550 Part 1 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/!

CALLING FUNCTIONS 2

Calling Functions so far we have seen three 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 in general, a function call is also an expression: <expr> => <function>(<arg 1 >,, <arg n >) Example 1: x = input() print type(x) Example 2: from math import log print log(4398046511104, 2) 3

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 cos floor log sin asin cosh fmod log10 sinh atan degrees frexp modf sqrt atan2 exp hypot pow tan ceil fabs ldexp radians tanh access using math.<function> : c = math.sqrt(a**2+b**2) 4

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 5

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'>" 6

DEFINING FUNCTIONS 7

Function Definitions functions are defined using the following grammar rule: <func.def> => def <function>(<arg 1 >,, <arg n >): <instr 1 >; ; <instr k > 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) 8

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

Executing Programs (Revisited) Program stored in a file (source code file) Instructions in this file executed top-to-bottom Interpreter executes each instruction Source Code Interpreter Input Output 10

Functions Calling Functions functions can call other functions Example: def white(): print " #" * 8 create new function variable white def black(): print "# " * 8 def all(): all() white(); black(); white(); black() white(); black(); white(); black() 11

Functions Calling Functions functions can call other functions Example: def white(): print " #" * 8 create new function variable black def black(): print "# " * 8 def all(): all() white(); black(); white(); black() white(); black(); white(); black() 12

Functions Calling Functions functions can call other functions Example: def white(): print " #" * 8 create new function variable all def black(): print "# " * 8 def all(): all() white(); black(); white(); black() white(); black(); white(); black() 13

Functions Calling Functions functions can call other functions Example: def white(): print " #" * 8 call function all def black(): print "# " * 8 def all(): all() white(); black(); white(); black() white(); black(); white(); black() 14

Functions Calling Functions functions can call other functions Example: def white(): print " #" * 8 call function white def black(): print "# " * 8 def all(): all() white(); black(); white(); black() white(); black(); white(); black() 15

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

Functions Calling Functions functions can call other functions Example: def white(): print " #" * 8 call function black def black(): print "# " * 8 def all(): all() white(); black(); white(); black() white(); black(); white(); black() 17

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

Functions Calling Functions functions can call other functions Example: def white(): print " #" * 8 call function white def black(): print "# " * 8 def all(): all() white(); black(); white(); black() white(); black(); white(); black() 19

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

Functions Calling Functions functions can call other functions Example: def white(): print " #" * 8 # # # # # # # #! # # # # # # # #! # # # # # # # #! # # # # # # # #! # # # # # # # #! # # # # # # # #! # # # # # # # #! # # # # # # # #!! def black(): print "# " * 8 def all(): all() white(); black(); white(); black() white(); black(); white(); black() 21

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() 22

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) 23

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) 24

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) 25

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) 26

Variables are Local parameters and variables are local local = only available in the function defining them Example: in module math: a local to pythagoras c local to pythagoras x,y local to main 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) x local to math.sqrt b local to pythagoras 27

Stack Diagrams main x è 3 y è 4 pythagoras a è 3 b è 4 math.sqrt x è 25 28

Tracebacks stack structure printed on runtime error Example: def broken(x): print x / 0 def caller(a, b): broken(a**b) caller(2,5) 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 29

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) 30

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 31

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 32

TURTLE WORLD & INTERFACE DESIGN 33

Turtle World available from http://www.greenteapress.com/thinkpython/swampy/install.html basic elements of the library can be imported using from swampy.turtleworld import * w = TurtleWorld() creates new world w t = Turtle() creates new turtle t wait_for_user() can be used at the end of the program 34

Simple Repetition two basic commands to the turtle fd(t, 100) advances turtle t by 100 lt(t) turns turtle t 90 degrees to the left drawing a square requires 4x drawing a line and turning left fd(t,100); lt(t); fd(t,100); lt(t); fd(t,100); lt(t); fd(t,100); lt(t) simple repetition using for-loop for <var> in range(<expr>): <instr 1 >; <instr 2 > Example: for i in range(4): print i 35

Simple Repetition two basic commands to the turtle fd(t, 100) advances turtle t by 100 lt(t) turns turtle t 90 degrees to the left drawing a square requires 4x drawing a line and turning left fd(t,100); lt(t); fd(t,100); lt(t); fd(t,100); lt(t); fd(t,100); lt(t) simple repetition using for-loop for <var> in range(<expr>): <instr 1 >; <instr 2 > Example: for i in range(4): fd(t, 100) lt(t) 36

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): fd(t, 100) lt(t) square(t) u = Turtle(); rt(u); fd(u,10); lt(u); square(u) 37

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): fd(t, length) lt(t) square(t, 100) square(t, 50) 38

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

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

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

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

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

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

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

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

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

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) 48

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) 49

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) 50

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): fd(t, step_length) lt(t, step_angle) 51

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): fd(t, length) lt(t, angle) 52

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): fd(t, length) lt(t, angle) 53

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

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

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) 56

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) 57

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 58

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? 2. test if the post-conditions are given: does the return value have the right type? is the return value computed correctly? 3. debug function, if pre- or post-conditions violated 59