Functions and subroutines 01204111 – Computer and Programming.

Slides:



Advertisements
Similar presentations
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Advertisements

Do I need a robot today? You only need a robot if your team has not shown me your octagon and/or the octagon in a function.
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
Functions Jay Summet. Aug Functions A function is a piece of code you can use over and over again Treat it like a black box You pass it (optional)
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
CS 201 Functions Debzani Deb.
Introduction to Python
Chapter 2 Writing Simple Programs
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Chapter 3 Planning Your Solution
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Introduction to Python
General Programming Introduction to Computing Science and Programming I.
Introduction to Computers and Programming – Computer Programming.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Variables, Expressions, and Standard Functions. Topics Basic calculation Expressions, variables, and operator precedence Data types Input / Output Examples.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 3 Simple.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 12: A few other things.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Lecture 17 Parameters, Scope, Return values.
Lecture 5 1.What is a variable 2.What types of information are stored in a variable 3.Getting user input from the keyboard 1.
1 Structure of a C Program (continued) Presentation original from Dr. Turner’s class USF - COP C for Engineers Summer 2008.
ENG College of Engineering Engineering Education Innovation Center 1 MATLAB – Functions 1 Topics Covered: 1.Functions 2.Function files Functions.
Python Functions : chapter 3
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
Python Let’s get started!.
1 Project 2: Using Variables and Expressions. 222 Project 2 Overview For this project you will work with three programs Circle Paint Ideal_Weight What.
Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(
CRE Programming Club Class 2 (Import JJZ543 and Practice Your Typing!)
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
JavaScript Modularity. Goals By the end of this lecture, you should … Understand why programmers use modularity. Understand how to create a function in.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Functions. 2 Modularity What is a function? A named block of code Sometimes called a ‘module’, ‘method’ or a ‘procedure’ Some examples that you know are:
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 2 Writing Simple Programs
Chapter 9: Value-Returning Functions
User-Written Functions
Introduction to Programming
Functions Jay Summet.
CS 1110 Introduction to Programming Spring 2017
Variables, Expressions, and IO
Functions CIS 40 – Introduction to Programming in Python
CompSci 230 Software Construction
Functions.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Procedures Programming Guides.
Chapter 4 void Functions
Coding Concepts (Sub- Programs)
Introduction to Programming
Topics Introduction to Functions Defining and Calling a Void Function
Functions Jay Summet.
Topics Introduction to Functions Defining and Calling a Function
Functions Jay Summet.
Introduction to Computer Science
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Introduction to Programming
Functions, Procedures, and Abstraction
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
Functions Jay Summet.
Presentation transcript:

Functions and subroutines – Computer and Programming

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 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 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 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 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 โปรแกรมที่สมบูรณ์ 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 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 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 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 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 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 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() 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 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 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 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 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 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 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 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 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 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 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 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 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 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)) >>> inch_to_foot(cm_to_inch(250)) cm_to_inchinch_to_foot Length in cmLength in inchesLength in feet

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

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