functions and structured...
TRANSCRIPT
UNIT 6Functions and Structured Programming
LESSON 1What is a Function?
What is Structured Programming?
I can…..
• Divide a large program into small problems.
• Write a Python program as a function
Planning a Wedding
• What are some of the steps we will take when planning a
wedding?
Planning a Wedding
• Make Guest List
• Take Engagement Photos and Send out Save the Dates
• Decide on Wedding Party
• Find Wedding Gown, Bridesmaid Dresses, and Tuxes
• Pre-Marital Meeting with Officiant (Pastor, Priest, etc)
• Food Tasting
• Purchase Decorations
• Plan Rehearsal Dinner
• Do Final Preps• Decorate the Hall
• Prepare Food
• Dance and Enjoy!
What is Structured Programming?
• Organizing programs by breaking them up into smaller, easier to manage programs (called functions)
• Allows you to reuse code that is repeated!
• “Divide and Conquer” Method
• Top – Down Design• Break a large programming task (Top) into smaller and smaller
subtasks (Bottom)
**ALSO CALLED MODULAR PROGRAMMING**
Why is Structured Programming Needed?
• Past programming:
• Programming in older languages vs. modern style of programming
• Older: “Spaghetti Code”
• Hopelessly intertwined statements caused by numerous “jumps” between sections of code
• Nearly impossible to follow – NO FLOW
• Modern:
• Use functions – 1 main function where main code runs logically in order
• Will run other functions but always return to main.
Steps to Writing a Structured Program
1. Start with an Outline of the main program
• Write out pseudocode to describe major tasks to be
performed
• Avoid thinking about the details of each major task right now
2. Write the main - mostly calls to functions
• Translate each English phrase into one or two function calls
• Use documentations to describe the actions and make programs
readable
Steps to Writing a Structured Program
3. Write each function
• Define the function (name and parameters)
• Type the code for that function (indented)
4. Test and Debug
• Use a complete set of test data to be sure it works
• Make changes or refinements that are necessary or desireable
Example of the planning process
Functions Already Used
Turtle graphics….
• forward()
• color()
• left()
• goto(x, y)
Math functions…
• sqrt(n)
• pi
• pow(b, n)
• floor(n)
General Functions…
• print()
• input()
• eval()
String Functions…
• len(x)
• upper(x)
• chr(x)
• ord(x)
• split(x)
Random Functions…
• random()
• randrange(x,y,z)
• randrange(x, y)
**We’ve actually
used MORE than
this**
What is a function?
• A sub-program or block of code that accomplishes a
specific task
• Often returns a value, text, or object
• A “Mini Program”
• Also called a method or subroutine
New Approach to the Main Function
• We can (and will starting today) write our “main function”
like a function!
Functions Syntax:
def <name of function> ():
<statements>
Let’s Write an Example Together
• Let’s write a program that prints out the lyrics to the song
“Happy Birthday”
• Main program must now be written as a function so we
can add functions in later!
Program #1
# Happy Birthday Program
# create main function
def main ():
# get name from user
name = input(“What is your name?: “)
# print happy birthday to user
print(“Happy Birthday to you”)
print(“Happy Birthday to you”)
print(“Happy Birthday dear” , name)
print(“Happy Birthday to you”)
How do we make our program run?
The main function is an executable function – but we need
to tell it to execute the main!
def main () :
<statements>
…..
main() This line of code at the end of a python program will “run the main function”
Let’s Write our First Function
• In the happy birthday program – do you notice any code
repeating???
• This is a perfect time to use a function!
Let’s Look Back!
# Happy Birthday Program
# create main function
def main ():
# get name from user
name = input(“What is your name?: “)
# print happy birthday to user
print(“Happy Birthday to you”) repeated 3 times
print(“Happy Birthday to you”) repeated 3 times
print(“Happy Birthday dear” , name)
print(“Happy Birthday to you”) repeated 3 times
main()
Let’s Write a Function
**Add this code beneath the “main()” statements**
# function prints 1 line of Happy Birthday
def happy ():
print(“Happy Birthday to you”)
Let’s Update our Main!
# Happy Birthday Program
# create main function
def main ():
# get name from user
name = input(“What is your name?: “)
# print happy birthday to user
happy() calling and running the happy() function
happy() calling and running the happy() function
print(“Happy Birthday dear” , name)
happy() calling and running the happy() function
main()
LESSON 2Passing parameters to a function
I can…..
• Write a function in Python.
• Write a program that uses functions
Benefits of Structured Programs1. Easier to read
• Each function will have documentations explaining its purpose
2. Easier to write
• Complicated programs broken down into smaller, easier to manage
functions
3. Easier to use, change, adapt, modify, debug
• Only need to change in one location (not every time appears in
program)
• Easily determine where an error is occuring
4. Easier to reuse
• Can be copied into another program
• Can be called in the same program multiple times
5. Other, More powerful programming languages
require this kind of structure.
Writing Python Programs with Functions!
def main():
<statements>
function1()
function2()
def function1():
<statements>
def function2():
<statements>
main()
Question to Ponder
1. If each function is its own “mini program”, how is
information shared between different functions?
2. How do I get data that is held within one subroutine into
another one for processing??
Parameter
• Variable values passed into the function
• The function needs these values in order to “do its job”
• May include as many parameters as the function needs
• If no parameters are needed – the parentheses are empty
• Example: happy() function in lesson 1’s program
Parameter Passing
A function definition with parameters:
def <name> (<formal parameters>) :
<statements>
Example:
def hello (person) :
print(“hello” , person)
Parameter Passing
A function call with parameters:
<name>(<actual parameters>)
Parameters
• The parameter provides a method of transferring data
from the main function to be the function being called
• Ex:
ord(“A”) takes in a CHARACTER
chr(45) takes in an INTEGER
lower(message) takes in a STRING
Let’s update our Happy Birthday Program
Version 1:
• Create a function called “sing” that will take in a
parameter “name” and sing happy birthday to the
person
• The Sing function should use the “happy()”
function we create yesterday
• Program should sing “Happy Birthday” to Joe,
Callie, and Alex
Let’s update our Happy Birthday Program
# Happy Birthday Program
# create main function
def main ():
# get name from user
name = input(“What is your name?: “)
# print happy birthday to user
happy()
happy()
print(“Happy Birthday dear” , name)
happy()
main()
Sing Function
# Sings happy birthday to a person with a given name
def sing (personname):
happy()
happy()
print(“Happy Birthday dear, personname)
happy()
How do we call a function with parameters?
• The same way we call any other function – but we need to
ensure we “send it” that parameter requirements
Example:
sing(personname)
Let’s update our Happy Birthday Program
# Happy Birthday Program
# create main function
def main ():
# get name from user
name = input(“What is your name?: “)
#sings happy birthday to user
sing(name) # sends in name of user
main()
Let’s Sing to More People!
# Happy Birthday Program
# create main function
def main ():
# get name from user
name = input(“What is your name?: “)
#sings happy birthday to user and others!
sing(name) # sends in name of user
sing(“Joe”)
sing(“Callie”)
sing(“Alex”)
main()
LESSON 3Returning a Value
I can…..
• Write a function in Python that returns a value.
• Write a program that uses functions
Review of Terminology:
• What is a function?
• What is “structured programming”?
• What is “structured programming” also called?
• What are the benefits of structured programming?
How do we get a value from a function?
• Most functions we have used so far in this class have
provided us with a value.
• Examples:
len() returns the number of characters in a string
lower() returns a copy of a string in all lower case letters
randrange(4,9) returns a random integer between 4 and 8
ord() returns a character at the ASCII number
chr() returns an integer for the ASCII character
Returning a Value
• Called Function “returns” a value to the program calling
the function.
• If a value is returned, it must either be saved inside a
variable in the program calling the function or used
immediately when called
• If the returned value isn’t saved or used, it is LOST
• Function are NOT required to return a value
Returning a Value
Returning a Value
def <name> (<formal parameters>) :
<statements>
return <variable name>
Returning a Value
Example in Code
def addition(num1, num2):
sum = num1 + num2
return sum
Write a Program that
• Takes in value from a user a converts it from pounds to
kilograms.
Program: Convert Pounds to Kilograms
# main program
def main():
#welcome statement
print(“Converts pounds to kilograms \n \n”)
# gets weight from user
lbs = eval(input(“Enter your weight in lbs: “)
# converts pounds to kilograms, returns kgs, and
# SAVES the value inside a new variable named kgs
kgs = compute(lbs)
Program continued
# prints kilograms to screen
print(Weight in kgs: “ ,kgs)
# function that converts pounds to kilograms
def compute(lbs):
kilograms = lbs/2.2
return kilograms
#runs main program
main()
2nd Way to Use returned values
# main program
def main():
#welcome statement
print(“Converts pounds to kilograms \n \n”)
# gets weight from user
lbs = eval(input(“Enter your weight in lbs: “)
#prints kgs to screen
print(Weight in kgs: “ , compute(lbs) )
LESSON 4Passing more than one Parameter
I can…..
• Write a function in Python that takes in multiple
parameters.
Review of Terminology:
• What is a function?
• What is structured programming?
• What is a parameter?
• What is a returned value?
What happens when we send in a parameter?
• Main function (or the function calling another function to
run) sends in the VALUE
• This means if a variable name is placed in the parameter
list, the VALUE is the only thing sent inTHE VARIABLE VALUE WILL NOT BE CHANGED IN THE MAIN PROGRAM
AS THE FUNCTION FUNS
• The variable value sent in will only be USED by the
function to complete its task
Example
def main():
name = input(“What is your name: “)
double(name)
print(name)
def double(name) :
name = name*2
print(name)
main()
Functions Using Parameters
name name
Each function stores its local variable information in different
places in memory
In this program – there are actually 2 variables called “name”
• one saved in the main program’s block of memory
• another stored in the double function’s memory
Local Variable
• All variables are LOCAL to the function they are defined
in.
• **Bubbler Explanation Example**
• To access a variable outside a function, it must be passed
to the function
Passing Parameters
Function Definition Syntax:
def <name>(<formal parameter1>, … , <formal parameterN>)
<body>
Function Call Syntax:
<name>(<actual parameter1>, … <actual parameterN>)
Passing Parameters by VALUE
• A copy of the VALUE of a variable are passed to the
function.
• The function than creates it’s own variable with that value
– this variable is LOCAL to the function
When Python Comes to a Function Call
1. The calling function suspends execution at the point of
the call
2. The formal parameters of the function get assigned the
values supplied by the actual parameters in the call.
3. The body of the function is executed.
4. Called function returns a value (if necessary) and the
program returns to the point just after where the
function was called.
Example Program #1
def main() :
print(“The value of x in main before the function call” , x)
changeX(x)
print(“The value of x in main after the function call” , x)
def changeX(x)
print(“The value of x at beginning of changeX call” , x)
x = x + 25
print(“The value of x after changeX call” , x)
main()
Example Program #2
def() main:
length = eval(input(“Enter length: “))
width = eval(input(“Enter width: “))
area = computeArea(length, width)
print(“area = “ , area)
def computeArea(l, w) :
a = l*w
return a
main()
Write a Program Together
• Write a program that ultimately asks the user to enter in
the base and height of a triangle and then calculates the
area of the triangle.
• Main
• Welcome message (function or not)
• Ask the user for the base and height (function or not)
• Area Function – need the base and height sent into it – return the
area of the triangle
• Print out the output (function or not)
LESSON 5Combining Structure Programming with
Control Structures (if and loops)
I can…..
• Use control structures (loops and conditionals) with
function calls.
Example Program 1
• Roll two dice until get a roll of 2 (snake eyes – each die is
a 1 = total of “2”)
• Track how many rolls it takes to roll snake eyes
• Print the number of rolls to the screen
Rolls (# of times I have rolled the die)
Rolltotal (total with the two die values added together)
Keep rolling until I roll a 2 (while loop)
Function – roll – roll two die (randomly 1-6), return the
“rolltotal”
Example Program 1 - Code
from random import randrange
def main():
roll = 0
rolltotal = 0
while rolltotal != 2 :
rolltotal = rolldice()
roll = roll + 1
print(“It took” , roll, “rolls to get snake eyes”)
Example Program 1 – Code (pg 2)
def rolldice():
roll1 = randrange(1, 7)
roll2 = randrange(1, 7)
rolltotal = roll1 + roll2
return rolltotal
main()
Example Program 2
• Takes in a number
• States whether the number is even or odd (using a
function)
Takes in a number
Example Program 2 - Code
def main():
number = eval(input(“Please enter in a number: “))
evenodd = evenOrOdd(number)
print(“Your number is” , evenodd)
def evenOrOdd(number):
if number%2 == 0:
return “even”
else :
return “odd”
main()
EXTRA
Program 5
• How many items did you buy
• Cycles through item prices and finds sum
• Asks for tax
• Calculates total cost
• Asks user if they want to play again
Widgets and Dodads project