LPTHW Exercises 18-26



Functions:  the building blocks of a program

REVIEW


  1. What are data types?
  2. Which data types do we know thus far?
  3. What are variables?  Assignment?  Defined?
  4. What is string interpolation?

Exercise 18: Intro to Functions

def print_two_again(arg1, arg2):
    print "arg1: %r, arg2: %r" % (arg1, arg2)

def print_one(arg1):
    print "arg1: %r" % arg1

def print_none():
    print "I got nothin'."        
Units of code that can be reused (i.e. a mini-script or factory)

How do we define functions?    How do we call functions?  What does calling a function achieve?

What are function arguments?

Problem Set #1


Save a script called "problem_set_1" within the IDE which contains a function that converts inches to feet: 
 
1) The function should take, as an argument, a height in inches

2) Inside function, print the value of the argument in inches

3) Within the function, convert the value to feet

4) Print the result inside the function

Exercise 19: Function Arguments


Arguments to functions 

are input values (data)


They are assigned to variable names inside the function


See IDE for example




Extra Content: Intro to Scope

How does Python know where to find variable names?
What happens when a variable is reassigned inside a function?

exercise 21: Return Values

 def seconds_to_minutes(seconds):     calculated_minutes = float(seconds) / 60     return calculated_minutes
minutes = seconds_to_minutes(120) print minutes
def print_name(name):
print name ### implicitly, a function ends with this if no return statement is present ### return None
def abrupt_ending(): return 1 # Functions stop whenever a return statement is encountered print 'hello function'

exercise 21 Continued


See IDE

What is happening on line 32?

exercise 22-23: Memorization


Go through these exercises on your own

Share the code that you found online to read

Exercise 24: Group Practice


LET'S READ CODE


SEE IDE

Exercise 26: Test yourself


Really important that you do this exercise on your own

Functions: basic building blocks of a program

By benjaminplesser

Functions: basic building blocks of a program

  • 1,006