Defining Functions.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Computer Science 1620 Loops.
Chapter 6: User-Defined Functions I
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
CS 201 Functions Debzani Deb.
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
Functions and abstraction Michael Ernst UW CSE 190p Summer 2012.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
CS 127 Writing Simple Programs.  Stages involved  Analyze the problem  Understand as much as possible what is trying to be solved  Determine Specifications.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 6 Defining Functions.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Functions (2)
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Data Types and Conversions, Input from the Keyboard If you can't write it down in English, you can't code it. -- Peter Halpern If you lie to the computer,
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
1 Functions Function Prototype float sqrt(float x); Function name, type, parameter and parameter type Function Definition float sqrt(float x) { // compute.
4 March 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems
6. FUNCTIONS Rocky K. C. Chang October 4, 2015 (Adapted from John Zelle’s slides)
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Input, Output and Variables GCSE Computer Science – Python.
Introduction to Programming
Introduction to Programming
Chapter 6: User-Defined Functions I
COMPSCI 107 Computer Science Fundamentals
Data Types and Conversions, Input from the Keyboard
Introduction to Programming
CS 1110 Introduction to Programming Spring 2017
Chapter 6 Modular Programming Dr. J.-Y. Pan Dept. Comm. Eng.
FIGURE 4-10 Function Return Statements
Chapter 6 Functions.
Functions CIS 40 – Introduction to Programming in Python
Functions.
CMSC201 Computer Science I for Majors Lecture 10 – Functions (cont)
User-Defined Functions
Learning Outcomes –Lesson 4
CMSC201 Computer Science I for Majors Lecture 14 – Functions (Continued) Prof. Katherine Gibson Based on concepts from:
Introduction to Programming
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Introduction to Programming
Programming We have seen various examples of programming languages
Introduction to Programming
5. Functions Rocky K. C. Chang 30 October 2018
Topics Introduction to Functions Defining and Calling a Void Function
Chapter 6: User-Defined Functions I
Introduction to Value-Returning Functions: Generating Random Numbers
CS 1111 Introduction to Programming Spring 2019
Introduction to Programming
COMPUTER PROGRAMMING SKILLS
CISC101 Reminders Assignment 3 due today.
Introduction to Programming
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
def-ining a function A function as an execution control structure
Using Modules.
Introduction to Methods and Interfaces
Python Creating a calculator.
Unit Testing.
Lecture 2 - Names & Functions
Presentation transcript:

Defining Functions

Today's Goal Learn to write your own functions

Functions Recall that a function is like a mini-program: Takes input Performs calculations Produces result

Anatomy of a Function Definition Function name Parameters A function definition consists of 1. Interface: Specifies Function name Parameters 2. Implementation Statements that perform the work def add(x, y): result = x + y return result

A Basic Example The drawSquare function: takes no parameters draws a square of fixed size using the turtle created by the main program Note that the functions must be defined at the top of the program import turtle def drawSquare(): for i in range(4): t.forward(20) t.left(90) # ---- main program ---- t = turtle.Turtle() drawSquare()

An Example with Parameters We want two different turtles to be able to draw a square Our new drawSquare() needs two parameters from the main program: Turtle to use to draw Length of side of square def drawSquare(t, size): for i in range(4): t.forward(size) t.left(90) # ---- main program ---- alex = turtle.Turtle() drawSquare(alex, 40) greta = turtle.Turtle() drawSquare(greta, 20)

More About Parameters Formal parameters Parameters in Function Definition Placeholders for values supplied by code that calls the function Called "Formal Parameters" Parameters in Calling Code Supply values to function Called "Actual Parameters" or "Arguments" When a function is called, values from the arguments are copied to the formal parameters def drawSquare(t, size): for i in range(4): t.forward(size) t.left(90) # ---- main program ---- alex = turtle.Turtle() drawSquare(alex, 40) Actual parameters (aka Arguments)

Returning Data A function can return a value to its caller using the return statement The return statement specifies a value to be transmitted back to the caller. When the return statement executes, the specified value is copied back to the variable in the calling assignment statement. Demo: Trace execution in CodeLens Textbook 6.2 Functions that Return Values def square(x): answer = x * x return answer result = square(10) print(result) 100

Returning Multiple Values A function can return two or more values. def divide(x, y): quotient = x // y remainder = x % y return (quotient, remainder) (quo, rem) = divide(10, 3) print(quo, rem)

Calling Functions in Expressions The data returned by a return statement can be used in any expression Doesn't have to be in an assignment statement def add(x, y): result = x + y return result print( add(2, 3) ) y = 5 * add(5, 10) z = add(add(2, 3), y)

Type Hints result = x + y return result You can specify the data types of the parameters and the return value by adding type hints A type hint specifies the expected data type for a particular parameter or for the return type The type hints are for readers of your code They are not checked by the Python interpreter Data Type names: int, float, bool, str Parameter type hints def add(x, y): result = x + y return result def add(x: float, y: float) -> float: Return type hint

Practice Write a function named max that takes two numbers and returns the larger. Write a function named roundIt that takes a positive number and rounds it to the nearest integer (hint: think about adding .5 and then dropping any fractional portion). Include type hints.

Practice The program below finds the largest number in a list of positive numbers entered by the user. Rework the following code to use max(): largest = 0 num = 0 while num != -1: num = int(input(("Enter a number (-1 to quit): ")) if num > largest: largest = num print('The largest number was', largest) def max(x: int, y: int) -> int: if x > y: return x else: return y

Why Create Functions? Two key reasons: Manage complexity Eliminate duplicate code

Duplicate Code Duplicate code is a Great Evil When you copy and paste code, you copy the bugs in the code Duplicate code leads to larger, more complicated programs Practice: Create a function to eliminate the duplicate code alex.forward(30) alex.right(120) greta.forward(50) greta.right(120)

Managing Complexity Large programs are complicated. To manage the complexity, we break the programs up into functions. We can Test each function separately Reason about each function separately Functions are a key mechanism that makes abstraction possible. Abstraction (n). Hiding information to manage complexity.

Abstraction Abstraction is one of the Big Ideas in Computer Science. It makes digital technology possible. Without it, there would be no Smart phones Internet Digital messaging Why?