How to define a function in python?



Use of a function in Python

We have learnt few things in our last two posts about python. We started from the beginning with a python prgoram and continued with how to write a for loop in python

In this post I will discuss how to write and call a simple function in python. So let us start with simplest function. Start a python notebook as explained in my last posts or if you want to use terminal script then open any text editor and paste the following code. You can also run these codes on my blog at the end of each post.

def age(x):  
   return "Your age is", x
    
We defined a very simple function called age(x). This function just prints the value given to it. Let us check how to call it.

In [16]: age(20)
Out [20]: Your age is 20

We gave input 20 to the function and it printed "Your age is 20". Let us now go a level higher and try to write another function.

def square(x):
   f=x*x
   return
In [22]: square(87976)
Out[22]: 7739776576

In this function we can calculate square of any number in the argument.

How to use conditions if/else in python?

How to find roots of a quadratic equation in python?

So in this example we define a function which solves a quadratic equation of the form ax^2+bx+c.
We used also if condition to stop if the solution was complex.

import math
def roots(a,b,c):
   d = b**2-4*a*c # discriminant                 
   if d < 0:
       print "Solution is not real"
   elif d == 0:
       x = (-b+math.sqrt(b**2-4*a*c))/float(2*a)
       print "This equation has one solutions: ", x
   else:
       x1 = (-b+math.sqrt(b**2-4*a*c))/float(2*a)
       x2 = (-b-math.sqrt(b**2-4*a*c))/float(2*a)
   return "Two solutions: ", x1, " and", x2
roots(1,4,1)

How to approximate value of pi using python?

Let us write an approximate value of python using a series.
π = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
Now let us try to evaluate this value within some errors.
def series(n):
    return 4 / (2.0 * n + 1) * (-1) ** n
This function is a simple one where n defines is the nth term in the series.

def series(n):
   return 4 / (2.0 * n + 1) * (-1) ** n
def pi(err):
   last = series(0)  # starts series with first term
   new = series(0) + series(1)  #add first 2 terms
   n = 2  # define n to start while loop after first 2 terms

   while abs(last - new) > err:#while loop to check the error
       last = new #replace last with new
       new += series(n) #add to the series
       n += 1 #count iterations

   return new, n #returns the value and iterations needed
print pi(0.000001)

Here we called a function inside another function. Series is a function which we call in pi. Try to play with calling functions inside functions. Funception :)

How to find nth root of a number using Newton's method in python?

def nthroot(k, n):    a, b = n, n+1    while a < b:        b = a        t = (k-1) * b + n /float(pow(b, k-1))        a = t /float(k)    return b print nthroot(2,3)

How to solve a differential equation using Euler's method in Python?


This is another example of how to call a function inside another function.
import math
def  euler(f,y0,t0,n,h): #define function to use Euler's method
    t,y = t0,y0 #y0,t0 are initial values for variable y and t
    while t <= n:# n defines number of steps to iterate
        t += h # h is the time step we want to have in each iteration
        y += h * f(t,y) # guess the numerical value for the current step
        print t,y #print the values 
def func(x, t): #function we want to integrate: y'=func(x,t)
        return 2/x+math.sin(5*t)# you can put any random function here
euler(func,0,0,100,0.01) # this is how we call function euler and give func as an argument.
You could now try few things in python and in the next post we will learn how to plot functions, write data to file and plot the data using python. You can write me if you need any help or if something is not clear.

Try to run programs here

You can run the code I wrote above here. You can just copy paste and try to run. You can also write your own small programs here and test them. At the end open a text editor, copy program and save it on your computer. Start a terminal and run it as python yourprogram.py.

Comments

Popular Posts