Functions are defined with three components:

1. The header, which includes the def keyword, the name of the function, and any parameters the function requires. Here’s an example:

def hello_world(): # There are no parameters

2. An optional comment that explains what the function does.

"""Prints 'Hello World!' to the console."""

3. The body, which describes the procedures the function carries out. The body is indented, just like conditional statements.

print "Hello World!"

Pass a variable/parameter to a function

def func1(Name):
  """Prints the name passed to it"""
  print Name

func1(jack)

Name is referred to as the ‘parameter’ passed to the function

Multi parameter functions

def func1(FirstName, LastName):
  """Prints the name passed to it"""
  print FirstName + LastName

func1(jack, johnson)

Functions calling Functions

def func1(m):
  """Adds 1 to the parameter passed"""
  return m + 1

def func2(n)
  """Adds 2 to the parameter passed"""
  return funct(n) + 1

Import all functions from a library

import math

Import all functions from a library without having to call them the lengthy way (math.sqrt)

from math import *

Leave a Reply

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