Beruflich Dokumente
Kultur Dokumente
Card Question
String "Ferraris"
List ["my","name","is","Mater"]
Functions
We have seen some built-in functions. For example,
casting functions like str( ) and int( ) are built-in functions
we can use. So is the len function for strings.
>>> print str(4) + str(1)
str has input of type integer and output of type string
>>> print int("4")
int has input of type string and output of type integer
>>> print len(“abc”)
len has input of type string and output of type integer
We can also write our own functions. Let’s write a
function to say Hi to George.
def sayHi( ):
print "Hi George"
def sayHi2(anyName):
print "Hi " + anyName
>>> sayHi2("Martha")
def sayHi2U( ):
name=requestString("What is your name? ")
print "Hi "+name
>>> sayHi2U( )
For each of these functions, a) state the function name and
the parameters (if any). b) How would you call each of
these functions? c) What happens when you call them?
def ave90and98( ): def average(test1,test2):
test1 = 90 sum = test1+test2
test2 = 98 ave = sum/2
sum = test1+test2 print ave
ave = sum/2
print ave
def askAndAverage( ):
test1 = requestInteger("Please enter score on Test 1:")
test2 = requestInteger ("Please enter score on Test 2:")
sum = test1+test2
ave = sum/2
print ave
Return statements
We can have a function return a value. For example, we
have the function average:
def average(test1,test2):
sum = test1+test2
ave = sum/2
print ave
def finalgrade(test1,test2,bonus):
mygrade = average(test1,test2)
print mygrade + bonus
>> finalgrade(90,98,5)
Discuss with your neighbor: 1. In this code:
def career(person,job):
print 'The '+job+' is '+person
>>> career('Sally','attorney')
a. identify the following:
name of the function
parameters
the value assigned to person
b. What prints as the result of this function call? What
prints if instead we call the function with
>>> career('attorney','Sally')
c. Does the colon go with the definition of the function or
with the function call?
2. Matching
Parameters output
Arguments inputs
3. Consider the directions: Write a function that returns
the square of a given number.
a. How many parameters should your function
have? How do you know that?