Functions

Courses

Functions
To repeat lines of code, you can use a function. A function has a unique distinct name in the program. Once you call a function it will execute one or more lines of codes, which we will call a code block.

For example, we could have the Pythagoras function:

pythagoras

In case your math is a little rusty,  a^2 + b^2 = c^2. Thus, c = sqrt( a^2 + b^2). In code we could write that as:

import math

def pythagoras(a,b):
    value = math.sqrt(a *a + b*b)
    print(value)

pythagoras(3,3)

We call the function with parameters a=3 and b =3 on the last line.  A function can be called several times with varying parameters. There is no limit to the number of function calls.

The def keyword tells Python we define a function.  Always use four spaces to indent the code block, using another number of spaces will throw a syntax error.

It is also possible to store the output of a function in a variable.  To do so, we use the keyword return.

import math

def pythagoras(a,b):
    value = math.sqrt(a*a + b*b)
    return value


result = pythagoras(3,3)
print(result)

The function pythagoras is called with a=3 and b=3. The program execution continues in the function pythagoras. The output of math.sqrt(a*a + b*b) is stored in the function variable value. This is returned and the output is stored in the variable result. Finally, we print variable result to the screen.


While loop
Lists

6 thoughts on “Functions

  1. Reply
    Sebastian - February 13, 2016

    You got a small typo below the first block of code. I think it’s supposed to be ‘y=3’. 🙂

    1. Reply
      admin - February 18, 2016

      Thanks Sebastian!

  2. Reply
    Ayush - July 12, 2016

    How do you do addition and subtraction?
    By the way I am a beginner

    1. Reply
      admin - July 13, 2016
      def add(a,b):
          return a+b
      
      def sub(a,b):
          return a-b
      
      print( add(5,4) )
      print( sub(3,2) )
      
      
  3. Reply
    Napoleon - October 10, 2016

    When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three e-mails with the same comment. Is there any way you can remove people from that service? Cheers!

    1. Reply
      admin - January 19, 2017

      Removed your mail address, should be good now. Let me know if you still get mails

Leave a Reply

Your email address will not be published. Required fields are marked *