Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions and Abstraction

Similar presentations


Presentation on theme: "Functions and Abstraction"— Presentation transcript:

1 Functions and Abstraction

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

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

4 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.")

5 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

6 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

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

8 Writing Function Documentation

9 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

10 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

11 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

12 Time to Practice Write short docstrings for guessWithFunctions.py

13 Local and Global Variables

14 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()

15 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

16 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

17 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


Download ppt "Functions and Abstraction"

Similar presentations


Ads by Google