1 / 57

# Function (in Python) - PowerPoint PPT Presentation

Function (in Python). g(x) = x 3 + 1 g(2) = 9 g(5) = 126. def g(x): return(x ** 3 + 1). Function (in Python). g(x) = x 3 + 1 g(2) = 9 g(5) = 126. def g(x): return(x ** 3 + 1) To Call the Functions (to make them run): g(2) g(5)

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about ' Function (in Python)' - john-mckee

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

• g(x) = x3 + 1

• g(2) = 9

• g(5) = 126

def g(x):

return(x ** 3 + 1)

• g(x) = x3 + 1

• g(2) = 9

• g(5) = 126

def g(x):

return(x ** 3 + 1)

To Call the Functions (to make them run):

g(2)

g(5)

To see what the function calculates (returns):

print (g(2))

print (g(5))

func(x,y) = x*y

func(2,7) = 14

func(5,4) = 20

• Calculate the area of a rectangle?

• Name of function?

• Input?

• Output?

• Test cases?

• Calculations?

Can we now write the function?

def arearectangle(len,width):

return(len*width)

func(x) = (x-32)/1.8

func(68) = 20.0

func(22) = -5.5556

• Function name?

• f_to_c

• Input?

• An integer (the fahrenheit temperature)

• Output?

• A float (the celsius temperature)

• Calculations?

• (ftemp – 32) / 1.8

• Test Cases?

• f_to_c(68) -> 20.0

• f_to_c(22)->-5.5556

def f_to_c(ftemp):

return((ftemp - 32 )/ 1.8)

3 newfunc 27

5 newfunc 3125

2 newfunc 4

5,3 newfunc2 2

18,6 newfunc2 0

7,2 newfunc2 1

3,4,2 newfunc3 5

7,6,2 newfunc3 10

4,21,6 newfunc3 7

• def newfunc(par1):

• return(par1**par1)

• def newfunc2(par1,par2):

• return (par1 % par2)

• def newfunc3(par1, par2, par3):

• return(par1+(par2//par3))

• print(newfunc(3))

• print(newfunc(5))

• print(newfunc(2))

• print(newfunc2(5,3))

• print(newfunc2(18,6))

• print(newfunc2(7,2))

• print(newfunc3(3,4,2))

• print(newfunc3(7,6,2))

• print(newfunc3(4,21,6))

#This function calculates the square of the input value

#and returns that squared value

#input: an integer

#output: an integer

#Test Cases:

# print(newfunc(3)) -> 27

# print(newfunc(5)) -> 3125

# print(newfunc(2))-> 4

#Author: Debra Yarrington

#Sept 6, 2011

def newfunc(par1):

return(par1**par1) # returns the square

• Comments aren’t executed (aren’t converted to machine language). Python’s compiler ignores them. They’re for people who are reading your code.

• They also can be used to help you (and others) understand what you are doing and why

• 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

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

• Remember: after we use a function, what remains is what is returnedfrom the function

return(x + y)

return(x + y)

def div(x,y,z):

print(div(7,3,2))

return(x + y)

def div(x,z):

print(div(7,2))

return(x + y)

def div(y,x):

print(div(7,2))

return(x + y)

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

def Squr(par1):

return(par1 ** 2)

def dbl(par2):

return(par2 + par2)

What does this get us?

def Func1(p1,p2):

return(Squr(p1) - Squr(p2))

print(Func1(4,3))

def Func2(p1,p2,p3):

return(Squr(p1) * Func1(p2,p3))

print(Func2(2,3,2))

def Func3(p1,p2):

return(dbl(Squr(p1)))

print(Func3(4))

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

32 if x > 0

_

f(x) = x

0 otherwise

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?

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 * -1) ** 3 + 2 * x)

else:

return (-1)

f(3) # this equals?

f(0) # this equals?

f(-2) # this equals?

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?

def f(x):

if x > 5:

return (x*4)

elif x > 4:

return(x * 6)

elif x == 4:

return (x*3)

else:

return(x*2)

print(f(5)) # what is printed?

print(f(4)) # what is printed?

print(f(3)) # what is printed?

def f(x):

if x != 10:

return (x * 2)

else:

return (x ** 2)

print(f(6))

print(f(12))

print(f(10))

def f(x):

if x < 10:

return (x+9)

elif x < 5:

return (x + 4)

elif x < 0:

return (x)

else:

return(0)

print(f(-1)) ?

return(par1 + "ubba")

Aside: str

• Can’t add a string with a number:

• Can’t: print(“puddle” + 4)

• Can add strings to strings!

• New word of the day: Concatenate = join (string + string)

• Can: print(“puddle” + “ jumping”)

• Can: print(“puddle” + “4”)

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

• using * to multiply numbers and * to make multiple copies of a string

• Second new word of the day

• What if we want to print a parameter?

• Example:

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?

• We want to see what ftemp holds (what’s inside of the parameter ftemp)

• Try:

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

• Doesn’t work (why?)

def 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

• def makestr(x):

• if (dow(x) !="Error"):

• return("Today is " + dow(x))

• else:

• print (makestr(4))

• print (makestr(9))

• def makestr(x):

• if (dow(x)=="Error"):

• else:

• return("Today is " + dow(x))

• print (makestr(9))

• print (makestr(-1))

def dow(x):

if (x == 1):

return("Sunday")

elif (x == 2):

return("Monday")

elif (x == 3):

return("Tuesday")

elif (x == 4):

return("Wednesday")

elif(x == 5):

return("Thursday")

elif (x == 6):

return("Friday")

elif (x == 7):

return ("Saturday")

else:

return("Error")

print(dow(3))

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

def ReturnSomething(value):

if value = 1:

return “glub”

else:

return “blug”

print (ReturnSomething(1))

def q(x):

if (x>5) or (x < 10):

return("just enough")

elif (x > 5) or (x < 15):

return("too much")

else:

return("no idea")

print(q(13))

def q(x):

if (x>5) and (x < 10):

return("just enough")

elif (x > 5) and (x < 15):

return("too much")

else:

return("no idea")

print(q(7))

if ((x<10) and (x >5)) or ((x <30 ) and (x > 25)):

return(“hi")

else:

return(“low")

q(2)

q(20)

q(27)

q(8)

Versus:

def s(x):

if (x<10) and ((x >5) or (x<30 )) and (x > 25):

return(“hi")

else:

return(“low")

s(2)

s(20)

s(27)

s(8)

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

else:

return(str(x) + " is not a multiple of 3")

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

What is returned?

print(eqcheck(4))

#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(isDivisable(15,5,3))

print(isDivisable(150,5,3))

# Is this what we want ?

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

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

• print (g(17))

def q(x):

if (x>5) and (x < 10):

return("just enough")

elif (x > 5) and (x < 15):

return("too much")

else:

return("no idea")

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

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

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

• Input: 6 integers:

• your project score, your lab score, your exam score and the percent worth of projects, labs, and exams.

• Output: A string

• Calculation:

• yourproj * proj/100 + yourlab * lab/100 + yourexam * exam/100.

• If the total > 90, return an“A”

• If the total is between 80 and 89, return a “B”

• If the total is between 70 and 79, return a “C”

• If the total is between 60 and 69, return a “D”

• Otherwise, return an “F”

Ugly and inefficient

if (yourproj*(proj/100)+yourlab*(lab/100)+yourexam*(exam/100)) >= 90:

return (“A”)

elif (yourproj*(proj/100)+yourlab*(lab/100)+yourexam*(exam/100))>= 80:

return (“B”)

elif (yourproj*(proj/100)+yourlab*(lab/100)+yourexam*(exam/100))>= 70:

return (“C”)

elif (yourproj*(proj/100)+yourlab*(lab/100)+yourexam*(exam/100))>= 60:

return (“D”)

else

return (“F”)

Prettier, but still inefficient

def getTot(yp,yl,ye,p,l,e):

return(yp * p/100 + yl * l/100 + ye * e/100)

if getTot(yourproj, yourlab, yourexam,proj,lab,exam) >= 90:

return (“A”)

elifgetTot(yourproj, yourlab, yourexam,proj,lab,exam) >= 80:

return (“B”)

elifgetTot(yourproj, yourlab, yourexam,proj,lab,exam) >= 70:

return (“C”)

elifgetTot(yourproj, yourlab, yourexam,proj,lab,exam) >= 60:

return (“D”)

else

return (“F”)

Pretty and efficient!

def getTot(yp,yl,ye,p,l,e):

return(yp * p/100 + yl * l/100 + ye * e/100)

yourscore = getTot(yourproj, yourlab, yourexam,proj,lab,exam)

if yourscore >= 90:

return (“A”)

elifyourscore >= 80:

return (“B”)

elifyourscore >= 70:

return (“C”)

elifyourscore >= 60:

return (“D”)

else

return (“F”)

• A variable is a name we give to a space in memory.

• We put values into that space, and then use the name as if it is the value.

y= 3 # note we’re using = not ==!

• This says y now holds the value 3, just like parameters

def f(x): #simple example

y = 3 # y only exists within this function

return(x + y)

def f(x):

y=3

y=y+x # do the right side first, then put

# that value into the left side

return(y**2) # this is where the function ends

f(5)

def calcvol(length,width,depth):

area = length * width #area only exists inside this function

vol = area * depth

return(vol)

dollars = 2.57

print(“Currently, you have “ + str(dollars) + “ in your bank account”)

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

>>> x = 4

>>> x +=2

>>> x

6

>>> x -=7

>>> x

-1

>>> x *= 32

>>> x

-32

>>> x /=8

>>> x

-4.0

>>>

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

How can we do it with this?

def getTot(yp,yl,ye,p,l,e):

return(yp * p/100 + yl * l/100 + ye * e/100)

yourscore = getTot(yourproj, yourlab, yourexam,proj,lab,exam)

if yourscore >= 90:

return (“A”)

elifyourscore >= 80:

return (“B”)

elifyourscore >= 70:

return (“C”)

elifyourscore >= 60:

return (“D”)

else

return (“F”)

def loanqualifier(x,y):

if (x >= 35000):

if (y >= 2):

return("Congratulations! You qualify!")

else:

return("You will qualify in " + str(round(2-y) ,2)+ " years.")

else:

if (y>=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))

• return (“You get an A!”)

• else:

• return(“You fail.”)

• What if we want to ask the user to input their salary and years of work?

• We can use input!

• answer = input(“Do you love this 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

def getage_2():

x = input(“How old are you?”)

x = int(x)

if x < 16: #works

return(“You can’t drive”)

else:

print(getage_2())

def getage_1():

x = input(“How old are you?”)

return(“You can’t drive”)

else:

print(getage_1())

Original:

def loanqualifier(x,y):

if (x >= 35000):

if (y >= 2):

return("Congratulations! You qualify!")

else:

• return(“Youqualify in "+ str(round(2-y),2)+" years.")

else:

if (y>=2):

return("You must make at least 35000 to qualify.")

else:

return("I'm sorry, you don't qualify.")

New:

def loanqualifier():

x=int(input(“Enter salary: ”))

y = float(input(“Enter years at current job: ”))

if (x >= 35000):

if (y >= 2):

return("Congratulations! You qualify!")

else:

return(“Youqualify in "+str(round(2-y),2)+" years.")

else:

if (y>=2):

return("You must make at least 35000 to qualify.")

else:

return("I'm sorry, you don't qualify.")

print(loanqualifier()

What if we want to ask the user to input their salary and years of work?

def calcsomething(par1):

if ((par1%2) == 1):

return(par1 * -1)

else:

return(par1)

def finddif(par1,par2):

var1 = calcsomething(par1)

if (var1 < 0):

var1 = 0

var2 = calcsomething(par2)

if (var2 < 0):

var2 = 0

if ((var1 - var2) < 0):

return(var2 - var1)

else:

return(var1 - var2)

print(finddif(3,7))

print(finddif(4,7))

print(finddif(2,4))

def MakeDate(par1,par2,par3): var1 = "Today is " var1 += GetDOW(par1) var1 += ", " var1 += GetMonth(par2) var1 += " " var1 += "20"+str(par3) return(var1)print(MakeDate(6,9,12)

def GetMonth(x):

if (x == 1):

return("January")

elif (x == 2):

return("February")

elif (x == 3):

return("March")

elif (x == 4):

return("April")

elif(x == 5):

return("May")

elif (x == 6):

return("June")

elif (x == 7):

return ("July")

elif (x == 8):

return("August")

elif (x == 9):

return("September")

elif (x == 10):

return("October")

elif(x == 11):

return("November")

elif (x == 12):

return("December")

def GetDOW(x):

if (x == 1):

return("Sunday")

elif (x == 2):

return("Monday")

elif (x == 3):

return("Tuesday")

elif (x == 4):

return("Wednesday")

elif(x == 5):

return("Thursday")

elif (x == 6):

return("Friday")

elif (x == 7):

return ("Saturday")

def fu1(x):

y = x*3

if (y < 0):

y = y * -1

elif (y < 10):

y = y + 4

return(y)

print(fu1(-2))

def fu2(x):

y = x*3

if (y < 0):

y = y * -1

if (y < 10):

y = y + 4

return(y)

print(fu2(-2))

• Libraries: Math:

from math import *

• Imports all functions and variables inside the math library.

• Pi is defined inside the math library.

• We could also do:

import math

print (func(2))

• We can use the round function to truncate

• We could round:

def func3(x,y):

return(round((x/y),3))

print func3(10,3))

• Another examle:

from math import *

print func(3))

• One more examle:

from math import *