Python Lesson 16: Creating and using functions

  1. Write and call a simple Function in Python
  2. Write a function that takes a parameter
  3. Write a function that takes a parameter that has a default value
  4. Return a value in an Function

A function is a block of code which only runs when it is called.  A function can take in data and return data.

  1. Write a simple Function in Python
  2. Write a function that takes a parameter

1) Write and call a simple Function in Python

To write a function in python start with the def keyword + function name +  open and closed parenthesis + a semicolon

#Hello world Function
def HelloWorld():
    print("Hello World")
Notebook Output
#Call the HelloWorld Function
HelloWorld()
Notebook Output

2) Write a function that takes a parameter

Parameters in Python functions are put in between the open and closed parenthesis after the function name.

#Hello Function with a parameter
def Hello(name):
    print("Hello " + name)

Hello("Henry")
Notebook Output

3) Write a function that takes a parameter that has a default value

Default parameters are put in between the open and closed parenthesis after the function name and after the parameter name with an equal sign. If a parameter is not specified in the function call then the function will use the default value.

#Hello Function with a parameter
def Hello(name = "BOB"):
    print("Hello " + name)

#Call and return default parameter
Hello()
#Call and return parameter
Hello("John")
Notebook Output

4) Return a value in an Function

To return a value in a Python function use the return keyword

#Return a value in a Function
def add(value1, value2):
    return value1 + value2

answer = add(4,5)
print(answer)
Notebook Output

Recommended Books