/
Other things: functions Can you have a function with no inputs? Other things: functions Can you have a function with no inputs?

Other things: functions Can you have a function with no inputs? - PowerPoint Presentation

ximena
ximena . @ximena
Follow
66 views
Uploaded On 2023-06-22

Other things: functions Can you have a function with no inputs? - PPT Presentation

Yes def f return 3 4 Can you have a function with no outputs Yes def fx 3 4 Can you have a function with no inputs and outputs Yes def f 3 4 Functions Math fx x ID: 1001798

print return function def return print def function elif str true number divisible par1 summing false evenly add2 ftemp

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Other things: functions Can you have a f..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1. Other things: functionsCan 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 + 4Can you have a function with no inputs and outputs?Yes:def f( ): 3 + 4

2. Functions:Math: f(x) = x3Python: 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 numberf(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 RETURNEDWhen 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 functiondef 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 f1(par1, par2): return(par2 - par1)print(f1(2,4))#2def f2(x1,x2): return(x1**2 + x2)print(f2(3,6))#15def f3(p1,p2): return(f2(p1,p2) + f1(p1,p2))print(f3(3,2))10def f4(p1,p2): return(f2(p2,p2) - f1(p1,p1))print(f4(4,2))6def f5(q1,q2): return(f2(q2,q1))print(f5(17,5))42def f6(par1,par2): return( 3 + f1(par1, 17+par1))print(f6(4,26))20

10. Given the functiondef Squr(par1): return(par1 ** 2)def dbl(par2): return(par2 + par2)def Func1(p1,p2): return(Squr(p1) - Squr(p2))print(Func1(4,3))>>7def Func2(p1,p2,p3): return(Squr(p1) * Func1(p2,p3))print(Func2(2,3,2))>>20def 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))>> 70def Func6(p1): return(dbl(dbl(dbl(Squr(p1)+1))-Squr(3)))print(Func6(-2))>>22

11. Piecewise functionsCan we have a function like this? 32 if x > 0 f(x) = 0 otherwise 

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

13. Piecewise functionsHow about this? x3 + 2x if x > 2 f(x) = -x3 + 2x if x < 0 -1 otherwise

14. 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 > 2 f(x) = -x3 + 2x if x < 0 -1 otherwise

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

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: execute this statement(s)elif condition3 is true: execute this statement(s)else: execute this statement(s) #only one else condition!

18. Rules for If/elif/else:If/elif condition must evaluate something that is True or Falseif (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 elseThe 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. 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?

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

21. 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)) ?

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

23. Logical Operatorsand(True and True)(True and False)(False and True)(False and False)TrueFalseFalseFalseor(True or True)(True or False)(False or True)(False or False)TrueTrueTrueFalsenot(not True)(not False)FalseTrue

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

26. What have we learned so far?Atomic dataTypesOperatorsFunctionsInput parametersReturn valuesDiff between return and print!!!Function compositionBranching (if conditions)

27. StringsPython cares about types:We can do different operations on different typesCan’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 involvedusing + 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") else: 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 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

33. Solutiondef 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 ftempwhat is inside of ftemp is an integer. We can’t add integers to stringsstr(ftemp) takes the number inside of the parameter ftemp and converts it to a string

34. New Functioninput : 3 integers - x, y and zOutput: 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: isDivisibleCalculations: Two parts: check if x is between 0 and 100Check if x is evenly divisible by both y and z

35. #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 zdef 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. #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 zdef 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 zdef 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?

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 ValuesWe now know functions can return:Numbers (int, double)StringsTrue or False ?AKA Boolean ValuesYes, No1, 0We 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)==0def 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") else: return(str(x) + " is not a multiple of 3")

42. Returning to Boolean Values:Quadratic Equation:x2 - 3x – 4 = 0Is 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?

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 valuedef eqcheck(x): return (x**2 – 3*x – 4) == 0What is returned?print(eqcheck(3))What is returned? print(eqcheck(4))

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)) else: return(str(x) + f2(x-1))print(f2(4))

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 recursiondef recurse():return(recurse())#This isn’tdef nonrecurse():return(“nope”)

49. Try: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))def f3(x): if (x == 1): return x else: return(x + f3(x-2))print(f3(4))

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 EssentialsWe 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 conditionif (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 5And we know x holds 4.So summing(4) returns 9Now 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 10Write 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 10def 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 integersdef 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 ydef 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))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))

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 NumbersUsed for Everything!Gaming (games of chance, unpredictable movements, unpredictable timing, etc.Generating noise in signalsRandom checking of dataAnd 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 numbersAnd thenx=randrange(1,10)#x now holds a number between 1 and 9 (doesn’t include 10)Example:from random import *import turtledef 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))