Textbook. Topic 6: Functions. Motivation. What is a Function? What s a function? How can we use functions to write better software?

Similar documents
Textbook. Topic 5: Repetition. Types of Loops. Repetition

Topic 2: Introduction to Programming

9.1 Linear Inequalities in Two Variables Date: 2. Decide whether to use a solid line or dotted line:

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Topic 8: Lazy Evaluation

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Topic 7: Lists, Dictionaries and Strings

Computer Science & Engineering 150A Problem Solving Using Computers

Lecture 04 FUNCTIONS AND ARRAYS

Iterators & Generators

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

CS 106 Introduction to Computer Science I

Math 15 - Spring Homework 5.2 Solutions

CSI33 Data Structures

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Static Methods. Why use methods?

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

ME422 Mechanical Control Systems Matlab/Simulink Hints and Tips

1/11/2010 Topic 2: Introduction to Programming 1 1

S206E Lecture 19, 5/24/2016, Python an overview

Lecture Chapter 2 Software Development

Software Design. Levels in Design Process. Design Methodologies. Levels..

Functions. Lecture 6 COP 3014 Spring February 11, 2018

CSI33 Data Structures

Semester 2. Structured Programming. Modular Programming Top-down design. Essentials covered. More complex programming topics.

142

2. Functions I: Passing by Value

Data Structures (list, dictionary, tuples, sets, strings)

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Algorithms: The recipe for computation

CS110D: PROGRAMMING LANGUAGE I

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Computing and compilers

Unit: Rational Number Lesson 3.1: What is a Rational Number? Objectives: Students will compare and order rational numbers.

Using Flash Animation Basics

0.5 Graphing Piecewise-Defined Functions

Testing. UW CSE 160 Winter 2016

C3 Numerical methods

Introduction to Modules. Chapter 3. Defining and Calling a Module. Introduction to Modules. 5 Benefits of Modules. Modules CSUS, Spring 2016

Lecture 19. Operators and Abstraction

Learning objectives: Software Engineering. CSI1102: Introduction to Software Design. The Software Life Cycle. About Maintenance

1. Write two major differences between Object-oriented programming and procedural programming?

PREPARING FOR THE FINAL EXAM

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Differentiability and Tangent Planes October 2013

Cubic Splines By Dave Slomer

Outline. Introduction to Programming (in C++) Introduction. First program in C++ Programming examples

Chapter 1: Principles of Programming and Software Engineering

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Programming with Python

Object Oriented Methods : Deeper Look Lecture Three

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

Outline. software testing: search bugs black-box and white-box testing static and dynamic testing

Fundamentals of Programming Session 13

Lecture Notes: Hoare Logic

Chapter 5 C Functions

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving Excel Tutorial VIII

SCRATCH MODULE 3: NUMBER CONVERSIONS

Math Homework 3

Unit: Quadratic Functions

Outline. Outline. 1 Chapter 2: Data Abstraction

Is the statement sufficient? If both x and y are odd, is xy odd? 1) xy 2 < 0. Odds & Evens. Positives & Negatives. Answer: Yes, xy is odd

Introduction to Python (All the Basic Stuff)

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

2.2 Data Abstraction

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

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

CMSC 201 Spring 2017 Lab 05 Lists

Formal Methods for Java

Chapter 6: Functions

12/30/2013 S. NALINI,AP/CSE

User-Centered Development

CS111: PROGRAMMING LANGUAGE1. Lecture 2: Algorithmic Problem Solving

Computing. Building Retention: What prior learning must be built upon/revisited and how will it be assessed? Term Cycle 1

Procedures: Algorithms and Abstraction

Mobile App:IT. Methods & Classes

Object Oriented Software Design

2. From General Form: y = ax 2 + bx + c # of x-intercepts determined by the, D =

CSCA08 Winter 2018 Week 2: Variables & Functions. Marzieh Ahmadzadeh, Brian Harrington University of Toronto Scarborough

Chapter 1: Programming Principles

Help File on C++ and Programming at CSUSM by Rika Yoshii

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Unit 7. Functions. Need of User Defined Functions

CSC Advanced Object Oriented Programming, Spring Specification

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Math 1113 Notes - Functions Revisited

2.2 Transformers: More Than Meets the y s

Numerical Methods in Scientific Computation

Section Graphs of the Sine and Cosine Functions

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Curriculum Map Grade(s): Subject: AP Computer Science

Assignment 7: Due Wednesday May 11 at 6pm UPDATES on Monday May 9

Core Mathematics 1 Transformations of Graphs

CMSC 201 Spring 2019 Lab 06 Lists

CSI33 Data Structures

Logical operators: R provides an extensive list of logical operators. These include

Chapter 9. Introduction to High-Level Language Programming. INVITATION TO Computer Science

MAT 003 Brian Killough s Instructor Notes Saint Leo University

Software Development. Modular Design and Algorithm Analysis

Data Structures and Algorithms for Engineers

Transcription:

Textbook Topic 6: Functions What s a? How can we use s to write better software? Strongly Recommended Exercises The Python Workbook: 85, 86, 98 and 103 Recommended Exercises The Python Workbook: 84, 88, 92, 93, 101 and 102 Recommended Readings Starting Out with Python Chapter 3 and Chapter 6 (2 nd Ed.) / Chapter 5 (3 rd Ed.) 1 2 What is a Function? What is a? A named set of statements Perform some task Functions: May take parameters May return values What s have you already used? Motivation Ideally, a should perform a clearly defined specific single purpose hide details from the caller be sufficiently small to be easily understood be well documented 3 4

Defining a Function Creates a for later use The does not execute until it is called Function may be called many times (from different places) after it has been defined General form: def Name(parameters): statement(s) Create a that draws a music note Head will be a solid oval, 20 pixels wide and 10 pixels high Stem will be 50 pixels tall on the right side Center the head of the note at 100, 100 5 6 Calling Our Function A does not execute when it is defined It must be called Execution for the entire program begins at the first statement outside of a What s the problem with our? How do we fix it? 7 8

Parameters Allow us to provide data to a Data is placed in brackets after the name when the is called Parameter variables appear in brackets after the name in the definition Values appear in parameter variables when the executes Parameters are positional Actual Parameter Terminology The value placed in brackets after the name when the is called Formal Parameter The name of the parameter variable in the definition 9 10 Extend our note drawing so that it takes two parameters that control the position of the note Named Parameters Positional parameters assign values to parameter variables in the order that they occur Named parameters allow us to assign values in any order Allow for optional parameters / default values for some parameters May still be used in a positional manner 11 12

Extend the note drawing so that it takes additional parameters that specify the color of the note Default Parameter Values Python permits default values for parameters If the call does not supply a value then the default is used If the call includes a value for that parameter then the default value is overridden 13 14 Functions Can Call Functions Functions Can Call Functions Create a second for drawing a note Head will be a solid oval, 20 pixels wide and 10 pixels high Stem will be 50 pixels tall on the right side Flag will be a curve 15 16

Functions Can Return a Result Returning a result allows a value to move from the to the location where it was called Accomplished using a return statement inside the When the is called it is often on the right side of an assignment statement Functions Can Return a Result Write a that determines the number of real roots of an equation of the form ax 2 + bx + c = 0 17 18 Variables & Functions Variables can be defined inside s A variable defined inside of a can only be used inside that Behaves just like the variables we have used previously Variables & Functions Variables can be defined outside of s Referred to as global variables Can be read anywhere in the program after it is assigned a value All of the constants we have created are global variables that we choose not to change Use of global variables (other than as constants) is strongly discouraged 19 20

Variables & Functions Changing global variables By default, an assignment statement inside of a creates a new variable within that Even if a global variable with that name already exists Want to change a global variable? Include a global statement at the beginning of the Create a that computes n-factorial 21 22 Returning Multiple Values What if we need to return more than one value from a? Comma separated tuple of values in return statement Comma separated tuple of variables to the left of the equals sign Scope Scope determines the portion of a program where a name can be used Impacts s, variables, Functions Functions can t be called before they have been defined Functions in other modules cannot be used until after the import statement for that module 23 24

Variables Scope Cannot be read before they are given a value Can be used from the point where they are first assigned a value until the end of the Variables created inside a are destroyed when the exits Formal Parameters Formal Parameter variables hold values passed to a from the calling scope Formal parameters are normally read It is also possible to store a new value into a formal parameter (we don t usually do this!) Value of the variable will change in the called For the types we have used so far, the value will not change in the main program 25 26 Why Functions are Useful Facilitate Code Reuse Write once, use many times Reduce Complexity Low level details are hidden Programmer can concentrate on higher level problems Ease Maintenance Bugs only need to be corrected once Functions can be tested separately Comments Every should begin with a comment Describe the action taken by the Describe the parameters that need to be provided Describe the value returned by the 27 28

Preconditions / Postconditions Function comments may also describe Preconditions: Conditions that must be true before the executes If any precondition is not met, the may not behave correctly Postconditions: Conditions that are guaranteed to be true after the executes If the doesn t make a post-condition true then the contains a bug that must be fixed 29 Addition and multiplication practice: 10 random questions that involve adding or multiplying 2 integers between 1 and 10 30 Testing Test each you write individually Errors are easier to find Generally only need to look inside the being tested Only use the in the rest of your program once you have tested it thoroughly 31 32

Design How do s relate to top down design? Use top down design to break the problem into smaller pieces Each smaller piece is a good candidate for a Look at each Is it too big? Does it contain repeated code? Should it call other s? Modules Functions can be placed in modules to promote reuse Place the s in a different.py file Import it just like math or SimpleGraphics Add an if statement to prevent the main program from running in the imported file if name == " main ": main() 33 34 Functions Wrapping Up A named group of statements that perform a task Allow us to break our program into separate units that each have a specific purpose Ease program creation and debugging Where Are We Going? Now that we can write larger programs we want to be able to manage more data How can we work with many values at the same time in a reasonable way? How do we read and write values in files? 35 36