Upload
maria-nelson
View
216
Download
2
Embed Size (px)
Citation preview
PPT 2
Other things: functions
Can you have a function with no inputs? Yes:
def f( ):
return (3 + 4)
Can you have a function with no outputs? Yes:
def f(x):
3 + 4
Can you have a function with no inputs and outputs? Yes:
def f( ):
3 + 4
Functions: Math: f(x) = x3
Python: def f(x):
return(x**3)
Given a particular input to this function, will we ALWAYS get the same output?
e.g. f(2)
f(3)
Could we say that f(2) is equivalent to 8?
Could we say that f(3) is equivalent to 27?
Functions(how they work)def f(x): # code for a function that
return(x**3) # returns the cube of a number
f(2) # Calls the function. The function is now executed (i.e., calculated,
# converted to machine language and instructions run by the CPU).
# # After f(2) runs, all that remains is what is RETURNED
When the function is done being executed, 8 is returned (i.e., output from the function) and the instructions are removed from memory (RAM). Only 8 remains. Thus, for our purposes, f(2) is exactly the same thing as the number 8.
Using functions: Remember: after we use a function, what remains is
what is returned from the function
def add2(x,y):
return(x + y)
def add(x,y):
return(add2(x,y) + add2(x,y))
print(add(7,3))
Using functions:def add2(x,y):
return(x + y)
def div(x,y,z):
return(add2(x,y) / z)
print(div(7,3,2))
Using functions:def add2(x,y):
return(x + y)
def div(x,z):
return(add2(x,3) / z)
print(div(7,2))
Using functions:def add2(x,y):
return(x + y)
def div(y,x):
return(add2(y,3) / x)
print(div(7,2))
Using functions:def add2(x,y):
return(x + y)
def add3(y,x):
return(add2(y,3) + add2(11,x))
print(add3(7,2))
def f1(par1, par2):
return(par2 - par1)
print(f1(2,4))
#2
def f2(x1,x2):
return(x1**2 + x2)
print(f2(3,6))
#15
def f3(p1,p2): return(f2(p1,p2) + f1(p1,p2))
print(f3(3,2))10
def f4(p1,p2): return(f2(p2,p2) - f1(p1,p1))
print(f4(4,2))6
def f5(q1,q2): return(f2(q2,q1))
print(f5(17,5))42
def f6(par1,par2): return( 3 + f1(par1, 17+par1))
print(f6(4,26))20
Given the function
def Squr(par1):
return(par1 ** 2)
def dbl(par2):
return(par2 + par2)
def Func1(p1,p2):
return(Squr(p1) - Squr(p2))
print(Func1(4,3))
>>7
def Func2(p1,p2,p3):
return(Squr(p1) * Func1(p2,p3))
print(Func2(2,3,2))
>>20
def Func3(p1,p2):
return(dbl(Squr(p1)))
print(Func3(4))
>>AACH CRASH BURN
def Func4(p1,p2):
return(dbl(Squr(p2)+ Squr(p2)+3))
print(Func4(2,4))
>> 70
def Func6(p1):
return(dbl(dbl(dbl(Squr(p1)+1))-Squr(3)))
print(Func6(-2))
>>22
Piecewise functions Can we have a function like this?
32 if x > 0
f(x) =
0 otherwise
If /else (branching)def f(x):
if x > 0:
return (3**2/x)
else:
return (0)
f(3) # this equals?
f(0) # this equals?
f(-2) # this equals?
32 if x > 0 _f(x) = x
0 otherwise
Piecewise functions
How about this?
x3 + 2x if x > 2
f(x) = -x3 + 2x if x < 0
-1 otherwise
If /else (branching)def f(x):
if x > 2: return (x ** 3 + 2 * x)
elif x < 0: return(-x ** 3 + 2 * x)
else:return (-1)
f(3) # this equals?f(0) # this equals?f(-2) # this equals?
x3 + 2x if x > 2f(x) = -x3 + 2x if x < 0
-1 otherwise
Comparators (return T or F)
== equal to 5==5 true
!= not equal to 8!=5 true
> greater than 3>10 false
< less than 5<8true
>= greater than 6>=8 falseor equal to
<= less than 6<=8 trueor equal to
Note: == if conditions MUST use == (equality)
not = (assignment)
==
Asks a question: is this equal to that??? this == that ?
Yes or No!
True, this is equal to that, or
False, this is not equal to that
= We’ll see this in use shortly
If Statement structure:if condition1 is true:
execute this statement(s)
elif condition 2 is true:
execute this statement(s)
elif condition3 is true:
execute this statement(s)
else:
execute this statement(s)
#only one else condition!
Rules for If/elif/else:1. If/elif condition must evaluate something that is True or False
if (3== 4)…
if (8 > 4)…
if (f2(3) < 4)…
if (func(7)!=4)…
2. If does not require an elif or an else
1. Only one else if there is an else
3. The first branch that is true is executed, and nothing else:if (x > 3):
return(3)
elif (x > 2):
return (2)
4. If the condition is False, nothing indented under the condition is executed.
Exampledef f(x):
if x > 10:
return (x+9)
elif x < 7:
return (x + 4)
else:
return(0)
print(f(12)) # what is printed?
print(f(6)) # what is printed?
print(f(8)) # what is printed?
print(f(7)) # what is printed?
Exampledef f(x):
if x != 10:
return (x * 2)
else:
return (x ** 2)
print(f(6))
print(f(10))
Exampledef f(x):
if x < 10:
return (x+9)
elif x == 5:
return (x + 4)
elif x >10:
return (x)
else:
return(0)
print(f(5)) ?
anddef q(x): if (x>5) and (x < 10): return("just enough") elif (x >= 10) and (x < 15): return("too much") else: return("no idea")
print(q(12))
1. What does and do?
2. What type is returned from this function?
Logical Operators
and (True and True)(True and False)(False and True)(False and False)
TrueFalseFalseFalse
or (True or True)(True or False)(False or True)(False or False)
TrueTrueTrueFalse
not (not True)(not False)
FalseTrue
diff?
def q1(x): if (x>6) and (x < 5): return("just enough") elif (x > 15) and (x < 20): return("too much") else: return("no idea")
print(q1(7))print(q1(13))
def q2(x): if (x>6) or (x < 5): return("just enough") elif (x > 15) or (x < 20): return("too much") else: return("no idea")
print(q2(7))print(q2(13))
What happens?
def ReturnSomething(value):
if value = 1:
return “glub”
else:
return “blug”
print (ReturnSomething(1))
Strings Python cares about types:
We can do different operations on different types Can’t add a string with a number:
Can’t: print(“puddle” + 4)
Can add strings to strings!
Word of the day: Concatenate
means join (string concatenated to string)
Can: print(“puddle” + “ jumping”)
Can: print(“puddle” + “4”)
Can: return(“bat” + “ty”)
Can multiply a string by a number:
Can: print(“bla” * 38)
Can’t: print(“bla” * “bla”)
Operator overloading: doing more than one operation with the same
operator, depending on the types involved
using + for both numbers (to add) and strings (to join, aka CONCATENATE)
using * to multiply numbers and * to make multiple copies of a string
Adding Strings:
def addstrings(par1):
return(par1 + "ubba")
print (addstrings("gub"))
def addmore(par1):
return(addstrings(par1)+addstrings(par1))
print(addmore("hab"))
Printing inside my function:
What if I want to see the string that was input into the function?
def addstrings(par1): print(“par1 came in”)
return(par1 + "ubba")print (addstrings("gub"))
We want to print what’s inside par1, not “par1”Now we’re adding what’s inside par1 to “came in”
and that is what gets printed by the function before we leave the function.
print(par1 + “came in”)
Printing inside a functiondef f_to_c(ftemp): print("The temp before conversion is ftemp")
return((ftemp - 32 )/ 1.8)print (f_to_c(68))print (f_to_c(22))
Is this what we wanted? Is this what we want now?
print("The temp before conversion is” + ftemp
Solutiondef f_to_c(ftemp): print("The temp before conversion is” + str(ftemp)) return((ftemp - 32 )/ 1.8)print (f_to_c(68))print (f_to_c(22))
Note: ftemp is not in quotes.
When it is not in quotes, we’re talking about what’s inside of ftemp and not the word ftemp
what is inside of ftemp is an integer. We can’t add integers to strings
str(ftemp) takes the number inside of the parameter ftemp and converts it to a string
New Function input : 3 integers - x, y and z
Output: a string “Yes x is divisible by both y and z” or
“No, x is not evenly divisible by y and z”
“x is not in range”
Function name: isDivisible
Calculations: Two parts:
check if x is between 0 and 100
Check if x is evenly divisible by both y and z
#input : 3 integers, x, y and z#Output: a string # “Yes x is divisible by both y and z” or# “No, x is not evenly divisible by y and z”# “x is not in range”#Function name: isDivisible#Calculations: check if x is greater than 0 and less than 100 and is evenly#divisible by both y and z
def isDivisible(x, y,z):
if ((x > 0)and (x < 100)) and ((x%y) == 0) and (x % z) == 0):
#ugh! Long and hard to read
return (“Yes “+str(x)+” is divisible by both “+str(y)+” and “+str(z))
else:
return (“No, “+str(x)+” is not evenly divisible by “+str(y)+” and “+str(z))
print(isDivisible(15,5,3))
print(isDivisible(150,5,3))
Is this what we want ? Will it always work?
#input : 3 integers, x, y and z#Output: a string # “Yes x is divisible by both y and z” or# “No, x is not evenly divisible by y and z”# “x is not in range”#Function name: isDivisible#Calculations: check if x is greater than 0 and less than 100 and is evenly#divisible by both y and z
def isDivisible(x, y,z):
if ((x > 0)and (x < 100)) and ((x%y) == 0) and (x % z) == 0):
return (“Yes “+str(x)+” is divisible by both “+str(y)+” and “+str(z))
elif ((x > 0)and (x < 100)) :
return (“No, “+str(x)+” is not evenly divisible by “+str(y)+” and “+str(z))
else:
return (str(x) + “is not in range”)
print(isDivisible(15,5,3))
print(isDivisible(150,5,3))
Is this what we want ? Will it always work?
#input : 3 integers, x, y and z#Output: a string # “Yes x is divisible by both y and z” or# “No, x is not evenly divisible by y and z”# “x is not in range”#Function name: isDivisible#Calculations: check if x is greater than 0 and less than 100 and is evenly#divisible by both y and z
def isDivisible(x, y,z)
if (x > 0)and (x < 100):
if ((x%y) == 0) and ((x % z) == 0):
return (“Yes “+str(x)+” is divisible by both “+str(y)+” and “+str(z))
else:
return (“No, “+str(x)+” isn’t evenly divisible by “+str(y)+” and “+str(z))
else:
return(str(x ) + “ is not in range”)
print(isDivisible(15,5,3))
print(isDivisible(150,5,3))
Now what if x is 250 or -1?
Same?def g(x):
if (x>5) and (x < 10):
return("just enough")
elif (x > 5) and (x < 15):
return("too much")
else:
return("no idea")
def g(x): if (x > 5): if (x < 10): return("just enough") elif (x < 15): return("too much") else: return("no idea")
print (g(12))What about:print (g(17))
Loan QualifierWe want to write a function that tells someone whether they qualify for a loan. If a person makes more than 35,000 and they’ve been employed
for at least 2 years, they qualify.
If they make over 35,000, but haven’t been employed for at least 2 years, They should get a message saying how long they need to wait before
they can get the loan (e.g., if they’ve only been employed for 1.2 years, the program should
tell them to come back in .8 years) If they don’t make 35,000, but have been employed for over 2
years, They should get a message telling them the minimum salary
requirement If they don’t make 35,000 and they haven’t been employed for 2
years, they don’t qualify.
Using Nested If (ifs inside of ifs) can you write this?
LoanQualifierdef loanqualifier(sal,yrs): if (sal > 35000): if (yrs >= 2): return("Congratulations! You qualify!") else:
temp = str(2 – yrs) return("You will qualify in " + str(round(2-yrs) ,2)+ " years.") else: if (yrs>=2): return("You need to make at least 35000 to qualify for a loan") else: return("I'm sorry, you don't qualify.")
#Note the test cases – we’re testing all outputs to make sure they work
print (loanqualifier(40000,4)) print (loanqualifier(40000,1.2))print (loanqualifier(20000,4))print (loanqualifier(20000,1.2))
LoanQualifierdef loanqualifier(sal,yrs): if (sal > 35000): if (yrs >= 2): return("Congratulations! You qualify!") else: return("You will qualify in " + str(round(2-yrs) ,2)+ " years.") else: if (yrs>=2): return("You need to make at least 35000 to qualify for a loan") else: return("I'm sorry, you don't qualify.")
#Note the test cases – we’re testing all outputs to make sure they work
print (loanqualifier(40000,4)) print (loanqualifier(40000,1.2))print (loanqualifier(20000,4))print (loanqualifier(20000,1.2))
LoanQualifierdef loanqualifier(sal,yrs): if (sal > 35000): if (yrs >= 2): return("Congratulations! You qualify!") else:
temp = str(2 – yrs) return("You will qualify in " + temp + " years.") else: if (yrs>=2): return("You need to make at least 35000 to qualify for a loan") else: return("I'm sorry, you don't qualify.")
#Note the test cases – we’re testing all outputs to make sure they work
print (loanqualifier(40000,4)) print (loanqualifier(40000,1.2))print (loanqualifier(20000,4))print (loanqualifier(20000,1.2))