Presentation is loading. Please wait.

Presentation is loading. Please wait.

What is printed out? def f(x): print(x+3) return(x + 7) def g(k): return(f(k) + 2) print(g(1)) 4 10 def f2(x): return(x + 7) print(x+3) def g2(k): return(f2(k)

Similar presentations


Presentation on theme: "What is printed out? def f(x): print(x+3) return(x + 7) def g(k): return(f(k) + 2) print(g(1)) 4 10 def f2(x): return(x + 7) print(x+3) def g2(k): return(f2(k)"— Presentation transcript:

1 What is printed out? def f(x): print(x+3) return(x + 7) def g(k): return(f(k) + 2) print(g(1)) 4 10 def f2(x): return(x + 7) print(x+3) def g2(k): return(f2(k) + 2) print(g2(1)) 10

2 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

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

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

5 #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?

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

7 Loan Qualifier We want to write a function that tells someone whether they qualify for a loan. If a person makes or more and they’ve been employed for at least 2 years, they qualify. If they make or more, 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?

8 LoanQualifier def 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.") if (yrs>=2): return("You need to make at least to qualify for a loan") 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)) Class 1

9 LoanQualifier def 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.") if (yrs>=2): return("You need to make at least to qualify for a loan") 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)) Class 1

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

11 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 True/False (Boolean Values) are a TYPE!!! We can use True and False like other types (e.g., ints, strings) E.g., return(True)

12 George Boole (1815-1864) English mathematician
First professor of mathematics at Queen's College, Cork in Ireland. Best known as the author of The Laws of Thought (1854) which contains Boolean algebra. Boolean logic lays the foundations for programming Boolean: True/False

13 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") print(func2(7)) Print(func2(9)) Class1 stopped here Class 2 stopped here

14 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

15 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

16 Random Numbers Used all the time for so many things!!!!
Python lets you generate random numbers within a range import the random number library from random import * generate a random number between 2 numbers: randrange(0,10)

17 Example: from random import * def guess(x): #what type does guess return? if (x == randrange(1,10)): return True else: return False print(guess(3)) #what might be printed here? Better version: def guess2(x): return(x==randrange(1,10))

18 What’s wrong with this function? (hint: none printed out when I ran it)
from random import * def beloworabove(): if (randrange(-10,10) < 0): return("random number is below 0") elif (randrange(-10,10) == 0): return("random number is 0") elif (randrange(-10,10) > 0): return("random number is above 0") print(beloworabove())

19 Variables: (assignment)
A variable: holds a value. A space in RAM we give a name to A lot like parameters, only we create them within the function Then we can use them inside the function def f(x): #simple and silly example of using a variable y = 3 # y only exists within this function return(x + y)

20 Variables: def f(x): y=3 y=y+x # Do the right side first, then put
# that value into the left side. return(y**2) f(5)

21 More examples: def calcvol(length,width,depth):
area = length * width #area only exists inside this function vol = area * depth return(vol) def bankaccount(x,add): dollars = 2.57 print("Currently, you have " + str(dollars) + " in your bank account") if add == 1: dollars = dollars + x # evaluate right, then assign to left else: dollars = dollars - x return("you now have " + str(dollars) + " in your bank account") #again, function ends when the return statement is executed. print(bankaccount(0.10,1) print(bankaccount(1.0, 0)

22 Remember this? Better! from random import * def beloworabove2():
from random import * def beloworabove(): if (randrange(-10,10) < 0): return("random number is below 0") elif (randrange(-10,10) == 0): return("random number is 0") elif (randrange(-10,10) > 0): return("random number is above 0") print(beloworabove()) Better! from random import * def beloworabove2(): x = randrange(-10,10) if (x < 0): return("random number is below 0") elif (x == 0): return("random number is 0") elif (x > 0): return("random number is above 0") print(beloworabove2())

23 Variables: from random import * def f(x): y = randrange(0,10) if (x > 0): y = y + x # Do the right side first, then put # that value into the left side. return(y) elif (x < 0): y = y - x else: return y print(f(7)) print(f(-2))

24 Variables: def sqr(x): x = x*x return(x) print(sqr(3)) print(sqr(-2))

25 Variables from random import * def ag(k): x = randrange(1,10) if (k == 2): x = x +randrange(1,10) elif (k == 3): x = x + randrange(1,10)+randrange(1,10) elif (k == 4): x = x + randrange(1,10)+randrange(1,10)+randrange(1,10) x = x/k return x print(ag(3)) print(ag(4)) print(ag(2))

26 Variables from random import * def jackpot(): x = randrange(1,10) y = randrange(1,10) print("x is "+str(x)+", y is "+str(y)) return (x==y) print(jackpot())

27 Shortcuts >>> x = 4 >>> x +=2 #same as x = x + 2 >>> x 6 >>> x -=7 #same as x = x >>> x *= 32 #same as x = x * >>> x /=8 #same as x = x/8 -4.0

28 Example: def f(p1,p2): if p1>p2: x = p1-p2 else: x = p2-p1 if (x%2) == 1: # x is now what value? x+=1 # Now what is x? x/=2 # and now what is x? return(x) print(f(7,2)) print(f(24,82))

29 Input from user: What if we want to ask the user to input something?
We can use input! answer = input(“Is this your favorite class?”) Takes what you typed in and places it in the variable, answer. It’s always a string unless we convert it to another type if (answer == “yes”): return (“You get an A!”) else: return(“You fail.”)

30 Input The input function always returns a string type.
def getage_1(): x = input(“How old are you?”) if x< 16: return(“You can’t drive”) else: return(“Get your license”) print(getage_1()) def getage_2(): x = input(“How old are you?”) x = int(x) if x < 16: return(“You can’t drive”) else: return(“Get your license”) print(getage_2()) The input function always returns a string type. what you type in in response to the question is always considered a string. If you want it to be an int, you must convert it.

31 Why should I use a variable here?:
def f(): k = input("What is your favorite color?") if (k == 'blue'): return("You love harmony, are reliable, sensitive and always make an effort to think of others. You like to keep things clean and tidy and feel that stability is the most important aspect in life.") elif (k == 'red'): return(“you live life to the fullest and are tenacious and determined in their endeavors.") elif (k == 'green'): return("you are often affectionate, loyal and frank. Green lovers are also aware of what others think of them and consider their reputation very important. ") elif (k == 'yellow'): return("you enjoy learning and sharing your knowledge with others. Finding happiness comes easy to you and others would compare you to sunshine. ") elif (k == 'purple'): return("you are artistic and unique. You have a great respect for people but at times can be arrogant.") elif (k == 'brown'): return("you are a good friend and try your hardest to be reliable and dependable. Flashy objects are not something you desire; you just want a stable life.") print(f())

32 x = int(input("heads or tails? (1 or 0) ")) y = randrange(0,2)
from random import * def f(): x = int(input("heads or tails? (1 or 0) ")) y = randrange(0,2) if x == y: return("You guessed right! You both guessed " + str(x)) else: return("You’re wrong. You guessed "+str(x)+" and computer generated "+str(y)) print(f())

33 While Loop def ThreeYearOld(): x = "" while (x != "Because."):
x = input("But why?") return("Oh. Okay.") print(ThreeYearOld()) Look at this code: What must be true in order for the loop to start? This is the starting condition!! What will make the loop end? What must become false? This is the stopping condition!! Does something INSIDE the loop that changes so that eventually the loop will end?

34 Generic While Loops: While Loops: What value does this code return?
def f(x): counter = 0 while counter < x: #counter<x is the condition that must be true for the loop to continue! # code can go here counter = counter + 1 return(counter) print(f(5)) While Loops: Continues while condition is true Must initialize to make condition true in while loops we stop when the while condition is false. Something inside the loop must change so that the condition becomes false eventually. What value does this code return?

35 What does this print? def f(x): counter = 0 while counter < x:
print(counter) counter = counter + 1 return(counter) print(f(5))

36 What does this print? def f(x): counter = x while counter > 0:
print(counter) counter = counter - 1 return(counter) print(f(5))

37 What does this print? def f(x): counter = 0 while counter < 30:
print(counter) counter = counter + x return(counter) print(f(4))

38 What does this print? def f(x): total = 0 counter = 0
while counter < x: total = total + counter counter = counter + 1 return(total) print(f(6))

39 What does this do? def f(x): total = 0 counter = 0
while counter < x: total = total + x counter = counter + 1 return(total) print(f(6)) print(f(4)) print(f(5))

40 What does this print? def f(x): counter = 0 while counter < 2:
x = x + “an” counter = counter + 1 x = x+”a” return(x) print(f(“a b”))

41 While Loops: loop must have a True/False condition
while count >= 1: While loops starts when the condition is True It continues to loop while the condition is True It stops looping when the condition is False Something must change inside the loop that will eventually make the True/False condition False count = count -1

42 While loops Starting condition? What makes the loop stop?
def f(total): while count >= 1: print(“bla”) count = count -1 return(total) print(f(0)) Starting condition? What makes the loop stop? What inside the loop changes so that the loop will stop?

43 While loops def f(total, count): while count >= 1: print(“glub”) count = count + 1 return(total) print(f(0, 4)) Starting condition? What makes the loop stop? What inside the loop changes so that the loop will stop?

44 While loops def f(total, count): while count != 0: print(“blug”) count = count - 2 return(total) print(f(0, 4)) Starting condition? What makes the loop stop? What inside the loop changes so that the loop will stop?

45 While loop rules: We must initialize values BEFORE entering the while loop count = 0 answer = “anything” We must make sure the while loop condition is initially true to enter the loop: while count < 5: while answer != “because” We must make sure that something inside the loop changes so that the while loop condition will become false at some point! count = count + 1 answer = input(“But why?”)

46 Differences (syntactic):
We can initialize variables used by the while loop inside the function (BUT BEFORE THE WHILE LOOP!) def f(): x = 5 counter = 0 while counter < x: print(counter) counter = counter + 1 return(counter) print(f()) def f(x, counter): while counter < x: print(counter) counter = counter + 1 return(counter) print(f(5, 0))

47 What does this do? def w2(x,y): tot = 0 while (y > 0): tot += x y -= 1 return(tot) print(w2(3,5)) print(w2(4,6))

48 How about this? def f(x): while(x < 100):
if (x**2 - 3 *x - 4) == 0: print(str(x) + " solves the equation ") x = x + 1 return(“done”) print(f(-100))


Download ppt "What is printed out? def f(x): print(x+3) return(x + 7) def g(k): return(f(k) + 2) print(g(1)) 4 10 def f2(x): return(x + 7) print(x+3) def g2(k): return(f2(k)"

Similar presentations


Ads by Google