Lab 1 - A Simple Function

In python we can declare a function using the syntax def function_name():

A function begins with def, has a name in lower case, with words separated by underscores to improve readability, a set of () which contain parameters (more on this later) and ends in :.

Here is a very simple function that when it is called will return hello world.

  • In the top section of the Cloud9 IDE, you can write your program. To do this click on the + to open a New File or use ^ N

  • In the editor at the top add the following:

# A function that prints hello world
def hello_world():
    print('hello world')

# This line calls (runs) the function
hello_world()
  • Save the file using file > save or command + s with the name lab_1_hello_world.py. The py on the end denotes that it is a python file.

  • To run the program, enter the following command in the terminal:

    python lab_1_hello_world.py.

  • This should return hello world.

Congratulations! You have just written your first python program. Things to note:

  • The hash # symbol is used for comments. Anything after this on that line is ignored by python.
  • The function is defined using def.
  • The function has a name hello_world.
  • The next line is indented to show it is inside the function.
  • The function is called by last line hello_world().

What happens if you omit the final line hello_world()?

Check your answer

Returning information from a function

When a function performs some kind of activity, by default the information it remains contained within the boundary of the function. To pass the information to other parts of your code, you need to use return. The value the function returns is called the return value and it is passed back to the line which called the function.

  • Modify lab_1_hello_world.py as follows:
# A function that returns hello world
def hello_world():
    return 'hello world'

# Assign the hello_world() function to a variable.
greeting = hello_world()
print(greeting)

What did we do?

  • You created a function called hello_world().
  • In the first example, you used print() to display the output directly to the console.
  • In the second example, you used return to return the string hello_world to the point in the code where the function was called.
  • You assigned the hello_world() function to a variable called greeting.
  • You printed out the value of the variable greeting.

What did python do?

  • In the first example, python calls the hello_world() function and prints out the string using print(hello_world).
  • In the second example, python assigns the hello_world() function to a variable and stores the returned value.