Presentation is loading. Please wait.

Presentation is loading. Please wait.

Other things: functions

Similar presentations


Presentation on theme: "Other things: functions"— Presentation transcript:

1 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? def f(x): 3 + 4 Can you have a function with no inputs and outputs? Class 1 Stopped (Wed)

2 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?

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

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

5 Using functions: def add2(x,y): return(x + y) def div(x,y,z): return(add2(x,y) / z) print(div(7,3,2))

6 Using functions: def add2(x,y): return(x + y) def div(x,z): return(add2(x,3) / z) print(div(7,2))

7 Using functions: def add2(x,y): return(x + y) def div(y,x): return(add2(y,3) / x) print(div(7,2))

8 Using functions: def add2(x,y): return(x + y) def add3(y,x): return(add2(y,3) + add2(11,x)) print(add3(7,2))

9 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 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 Class 3 stopped after first example on Wed

10 Given the function def Squr(par1): return(par1 ** 2) def dbl(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 Given the function def Squr(par1): return(par1 ** 2) def dbl(par2): return(par2 + par2) Class 2 stopped (Wed)

11 Piecewise functions Can we have a function like this? 32 if x > 0 𝑥
0 otherwise

12 If /else (branching) def f(x): if x > 0: return (3**2/x) else:
f(3) # this equals? f(0) # this equals? f(-2) # this equals? if x > 0 f(x) = x _ 0 otherwise

13 Piecewise functions How about this? x3 + 2x if x > 2
f(x) = -x3 + 2x if x < 0 otherwise Class 3

14 If /else (branching) def f(x): if x > 2: return (x ** 3 + 2 * x)
x3 + 2x if x > 2 f(x) = x3 + 2x if x < 0 otherwise If /else (branching) def f(x): if x > 2: return (x ** * x) elif x < 0: return(-x ** * x) else: return (-1) f(3) # this equals? f(0) # this equals? f(-2) # this equals?

15 Comparators (return T or F)
== equal to 5==5 true != not equal to 8!=5 true > greater than 3>10 false < less than 5<8 true >= greater than 6>=8 false or equal to <= less than 6<=8 true or equal to Class 3 stopped here

16 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

17 If Statement structure:
if condition1 is true: execute this statement(s) elif condition 2 is true: elif condition3 is true: else: #only one else condition!

18 Rules for If/elif/else:
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)… If does not require an elif or an else Only one else if there is an else The first branch that is true is executed, and nothing else: if (x > 3): return(3) elif (x > 2): return (2) If the condition is False, nothing indented under the condition is executed.

19 Example def 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?

20 Example def f(x): if x != 10: return (x * 2) else: return (x ** 2) print(f(6)) print(f(10))

21 Example def 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)) ? Class 2 stopped here

22 and def 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)) What does and do? What type is returned from this function?

23 Logical Operators and (True and True) (True and False)
(False and True) (False and False) True False or (True or True) (True or False) (False or True) (False or False) not (not True) (not False)

24 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))

25 What happens? def ReturnSomething(value): if value = 1: return “glub” else: return “blug” print (ReturnSomething(1)) Class 3

26 What have we learned so far?
Atomic data Types Operators Functions Input parameters Return values Diff between return and print!!! Function composition Branching (if conditions)

27 Strings Python cares about types: Can’t add a string with a number:
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”)

28 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

29 Adding Strings: def addstrings(par1): return(par1 + "ubba") print (addstrings("gub")) def addmore(par1): return(addstrings(par1)+addstrings(par1)) print(addmore("hab"))

30 def getname(x): if x == 3: return("John") elif x == 13: return("Joe") elif x == 7: return("Sam") else: return("Bob") print(getname(13)) def getpron(x): if x == 2: return("you") elif x == 3: return("I") elif x == 4: return("she") elif x == 5: return("he") return("it") print(getpron(5)) def getverb(x): if x == 17: return("am") elif x == 24: return("was") elif x == 32: return("love") else: return("ran over") print(getverb(27)) def makeit(x,y,z): return(getname(z) + getpron(y) + getverb(x)) print(makeit(17,3,7))

31 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”)

32 Printing inside a function
def 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

33 Solution Note: def f_to_c(ftemp):
print("The temp before conversion is” + str(ftemp)) return((ftemp - 32 )/ 1.8) print (“The temp after conversion is” + str(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

34 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

35 return (“Yes “+str(x)+” is divisible by both “+str(y)+” and “+str(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?

36 elif ((x > 0)and (x < 100)) :
#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?

37 #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)) 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?

38 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))

39 Quick function: Write a function that checks to see if a number is even or not. What TYPE does this return?

40 Boolean Values We now know functions can return: True or False ?
Numbers (int, double) Strings True or False ? AKA Boolean Values Yes, No 1, 0 We can use True and False as if they are a type) E.g., return(True)

41 def ismultof3(x): if ((x%3) == 0): return(True) else: return(False) When python executes the following statement, what is the result? (x%3)==0 def ismultof3(x): return((x%3) == 0) def func2(x): if (ismultof3(x)): # Can we see why specifying what type # is returned from a function is critical?!? return(str(x) + " is a multiple of 3") return(str(x) + " is not a multiple of 3") Class1 stopped here Class 2 stopped here

42 Returning to Boolean Values:
Quadratic Equation: x2 - 3x – 4 = 0 Is this true for 1? 2? 3? 4? Can you write a function that returns the answer to this question? Hint: the function needs to return a boolean value. What is the input? How do you check for the output? Class 3

43 Function to represent this:
#Name: eqcheck #Calculation: Determines if input value (x) will solve #the problem: # x2 - 3x – 4 = 0 #Input: x: a number #Output: a boolean value def eqcheck(x): return (x**2 – 3*x – 4) == 0 What is returned? print(eqcheck(3)) print(eqcheck(4)) Class 1

44 Remember? def Squr(par1): return(par1 ** 2) def dbl(par2):
return(par2 + par2) def Func4(p1,p2): return(dbl(Squr(p2)+ Squr(p2)+3)) print(Func4(2,4)) def Func5(p1): return(dbl(dbl(dbl(p1)))) print(Func5(4))

45 What gets printed out? def f(n): if (n == 0): return (" ") else: print(“blug ") return f(n-1) f(3)

46 What about? def f(x): if (x == 0): return x else: return(x + f(x-1)) print(f(4)) def f2(x): if (x == 1): return (str(x)) return(str(x) + f2(x-1)) print(f2(4)) class 3

47

48 Recursion (one of 3 types of loops)
Recursion is when a function is defined in terms of itself (it calls itself). Def: A recursive definition is one that defines something in terms of itself (that is, recursively) Recursion is, in essence, making a function happen again and again without our having to call it (convenient, huh?) It is one of 3 types of loops we will learn all do the same thing, just different syntax) #This is recursion def recurse(): return(recurse()) #This isn’t def nonrecurse(): return(“nope”) Class 2

49 Try: def f(x): return(x + f(x-1)) print(f(4)) def f2(x): if (x == 1):
else: return(x + f3(x-2)) print(f3(4)) def f(x): return(x + f(x-1)) print(f(4)) def f2(x): if (x == 1): return x else: return(x + f2(x+1)) print(f2(4)) class2

50 How about: def f(x): if x == 100: return(“none") else: if (x**2 - 3 *x - 4) == 0: print(str(x) + " solves the equation ") return(f(x+1)) print(f(-100))

51 Loop Essentials We now have the basics:
Must formulate a problem in terms of itself. (Recursion: the function must call itself) Must include a condition for stopping the recursion (base case) Must make sure that we will always hit that stopping condition.

52 Sum numbers (1-5) def summing(x):
If we start by calling the function with 1, when should we stop? if (x >= 5): # must return something that does not make the loop happen again!!!!! return(x) #why x? Assume the smallest case possible: Summing one number. No matter what the number is, if you are summing that number and that number only, you want to return that number. Alt: if we start summing 1-5 by calling the function with 5, when should we stop? if (x <= 1): return(x) Note: Sometimes we can have MORE THAN ONE stopping condition (you only have to make one of them happen)

53 Sum numbers (1-5) def summing(x): Stopping Condition? if (x >= 5):
return(x) How do we make sure that we get to the stopping condition? Increase x every time we “loop” E.g., summing(x+1) Alternative: summing(x-1) If we do these two things, we will likely avoid an infinite loop

54 Sum numbers 1-5 (cont.) def summing(x):
Stopping condition if (x >= 5): return (x) Progressing towards stopping condition: summing(x+1) Finally, we need to write our function: Pretend there are only 2 cases – the last case (step 1, above) and the case right before that. (e.g., summing 4-5) We want to return(x + summing(x+1)), right? From step 1 we know summing (x+1) returns 5 And we know x holds 4. So summing(4) returns 9 Now what if we summed from 3-5? Can we use what we just did?

55 Sum Numbers 1-5 (cont.) Put it all together: def summing(x):
if (x >= 5): return(x) else: return(x + summing(x+1)) print(summing(1))

56 Try: Write a recursive function that creates a string of every other number starting at 1 and ending at 10 Write a recursive function that sums every other number between two integers (you can assume the second integer is greater than the first integer) Write a recursive function that counts the number of numbers that is evenly divisible by 3 between x and y

57 Problem 1:Write a recursive function that prints out every other number starting at 1 and ending at 10 def g(x): if x == 10: return(str(x)) elif x > 10: return() else: return(str(x) + g(x+2)) print(g(1))

58 Problem 2: Write a recursive function that sums every other number between two integers
def g(x,y): if x == y: return(x) elif x > y: return() else: return(x + g(x+2)) print(g(3,12))

59 Problem 3: Write a recursive function that counts the number of numbers that is evenly divisible by 3 between x and y Same? def h(x,y,z): if x >=y: return(z) elif x%3 == 0: return (h(x + 1,y,z+1)) else: return(h(x+1,y,z)) print(h(3,28,0)) def h(x,y): if x >=y: return(0) elif x%3 == 0: return (1 + h(x + 1,y)) else: return(h(x+1,y)) print(h(3,28))

60 Try: def g(x): if (x == 0): return('r') elif (x%5==0): return(g(x-1)+'t') elif (x%3 == 0): return(g(x-1) + 'b') elif (x%2 == 0): return(g(x-1) + 'o') else: return(g(x-1)) print(g(5))

61 Random Numbers Used for Everything! To create a random number:
Gaming (games of chance, unpredictable movements, unpredictable timing, etc. Generating noise in signals Random checking of data And the list goes on and on! To create a random number: from random import * #imports the random library, including all the functions to generate random numbers And then x=randrange(1,10) #x now holds a number between 1 and 9 (doesn’t include 10) Example: import turtle def f(x): if (x == 5): return("Done") else: x = randrange(0,10) print("the random number is " + str(x)) return(f(x)) print(f(10))


Download ppt "Other things: functions"

Similar presentations


Ads by Google