DM536 Introduction to Programming. Peter Schneider-Kamp.

Similar documents
DM502 Programming A. Peter Schneider-Kamp.

DM536 Introduction to Programming. Peter Schneider-Kamp.

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

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

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM502 Programming A. Peter Schneider-Kamp.

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

Conditionals and Recursion. Python Part 4

DM503 Programming B. Peter Schneider-Kamp.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Control Flow: Loop Statements

CS 1301 CS1 with Robots Summer 2007 Exam 1

Conditionals: Making Choices

Functions and Recursion

Python Boot Camp. Day 3

Python, Part 2 CS 8: Introduction to Computer Science Lecture #4

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

CS100: CPADS. Decisions. David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania

RECURSION: n. SEE RECURSION 3

How to Design Programs

Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

Pupil Name. Year. Teacher. Target Level. Key Stage 3 Self-Assessment Year 9 Python. Spelling Test No 3. Spelling Test No 2. Spelling Test No 1

DM550 Introduction to Programming part 2. Jan Baumbach.

Introduction to Computer Programming for Non-Majors

Test #2 October 8, 2015

Lecture Notes: CS 2370: Intro Programming Lecture Notes - Student Version

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Control Structures 1 / 17

Text Input and Conditionals

RECURSION 3. 1 Recursion COMPUTER SCIENCE 61A. June 30, 2016

Statements 2. a operator= b a = a operator b

Conditional Expressions and Decision Statements

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

CONTROL AND HIGHER ORDER FUNCTIONS 1

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Compound Data Types 1

Accelerating Information Technology Innovation

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

DM550 Introduction to Programming part 2. Jan Baumbach.

Section 10.1 Polar Coordinates

Flow of execution! The flow of execution is the order in which program statements are executed.

Chapter 8. Statement-Level Control Structures

Basics of Programming with Python

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

ENVIRONMENT DIAGRAMS AND RECURSION 2

DM502 Programming A. Peter Schneider-Kamp.

cs1114 REVIEW of details test closed laptop period

Intro. Scheme Basics. scm> 5 5. scm>

Chapter 8. Statement-Level Control Structures

Chapter 1. Fundamentals of Higher Order Programming

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

RETURN X return X Returning a value from within a function: computes the value of variable exits the function and returns the value of the variable

Control structure: Repetition - Part 2

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

CS1 Lecture 5 Jan. 26, 2018

A Brief Introduction to Scheme (I)

The SPL Programming Language Reference Manual

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

CONTROL AND HIGHER ORDER FUNCTIONS 2

Introduction to Computer Programming for Non-Majors

Accelerating Information Technology Innovation

Python Programming: An Introduction to Computer Science

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Python Programming: An Introduction to Computer Science

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

ENGR 102 Engineering Lab I - Computation

Introduction to Computer Programming for Non-Majors

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

CS1 Lecture 5 Jan. 25, 2019

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

PREPARING FOR PRELIM 1

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration

RECURSION, RECURSION, (TREE) RECURSION! 2

Control flow statements

MEIN 50010: Python Flow Control

QUark Language Reference Manual

1 Lexical Considerations

Lecture #3: Recursion

Module 8: Local and functional abstraction

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

Lecture #3: Recursion

Chapter 2 Writing Simple Programs

DM536 Programming A. Peter Schneider-Kamp.

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

Control of Flow. There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests.

An introduction to Scheme

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Python for Informatics

CS1102: Macros and Recursion

Module 10: Imperative Programming, Modularization, and The Future

Structure of Programming Languages Lecture 5

Problem 1 (a): List Operations

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Transcription:

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

TURTLE WORLD & INTERFACE DESIGN 2

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 3

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 4

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 27

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 28

CONDITIONAL EXECUTION 29

Boolean Expressions expressions whose value is either True or False logic operators for computing with Boolean values: x and y True if, and only if, x is True and y is True x or y True if (x is True or y is True) not x True if, and only if, x is False Python also treats numbers as Boolean expressions: 0 False any other number True Please, do NOT use this feature! 30

Relational Operators relational operators are operators, whose value is Boolean important relational operators are: Example True Example False x < y 23 < 42 "World" < "Hej!" x <= y 42 <= 42.0 int(math.pi) <= 2 x == y 42 == 42.0 type(2) == type(2.0) x >= y 42 >= 42 "Hej!" >= "Hello" x > y "World" > "Hej!" 42 > 42 remember to use == instead of = (assignment)! 31

Conditional Execution the if-then statement executes code only if a condition holds grammar rule: <if-then> => if <cond>: <instr 1 >; ; <instr k > Example: if x <= 42: print "not more than the answer" if x > 42: print "sorry - too much!" 32

Control Flow Graph Example: if x <= 42: print "not more than the answer" if x > 42: print "sorry - too much!" x <= 42 False x > 42 False True True print "not more " print "sorry - too " 33

Alternative Execution the if-then-else statement executes one of two code blocks grammar rule: <if-then-else> => if <cond>: <instr 1 >; ; <instr k > else: <instr 1 >; ; <instr k > Example: if x <= 42: print "not more than the answer" else: print "sorry - too much!" 34

Control Flow Graph Example: if x <= 42: print "not more than the answer" else: print "sorry - too much!" x <= 42 False True print "not more " print "sorry - too " 35

Chained Conditionals alternative execution a special case of chained conditionals grammar rules: <if-chained> => if <cond 1 >: <instr 1,1 >; ; <instr k1,1 > elif <cond 2 >: else: Example: if x > 0: print "positive" elif x < 0: print "negative" else: print "zero" <instr 1,m >; ; <instr km,m > 36

Control Flow Diagram Example: if x > 0: print "positive" elif x < 0: print "negative" else: print "zero" False x > 0 x < 0 True True False print "positive" print "negative" print "zero" 37

Nested Conditionals conditionals can be nested below conditionals: x = input() y = input() if x > 0: if y > 0: print "Quadrant 1" elif y < 0: print "Quadrant 4" else: print "positive x-axis" elif x < 0: if y > 0: print "Quadrant 2" elif y < 0: print "Quadrant 3" else: print "negative x-axis" else: print "y-axis" 38

RECURSION 39

Recursion a function can call other functions a function can call itself such a function is called a recursive function Example 1: def countdown(n): if n <= 0: print "Ka-Boooom!" else: print n, "seconds left!" countdown(n-1) countdown(3) 40

Stack Diagrams for Recursion main countdown n è 3 countdown n è 2 countdown n è 1 countdown n è 0 41

Recursion a function can call other functions a function can call itself such a function is called a recursive function Example 2: def polyline(t, n, length, angle): for i in range(n): fd(t, length) lt(t, angle) 42

Recursion a function can call other functions a function can call itself such a function is called a recursive function Example 2: def polyline(t, n, length, angle): if n > 0: fd(t, length) lt(t, angle) polyline(t, n-1, length, angle) 43

Infinite Recursion base case = no recursive function call reached we say the function call terminates Example 1: n == 0 in countdown / polyline infinite recursion = no base case is reached also called non-termination Example: def infinitely_often(): infinitely_often() Python has recursion limit 1000 ask sys.getrecursionlimit() 44

Keyboard Input so far we only know input() what happens when we enter Hello? input() treats all input as Python expression <expr> for string input, use raw_input() what happens when we enter 42? raw_input() treats all input as string both functions can take one argument prompt Example 1: a = input("first side: ") Example 2: name = raw_input("your name:\n") \n denotes a new line: print "Hello\nWorld\n!" 45

Debugging using Tracebacks error messages in Python give important information: where did the error occur? what kind of error occurred? unfortunately often hard to localize real problem Example: real problem error reported def determine_vat(base_price, vat_price): factor = base_price / vat_price reverse_factor = 1 / factor return reverse_factor - 1 print determine_vat(400, 500) 46

Debugging using Tracebacks error messages in Python give important information: where did the error occur? what kind of error occurred? unfortunately often hard to localize real problem Example: def determine_vat(base_price, vat_price): factor = float(base_price) / vat_price reverse_factor = 1 / factor return reverse_factor - 1 print determine_vat(400, 500) 47

FRUITFUL FUNCTIONS 48

Return Values so far we have seen only functions with one or no return sometimes more than one return makes sense Example 1: def sign(x): if x < 0: return -1 elif x == 0: return 0 else: return 1 49