Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions and subroutines 01204111 – Computer and Programming.

Similar presentations


Presentation on theme: "Functions and subroutines 01204111 – Computer and Programming."— Presentation transcript:

1 Functions and subroutines 01204111 – Computer and Programming

2 2 Do you know… None of the programming languages can provide all the specific commands that developers need. But many languages provide supports for user-defined commands, in the form of Functions

3 3 Thinking Corner Let's recall the functions that we have been using so far. Think about their goals, their inputs, and their outputs. function s inputsgoalsoutputs printAny expressions Shows the value of the expression to the console - inputA string or none Reads input from the userThe input as a string intA string or a number Converts the argument to an integer An integer floatA string or a number Converts the argument to a floating-point number A floating-point

4 4 Why build user- defined functions? This is a way to handle complexity of the problems: reduce a big task to many smaller ones. Reduce duplicate codes  For simpler maintainance Reduce the complexity of the main program  This makes it easier to read

5 5 Example: the area of a triangle Write a program that reads the length of the base and the height of a triangle and computes its area. Read the length of the base and the height of a triangle and compute its area Read the base length Read the height Compute the area Report the result Divided into smaller tasks

6 6 Major plan Read the base length Read the height Compute the area Report the result b = read_base() h = read_height() a = compute_area(b,h) show_area(a) b = read_base() h = read_height() a = compute_area(b,h) show_area(a)

7 7 โปรแกรมที่สมบูรณ์ def read_base(): b = input("Enter base: ") return int(b) def read_height(): h = input("Enter height: ") return int(h) def compute_area(base,height): return 0.5*base*height def show_area(area): print("Triangle area is", area) b = read_base() h = read_height() a = compute_area(b,h) show_area(a) def read_base(): b = input("Enter base: ") return int(b) def read_height(): h = input("Enter height: ") return int(h) def compute_area(base,height): return 0.5*base*height def show_area(area): print("Triangle area is", area) b = read_base() h = read_height() a = compute_area(b,h) show_area(a)

8 8 Defining a function in Python Parameters are optional. If a function needs more information, then parameters are required. Functions that have no return values do not need the return statement. def function_name ( parameters … ): : sequence of statements : return value (if any) def function_name ( parameters … ): : sequence of statements : return value (if any) Add the same indentation to show the block

9 9 Parameters A function can take more information. On its definition, we can list all parameters that it needs  Inside the function, parameters are variables that are initialized when the function is called. Thus the statement below that calls the function essential creates variables base and height that refer to 32 and 80 respectively.  These variables no longer exist after the function execution ends. def compute_area(base, height): return 0.5*base*height def compute_area(base, height): return 0.5*base*height compute_area(32,80) base32height80

10 10 Let's look closely at the definition Function name: compute_area Goal:  Compute the area of a triangle from the length of its base and its height. Parameters:  The base length, in parameter base  The height, in parameter height Return value: The area of the triangle def compute_area(base,height): return 0.5*base*height def compute_area(base,height): return 0.5*base*height

11 11 Thinking Corner Consider other functions on the previous example. Try to figure out various information of the them as in the previous slide.  Function names?  Goals?  Parameters?  Return values? def read_base(): : def read_height(): : def compute_area(base,height): : def show_area(area): : def read_base(): : def read_height(): : def compute_area(base,height): : def show_area(area): :

12 12 Notes The statements inside the function definition will not be executed inside the definition. They will be executed when the function is called. >>> print("Hello") Hello >>> def func():... print("hi") >>> >>> func() Hi >>> >>> print("Hello") Hello >>> def func():... print("hi") >>> >>> func() Hi >>> This "print" runs immediately. This "print" will not be executed here, because it is in the function definition. But when the function is called, the second "print" statement is executed.

13 13 Program flow print("Hello") def func1(): print("hi") def func2(): print("bye") func1() func2() func1() print("Hello") def func1(): print("hi") def func2(): print("bye") func1() func2() func1() 1 2 3 4 5 1. This "print" is not belongs to any function; therefore, it is executed normally. 2. Python see the "def " statements; therefore, it remembers the definitions of func1 and func2; both print functions shall not be executed here. 3. This is a call to func1. Now, the program execution jumps to the definition of function func1. 4. This is a call to func2. The program execution then jumps to the definition of function func2. 5. Same as 3

14 14 Example: the turtle & houses (1) We want to build a function build_house that asks the turtle to draw a house of a specific size. The function needs to parameters  turtle, for the turtle that will draw  size, for the size of the house size

15 15 Example: the turtle & houses (2) After some analysis, we see that to build a house, we need to subtasks:  Build the walls  Build the roof Therefore, we shall need two other functions:  build_walls --- for building walls  build_roof --- for building the roofs These functions shall be called by function build_house.

16 16 Teach the turtle to draw walls Note that we make sure that the direction of the turtle remains the same from the start. This is for the ease of designing the build_roof function later on. def build_walls(turtle,size): turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) def build_walls(turtle,size): turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) size

17 17 Teach the turtle to draw the roof def build_roof(turtle,size): # Since we know the turtle is facing right # we can tell the turtle to turn left # for drawing an equilateral triangle turtle.left(60) # and draw it turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(120) turtle.forward(size) # finally, we ask the turtle to return # to its starting direction turtle.right(180) def build_roof(turtle,size): # Since we know the turtle is facing right # we can tell the turtle to turn left # for drawing an equilateral triangle turtle.left(60) # and draw it turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(120) turtle.forward(size) # finally, we ask the turtle to return # to its starting direction turtle.right(180) size

18 18 Finally, the house! After we can draw the walls and the roof, we can easily teach the turtle to draw houses. def build_house(turtle,size): build_walls(turtle,size) build_roof(turtle,size) def build_house(turtle,size): build_walls(turtle,size) build_roof(turtle,size)

19 19 Full program from turtle import * def build_walls(turtle,size): turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) def build_roof(turtle,size): turtle.left(60) turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(180) def build_house(turtle,size): build_walls(turtle,size) build_roof(turtle,size) t = Turtle() build_house(t,300) # try to build a house from turtle import * def build_walls(turtle,size): turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) turtle.forward(size) turtle.right(90) def build_roof(turtle,size): turtle.left(60) turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(120) turtle.forward(size) turtle.right(180) def build_house(turtle,size): build_walls(turtle,size) build_roof(turtle,size) t = Turtle() build_house(t,300) # try to build a house

20 20 Experimenter's Corner From the turtle program  Try to swap statement build_roof and build_walls in function build_house. Is the result the same?  Try to change the direction of the turtle before calling build_house. How is the result?

21 21 Side notes... The terms used to call "function" in other programming languages may be different  In Object-oriented languages like C# or Java, a function is called a method.  Functions that do not return values may be called subroutines or procedures. Parts of a program which do not belong to any function is usually called "main program"  Languages, such as C, C#, and Java, require programmers to write main program in under a specific function, e.g., function main.

22 22 Thinking Corner Change the main program so that the turtle draws 3 houses (same size) with space of size 30 between two consecutive houses. 20

23 23 Example: from centimeters to inches Define function cm_to_inch  Takes one parameter, a length in centimeters.  Returns the same length in inches.  Use the following rule: 1 inch = 2.54 cm def cm_to_inch(x): return x/2.54 def cm_to_inch(x): return x/2.54

24 24 How to test functions in Wing IDE 1. Start a new program 2. Enter function definition 3. Save the file 4. Hit "Run" 5. Experiment with the function

25 25 Thinking Corner: inches to feet Define function inch_to_foot, which  Takes one parameter, the length in inches.  Returns the length in feet  1 foot = 12 inches

26 26 Example: centimeters to feet The function calls that return values can be used as expressions. This kind of expressions can be used in other expressions or even as arguments to other function calls >>> inch_to_foot(cm_to_inch(250)) 8.202099737532809 >>> inch_to_foot(cm_to_inch(250)) 8.202099737532809 cm_to_inchinch_to_foot Length in cmLength in inchesLength in feet

27 27 Thinking Corner: cm to foot Define function cm_to_foot  It is required that this function must use function cm_to_inch and function inch_to_foot defined previously.

28 28 Thinking Corner: Computing moving distance Take the example from last time that computes the distance from the acceleration and the duration and write it as a function  Function name: distance  Takes two parameters:  a (acceleration in m/s 2 ), and  t (duration in seconds)  Returns the distance that the object, initially staying still, moves.

29 29 Thinking Corner: volume of cylinders Define function volume, which  Takes two parameters  r, the radius of the base  h, the height of the cylinder  Returns the volume of the cylinder whose base radius is r and height is h. h h r v =  r 2 x h

30 30 Thinking Corner: When will the bucket be full? We are filling a bucket with water. Write a program that computes the duration needed to fill the full bucket, whose shape is a cylinder. The program should read from the user:  The diameter of the bucket, in inches  The height of the bucket, in inches  The rate of the water flowing into the bucket, in cc/s Then shows the duration needed to fill the bucket in minutes.

31 31 Example Enter tank's diameter (inch): 12 Enter tank's height (inch): 3 Enter water flow rate (cc/s): 15 Time to fill the tank is 6.17777758516 minutes Enter tank's diameter (inch): 12 Enter tank's height (inch): 3 Enter water flow rate (cc/s): 15 Time to fill the tank is 6.17777758516 minutes

32 32 Side notes: formatting strings with % We can format the output using operator % Try to change the previous program to show the duration with only two decimal digits. >>> x = 8.3 >>> 'Time to fill the tank is %.2f minutes' % x 'Time to fill the tank is 8.30 minutes' >>> print("Time to fill the tank is %.2f minutes" % x) Time to fill the tank is 8.30 minutes >>> x = 8.3 >>> 'Time to fill the tank is %.2f minutes' % x 'Time to fill the tank is 8.30 minutes' >>> print("Time to fill the tank is %.2f minutes" % x) Time to fill the tank is 8.30 minutes Put the value of x with 2 decimal digits here

33 33 Scope of variables The scope of variables defined inside a function starts from the point of the definition and ends where the function ends  These variables are called local variables. The scope of variables defined outside any functions starts from the point of the definition and ends at the end of the program.  These variables are called global variables.

34 34 Local and global variables x = 8 y = 3 def myfunc(): y = 5 a = x myfunc() print(x,y) x = 8 y = 3 def myfunc(): y = 5 a = x myfunc() print(x,y) This variable y is a different variable from the one defined outside. This variable x is the same variable as the one outside The output from function print is "8 3", That is, the global variable y remains unchange.

35 35 But be careful Result: the program prints 8 Result: Python shows errors x = 8 def myfunc(): print(x) myfunc() x = 8 def myfunc(): print(x) myfunc() x = 8 def myfunc(): print(x) x = 3 myfunc() x = 8 def myfunc(): print(x) x = 3 myfunc() This assignment makes variable x in myfunc to be local. Therefore, this x (which is the same x as in the next line) refer to a local variable which does not exist. Varible x here is the same as the global one

36 36 Global statement We can explicitly declare that this variable is the same as the global one. x = 8 y = 3 def myfunc(): global y y = 5 a = x myfunc() print(x,y) x = 8 y = 3 def myfunc(): global y y = 5 a = x myfunc() print(x,y) Now, this y is the same as the one outside The result is then 8 5

37 37 Suggestions Try to avoid using global variables, because  In this case, the behavior of the function is not only determined by the parameters, but it also depends implicitly on the global variables.  This, in turns, make it very hard to understand the program when many functions can change the value of the global variables.


Download ppt "Functions and subroutines 01204111 – Computer and Programming."

Similar presentations


Ads by Google