Functions and Abstraction

Slides:



Advertisements
Similar presentations
Guide to Programming with Python
Advertisements

Debugging Introduction to Computing Science and Programming I.
Functions and abstraction Michael Ernst UW CSE 190p Summer 2012.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
CPTR 124 Review for Test 1. Development Tools Editor Similar to a word processor Allows programmer to compose/save/edit source code Compiler/interpreter.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
CSC 212 – Data Structures Prof. Matthew Hertz WTC 207D /
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
L what are predefined functions? l what is? n function name n argument(s) n return value n function call n function invocation n nested function call l.
CMSC 150 METHODS AND CLASSES CS 150: Wed 25 Jan 2012.
CMSC 150 METHODS AND CLASSES CS 150: Wed 25 Jan 2012.
Georgia Institute of Technology More on Creating Classes part 1 Barb Ericson Georgia Institute of Technology Oct 2005.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Chapter 6 Functions The Tic-Tac-Toe Game. Chapter Content In this chapter you will learn to do the following: 0 Write your own functions 0 Accept values.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
CS 265 Jianbo Zhao. What is interface? Interface is a detailed boundary between code that provides a service and code that uses it. An interface defines.
Math operations 9/19/16.
Lesson 06: Functions Class Participation: Class Chat:
User-Written Functions
More Sophisticated Behavior
More on Functions (Part 2)
Python Let’s get started!.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Predefined Functions Revisited
Testing UW CSE 160 Winter 2017.
Functions CIS 40 – Introduction to Programming in Python
Functions.
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Imperative Programming
Functions BIS1523 – Lecture 17.
Number and String Operations
Functions, Procedures, and Abstraction
Testing UW CSE 160 Winter 2016.
Winter 2018 CISC101 11/27/2018 CISC101 Reminders
Passing Parameters by value
Learning to Program in Python
Writing Functions.
More on Functions (Part 2)
Maintaining a Program In today’s lesson we will look at:
Learning Intention I will learn about evaluating a program.
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
Chapter 6 – Methods Topics are:
Winter 2019 CISC101 4/8/2019 CISC101 Reminders
Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg
More on Creating Classes
COMPUTER PROGRAMMING SKILLS
Predefined Functions Revisited
Javascript Chapter 19 and 20 5/3/2019.
Variables in C Topics Naming Variables Declaring Variables
What is a Function? Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar.
CS31 Discussion 1D Fall18: week 2
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Python SAT 1 Feedback.
def-ining a function A function as an execution control structure
Functions, Procedures, and Abstraction
Computers and Scientific Thinking David Reed, Creighton University
CMPT 120 Lecture 4 – Unit 1 – Chatbots
CMPT 120 Lecture 13 – Unit 2 – Cryptography and Encryption –
 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.
Imperative Programming
Functions John R. Woodward.
Flow Control I Branching and Looping.
Using Modules.
Unit Testing.
Presentation transcript:

Functions and Abstraction

Today's Goal Learn to reorganize a program into Functions Learn about Local and Global Variables Learn to Document Functions

Getting Started Let's write a program to play a guessing game. The program picks a secret number and invites the user to guess the number.

guess.py import random secretNum = random.randrange(1, 11) numGuesses = 0 guess = 0 while guess != secretNum: guess = int(input("Enter your guess: ")) numGuesses += 1 if guess < secretNum: print("Your guess is too low.") elif guess > secretNum: print("Your guess is too high.") else: print("You got it!!") print("It took you", numGuesses, "guesses.")

Time to Reorganize This program is fairly straightforward Still, we can make it easier to comprehend by refactoring it into functions Refactoring is any reorganization of a program that does not alter its behavior In this case, we want to apply the principle of abstraction, hiding details to improve comprehension

Refactored guessWithFunctions.py import random def pickSecretNumber(): return random.randrange(1, 11) def checkGuess(guess, secretNum): if guess < secretNum: print("Your guess is too low.") elif guess > secretNum: print("Your guess is too high.") else: print("You got it!!") # main program def main(): secretNum = pickSecretNumber() numGuesses = 0 guess = 0 while guess != secretNum: guess = int(input("Enter your guess: ")) numGuesses += 1 checkGuess(guess, secretNum) print("It took you", numGuesses, "guesses.") main() # execute main program

Does this help? Introducing functions helps simplify the main program We need to know what each function does in order to fully understand the main program When examining a function call, we don't want to have to dig into the internals of the function to understand what the call does That would defeat the goal of abstraction We need a way to see "at a glance" what a function does: We need function documentation.

Writing Function Documentation

Function Docstrings You know how to write short comments using the # prefix Functions often contain one or more # comments that explain sections of code within the function To document the overall behavior of the function, we use a docstring A docstring is a triple-quoted string that appears indented as the first line of the function body Document with a Triple-quoted string: def add(x: int, y: int) -> int: """returns sum of `x` and `y`""" return x + y Don't document with a # comment: # returns sum of `x` and `y` No

Function Docstrings A good docstring describes What the method does (not how it does it) How the parameter values are used Refer to parameter values using `back ticks` What value is returned def add(x: int, y: int) -> int: """returns sum of `x` and `y`""" return x + y

Detailed Docstring Format A docstring always begins with a short, one-line description of the function When more space is needed for additional details, skip a line after the short description, then add preconditions and postconditions def sumNums(lo: int, hi: int) -> int: """Computes sum of [`lo`..`hi`] Preconditions: `lo` <= `hi` Postconditions: returns sum of numbers in range [`lo` .. `hi`] """ sum = 0 for i in range(lo, hi+1): sum += i return sum

Time to Practice Write short docstrings for guessWithFunctions.py

Local and Global Variables

Reworking checkGuess() Global variables are variables defined outside a function. We could change checkGuess() so that it accesses the values of the global variables guess and secretNum directly. However, it makes it less obvious that checkGuess accesses information in guess and secretNum. secretNum = 0 # define global variables guess = 0 def checkGuess(): if guess < secretNum: print("Your guess is too low.") elif guess > secretNum: print("Your guess is too high.") else: print("You got it!!") def main(): … while guess != secretNum: guess = int(input("Enter your guess: ")) numGuesses += 1 checkGuess()

Updating Global Variables We can't simplify pickSecretNumber() the same way By default, functions can access, but not update, global variables Any variables assigned to by a function are local variables Local variables are distinct from any variables of the same name used anywhere else in the program Local variables have a limited life They are created when the function assigns them a value They are destroyed when the function returns def pickSecretNumber(): secretNum = random.randrange(1, 11) # secretNum is a local variable pickSecretNumber() # no global secretNum was created

Updating Global Variables To update a global variable from a function, you must declare inside the function that the variable is global, not local Use the global statement inside a function to declare that the function wishes to update a global variable We say that functions that update global variables have side effects Unintended side effects are a source of tricky bugs def pickSecretNumber(): global secretNum secretNum = random.randrange(1, 11) pickSecretNumber() # global secretNum was created

Using Local and Global Variables Well-written programs have very few global variables Bugs involving global variables are much harder to track down than bugs involving local variables (why?) Most variables in well-written programs are local Best practices: Create global variables only for values that must be shared everywhere Prefer passing parameters and returning values to using global variables Python's default local/global behavior tends to encourage good style