Presentation is loading. Please wait.

Presentation is loading. Please wait.

Subroutines in Python Computers and Programming

Similar presentations


Presentation on theme: "Subroutines in Python Computers and Programming"— Presentation transcript:

1 Subroutines in Python 01204111 Computers and Programming
Chalermsak Chatdokmaiprai Department of Computer Engineering Kasetsart University Revised

2 First is a good news! In Python, a subroutine is called a function.
And Python functions work essentially the same as Mathematical functions (sin, cos, log, factorial, etc). And you have learned how to define and use Mathematical functions for a long, long time!

3 An expression is evaluated to an object
Program's storage x = 3 Global Frame Objects 2 y = 2*x-1 x 3 1 6 x = 'idle' y 5 2 z z = y 'idle' 7 10 y = y+2 0.7 2 print(y/10*2) 1.4 1.4 output

4 A function call is also an expression
Program's storage from math import factorial Global Frame Objects 3 2 6 x1 = 3*2*1-1 x1 5 1 3 x2 = factorial(3)-1 x2 factorial() 5 1 But function calls are more flexible in use than other forms of expressions. 6 y + (|4!–z|!) y = 20*factorial(x1) z = factorial(3+x2%2) print(y + factorial(abs(factorial(4)-z)))

5 No difference in use between "their functions" and "my own functions"
x = 5 y = 20*factorial(x) z = factorial(3+x%2) print(y+factorial(abs(factorial(4)-z))) from math import factorial Someone wrote it. We import and use it. def factorial(n): # returns n! result = 1 while n >= 2: result = result*n n = n-1 return result x = 5 y = 20*factorial(x) z = factorial(3+x%2) print(y+factorial(abs(factorial(4)-z))) We write it ourselves and proudly use it.

6 A demo of function defining and calling mechanism
The whole function definition is just a single Python statement that defines a function object (named sqr) Just like an assignment x = 2 def sqr(x): # returns the square of x result = x*x return result y = sqr(2) print(y, sqr(y-10)) Just like an assignment x = y-10 Run this program at

7 A demo of function defining and calling mechanism
This shorter version works effectively the same. def sqr(x): # returns the square of x return x*x y = sqr(2) print(y, sqr(y-10)) Because any expression can follow return Run this program at

8 Global Scope VS Local Scope
def sqr(x): # returns the square of x result = x*x return result x = sqr(2) print(x, sqr(x-10)) All y's in the main routine are changed to x. Does it run differently from the previous program? Why? Run this program at

9 Lab 04: Task 01: Example 1: Global Variables
def func1(): print(f"Inside func1(): x is {x}") x = 10 print(f"Before calling func1(): x is {x}") func1() print(f"After calling func1(): x is {x}") The variable x is created here and has global scope. Run this program at

10 Lab 04: Task 01: Example 1: Global Variables
print(f"Before calling func1(): x is {x}") def func1(): print(f"Inside func1(): x is {x}") func1() print(f"After calling func1(): x is {x}") It's OK to place the definition of func1 here because func1 is defined before it is called. Run this program at Where do you think is not OK to place the definition of func1?

11 Lab 04: Task 01: Example 2: Local Variables
def func2(): x = 50 # local variable x print(f"Inside func2(): x is {x}") x = 10 print(f"Before calling func2(): x is {x}") func2() print(f"After calling func2(): x is {x}") Run this program at

12 Run this program at http://pythontutor.com
Lab 04: Task 01: Example 3: Reference to a local variable before assignment def func3(): print(f"Inside func3(): x is {x}") x = 50 x = 10 print(f"Before calling func3(): x is {x}") func3() print(f"After calling func3(): x is {x}") Which x? Run this program at

13 Lab 04: Task 01: Example 4: Parameters are local
When func4() is called, parameter x behaves just like a local variable that has already been assigned a value. Unlike the previous example, there is no error here because x has been assigned. def func4(x): print(f"Inside func4(): x is {x}") x = 80 x = 10 print(f"Before calling func4(): x is {x}") func4(50) print(f"After calling func4(): x is {x}") Just like an assignment x = 50 Run this program at

14 Returning Multiple Values
import math def read_cylinder(): radius = float(input("cylinder's radius? ")) height = float(input("cylinder's height? ")) return radius, height r, h = read_cylinder() volume = math.pi*r*r*h print(f"Its volume is {volume:.2f}") Run this program at

15 Chained Calls: Calling a function that calls a function that calls a function that …
import math def cir_area(r): return math.pi*r*r >>> cir_area(2.1) >>> cir_area(1) def cyl_volume(r, h): vol = cir_area(r) * h return vol >>> cyl_volume(2, 3) >>> cyl_volume(1, 2)

16 Run this program at http://pythontutor.com
Chained Calls: Calling a function that calls a function that calls a function that … import math def read_cylinder(): radius = float(input("cylinder's radius? ")) height = float(input("cylinder's height? ")) return radius, height def cyl_volume(r, h): vol = cir_area(r) * h return vol def cir_area(r): return math.pi*r*r r, h = read_cylinder() volume = cyl_volume(r, h) print(f"Its volume is {volume:.2f}") Run this program at

17 Task: Finding the area of a trapezoid
A trapezoid is a convex quadrilateral with at least one pair of parallel sides. The area of a trapezoid can be calculated by the following formula: ref: a b h 𝑎𝑟𝑒𝑎= 𝑎+𝑏 2 ×ℎ Write a Python function trapezoid_area(a, b, h) that computes and returns the area of a trapezoid with a and b as the lengths of parallel sides, and h as the height.

18 Trapezoid Area – Python function
def trapezoid_area(a, b, h): """returns the area of a trapezoid where a and b are lengths of its parallel sides, and h is its height """ return 0.5*(a+b)*h >>> trapezoid_area(3, 2, 1) 2.5 >>> trapezoid_area(1.1, 2.2, 3.3) 5.445 >>>>>> help(trapezoid_area) Help on function trapezoid_area in module __main__: trapezoid_area(a, b, h) returns the area of a trapezoid where a and b are lengths of its parallel sides, and h is its height Test the function Use the help() function to display the docstring.

19 These arguments are called positional arguments
def trapezoid_area(a, b, h): """returns the area of a trapezoid where a and b are lengths of its parallel sides, and h is its height """ return 0.5*(a+b)*h We have, so far, passed arguments in the same order as that of the parameters >>> trapezoid_area(1.1, 2.2, 3.3) 5.445 These arguments are called positional arguments

20 Named Arguments (or Keyword Arguments)
def trapezoid_area(a, b, h): """returns the area of a trapezoid where a and b are lengths of its parallel sides, and h is its height """ return 0.5*(a+b)*h If we don't want to remember the order of the parameters (but we know their names), we can pass arguments using parameter names. >>> trapezoid_area(a=1, h=3, b=2) 4.5 >>> trapezoid_area(h=3, b=2, a=1) >>> x = 1 >>> y = 10 >>> trapezoid_area(b=y/5, a=x, h=y*x-7) These arguments are called named (or keyword) arguments Arguments can be any expressions as usual. Arguments can be any expressions as usual. Arguments can be any expressions as usual.

21 Enough for Pythonic things, Back to problem solving and programming:
Subroutines give rise to a powerful technique of constructing programs: Top-down Design Let's see some example of this.

22 Task: Finding Area of a Triangle
Write a program that reads XY coordinates of the three vertices of a triangle, then calculates and prints the area of the triangle in 4 decimal places. Enter XY coordinates of the three vertices: 1st vertex: x? 3 y? 1.5 2nd vertex: x? 0 y? 2 3rd vertex: x? 4.5 y? 6 Area of the triangle is >>> We want the program to run like this.

23 Finding Triangle Area - Idea
Heron's formula, named after Heron of Alexandria (10AD-70AD), calculates the area of a triangle from the three side lengths. Heron's formula states that the area of a triangle whose side lengths are a, b, and c is where s is the semiperimeter of the triangle: 𝑎𝑟𝑒𝑎= 𝑠(𝑠−𝑎)(𝑠−𝑏)(𝑠−𝑐) 𝑠= 𝑎+𝑏+𝑐 2

24 Length of the line joining 2 points
Example

25 Welcome to the ease and the power of
Top-down Design

26 Finding triangle area – Topmost Level
Algorithm of the main routine is simple: Read coordinates of the 3 vertices (x1,y1), (x2,y2), (x3,y3) Compute the triangle's area Print out the triangle's area translated into Python # --- main --- # x1, y1, x2, y2, x3, y3 = read_triangle() area = triangle_area(x1, y1, x2, y2, x3, y3) print(f"Area of the triangle is {area:.4f}") The function triangle_area() will do the calculation.

27 the subroutine call tree.
What we've done so far Done! main read_triangle triangle_area This schema is called the subroutine call tree.

28 read_triangle() – reads the three vertices
Algorithm of read_triangle() is simple: Read coordinates of the 1st vertex (x1, y1) Read coordinates of the 2nd vertex (x2, y2) Read coordinates of the 3rd vertex (x3, y3) Return (x1, y1), (x2, y2), (x3, y3) translated into Python def read_triangle(): """reads XY co-ordinates of 3 vertices of a triangle """ print("Enter XY coordinates of the three vertices:") x1, y1 = read_coordinates("1st vertex:") x2, y2 = read_coordinates("2nd vertex:") x3, y3 = read_coordinates("3rd vertex:") return x1, y1, x2, y2, x3, y3 read_coordinates() reads one vertex.

29 What we’ve done so far main read_triangle triangle_area
read_coordinates

30 read_coordinates() reads coordinates of a vertex
Algorithm of read_coordinates() is simple: Print a prompt message Read x Read y Return (x, y) translated into Python def read_coordinates(msg): print(msg) x = float(input("x? ")) y = float(input("y? ")) return x, y

31 What we’ve done so far main read_triangle triangle_area
read_coordinates

32 triangle_area() given 3 vertices, compute the triangle area
Algorithm of triangle_area() is simple: Get the 3 vertices (x1, y1), (x2, y2), (x3, y3) as parameters Calculate the three side lengths a, b, and c Calculate the semiperimeter s Use Heron's formula to calculate the area of the triangle Return the area of the triangle translated into Python def triangle_area(x1, y1, x2, y2, x3, y3): a = line_length(x1, y1, x2, y2) b = line_length(x2, y2, x3, y3) c = line_length(x3, y3, x1, y1) s = (a+b+c)/2 return math.sqrt(s*(s-a)*(s-b)*(s-c)) Master Heron in action here. to be imported

33 What we’ve done so far main read_triangle triangle_area
read_coordinates line_length

34 translated into Python
line_length() given two points, compute the length of the line joining them Algorithm of line_length() is simple: Get two points (x1, y1) and (x2, y2) as parameters Calculate the length of line joining the two points, using the formula: Return the length of the line translated into Python def line_length(x1, y1, x2, y2): """Given XY coordiates of 2 points, return the line length that joins them """ return math.sqrt((x1-x2)**2+(y1-y2)**2);

35 What we’ve done so far main read_triangle triangle_area
read_coordinates line_length

36 Putting them all together:
Done! Putting them all together: import math def read_triangle(): print("Enter XY coordinates of the three vertices:") x1, y1 = read_coordinates("1st vertex:") x2, y2 = read_coordinates("2nd vertex:") x3, y3 = read_coordinates("3rd vertex:") return x1, y1, x2, y2, x3, y3 def read_coordinates(msg): print(msg) x = float(input("x? ")) y = float(input("y? ")) return x, y def triangle_area(x1, y1, x2, y2, x3, y3): a = line_length(x1, y1, x2, y2) b = line_length(x2, y2, x3, y3) c = line_length(x3, y3, x1, y1) s = (a+b+c)/2 return math.sqrt(s*(s-a)*(s-b)*(s-c)) def line_length(x1, y1, x2, y2): return math.sqrt((x1-x2)**2+(y1-y2)**2); # --- main --- # x1, y1, x2, y2, x3, y3 = read_triangle() area = triangle_area(x1, y1, x2, y2, x3, y3) print(f"Area of the triangle is {area:.4f}")

37 many simple parts cleverly put together to do wonders.
Words of wisdom A complex task is composed of many simple parts cleverly put together to do wonders.

38 An important problem-solving technique
Therefore when confronted with a complex task, break it up into several simple parts and deal with them one by one. Then compose them up together to solve the original task.

39 The End

40 Major Revision History
Feb 13, 2018 – Chalermsak Chatdokmaiprai First release Constructive comments or error reports on this set of slides would be welcome and highly appreciated. Please contact


Download ppt "Subroutines in Python Computers and Programming"

Similar presentations


Ads by Google