Functions

Let's say that we have some code that does some task, but the code is 25 lines long, we need to run it over 1000 items and it doesn't work in a loop. How in the world will we handle this situation? That is where functions come in really handy. Functions are a generalized block of code that allow you to run code over and over while changing its parameters if you so choose. Functions may take (arguments) that you are allowed to change when you call the function. It may also return a value.

A function must be defined before you can call it. To define a function, we use the following syntax:

def <function name>(arg0, arg1, arg3,...):
    #code here must be indented.
    #you can use arg0,...,argn within the function
    #you can also return things
    return 1
    #This code returns 1 no matter what you tell the function

Functions can take as many arguments as you wish, but they may only return 1 thing. A simple example of a familiar function is any mathematical function. Take sin(x), it is a function that takes one argument x and returns one value based on the input. Let's get familiar with functions.


In [4]:
def add1(x):
    return x+1

print(add1(1))

def xsq(x):
    return x**2

print(xsq(5))

for i in range(0,10):
    print(xsq(i))


2
25
0
1
4
9
16
25
36
49
64
81

The true power of functions is being able to call it as many times as we would like. In the previous example, we called the square function, xsq in a loop 10 times. Let's check out some more complicated examples.


In [21]:
def removefs(data):
    newdata=''
    for d in data:
        if(d=="f" or d=="F"):
            pass
        else:
            newdata+=(d)
    return newdata

In [22]:
print(removefs('ffffffFFFFFg'))


g

In [23]:
intro='''##Functions
Let's say that we have some code that does some task, but the code is 25 lines long, we need to run it over 1000 items and it doesn't work in a loop. How in the world will we handle this situation? That is where functions come in really handy. Functions are a generalized block of code that allow you to run code over and over while changing its parameters if you so choose. Functions may take **(arguments)** that you are allowed to change when you call the function. It may also **return** a value.

A function must be defined before you can call it. To define a function, we use the following syntax:

    def <function name>(arg0, arg1, arg3,...):
        #code here must be indented.
        #you can use arg0,...,argn within the function
        #you can also return things
        return 1
        #This code returns 1 no matter what you tell the function
        
Functions can take as many arguments as you wish, but they may only return 1 thing. A simple example of a familiar function is any mathematical function. Take sin(x), it is a function that takes one argument x and returns one value based on the input. Let's get familiar with functions."'''
print(removefs(intro))


##unctions
Let's say that we have some code that does some task, but the code is 25 lines long, we need to run it over 1000 items and it doesn't work in a loop. How in the world will we handle this situation? That is where unctions come in really handy. unctions are a generalized block o code that allow you to run code over and over while changing its parameters i you so choose. unctions may take **(arguments)** that you are allowed to change when you call the unction. It may also **return** a value.

A unction must be deined beore you can call it. To deine a unction, we use the ollowing syntax:

    de <unction name>(arg0, arg1, arg3,...):
        #code here must be indented.
        #you can use arg0,...,argn within the unction
        #you can also return things
        return 1
        #This code returns 1 no matter what you tell the unction
        
unctions can take as many arguments as you wish, but they may only return 1 thing. A simple example o a amiliar unction is any mathematical unction. Take sin(x), it is a unction that takes one argument x and returns one value based on the input. Let's get amiliar with unctions."

In [24]:
def removevowels(data):
    newdata = ''
    for d in data:
        if(d=='a' or d=='e' or d=='i' or d=='o' or d=='u' or d=='y'):
            pass
        else:
            newdata+=d
    return newdata

In [25]:
print(removevowels(intro))


##Fnctns
Lt's s tht w hv sm cd tht ds sm tsk, bt th cd s 25 lns lng, w nd t rn t vr 1000 tms nd t dsn't wrk n  lp. Hw n th wrld wll w hndl ths sttn? Tht s whr fnctns cm n rll hnd. Fnctns r  gnrlzd blck f cd tht llw  t rn cd vr nd vr whl chngng ts prmtrs f  s chs. Fnctns m tk **(rgmnts)** tht  r llwd t chng whn  cll th fnctn. It m ls **rtrn**  vl.

A fnctn mst b dfnd bfr  cn cll t. T dfn  fnctn, w s th fllwng sntx:

    df <fnctn nm>(rg0, rg1, rg3,...):
        #cd hr mst b ndntd.
        # cn s rg0,...,rgn wthn th fnctn
        # cn ls rtrn thngs
        rtrn 1
        #Ths cd rtrns 1 n mttr wht  tll th fnctn
        
Fnctns cn tk s mn rgmnts s  wsh, bt th m nl rtrn 1 thng. A smpl xmpl f  fmlr fnctn s n mthmtcl fnctn. Tk sn(x), t s  fnctn tht tks n rgmnt x nd rtrns n vl bsd n th npt. Lt's gt fmlr wth fnctns."

So clearly we can do some powerful things. Now let's see why these functions have significant power over loops.


In [31]:
def fib(n):
 a,b = 1,1
 for i in range(n-1):
  a,b = b,a+b
 return a

def printfib(n):
    for i in range(0,n):
        print(fib(i))

printfib(15)


1
1
1
2
3
5
8
13
21
34
55
89
144
233
377

Here, using loops within functions allows to generate the fibonacci sequence. We then write a function to print out the first n numbers.

Exercises

  1. Write a function that takes two arguments and returns a value that uses the arguments.
  2. Write a power function. It should take two arguments and returns the first argument to the power of the second argument.

  3. is a semi-guided exercise. If you are stumped ask for help.

3a. Write a function that takes the cost of a dinner as an argument and returns the cost after a .075% sales tax is added.

3b. Write a function that takes the cost of a dinner and tax and adds a 20% tip to the total, then returns the total.

3c. Write a function that takes a list of food names(choose them yourself) as an argument and returns the cost of purchasing all those items.

3d. Write a function that takes a list of food names as an argument and returns the total cost of having a meal including tax and tip.

4 . In the next cell is a 1000-digit number, write a function to solve Project Euler #8 https://projecteuler.net/problem=8


In [44]:
thoudigits = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450

Lambda

Next we will look at a special type of function called a lambda. A lambda is a single line, single expression function. It is perfect for evaluating mathematical expressions like x^2 and e^sin(x^cos(x)). To write a lambda function, we use the following syntax:

func = lambda <args>:<expression>

for example:

xsq = lambda x:x**2
xsq(4) #returns 16

Lambdas will return the result of the expression. Let's check it out.


In [54]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#^^^Some junk we will learn later^^^

func = lambda x:np.exp(np.sin(x**np.cos(x)))
#^^^The important part^^^

plt.plot(np.linspace(0,10,1000), func(np.linspace(0,10,1000)))
#^^^We will learn this next^^^


Out[54]:
[<matplotlib.lines.Line2D at 0x7f27abb6d8d0>]

Exercises

  1. Write a lambda for x^n where x and n are arguments.

  2. Write a function that removes all instances of the letters "p", "h", "y", "s", "i", "c", "s" from any string. Then prints the new string out.

  3. Write a function that does the same thing as in, that is, write a function that takes two arguments, a variable and a list and check if the variable is in the list. If it is, return True, otherwise, return False.

  4. The factorial function takes a number n and returns the product n*(n-1)*(n-2)... Write this function.

  5. If you want to retrieve the 4th digit of a number, first convert it to a string using the str() command, then take the value at index [3]. Using this information and your factorial function from 4. solve Project Euler #20 https://projecteuler.net/problem=20.


In [ ]: