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
# This line calls (runs) the function
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.
file > save
command + s
To run the program, enter the following command in the terminal:
This should return hello world.
Congratulations! You have just written your first python program. Things to note:
What happens if you omit the final line hello_world()?
If you omit the final line hello_world() the python interpreter does not call the function, so nothing will happen. Try it out by editing the file and removing it.
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.
# A function that returns hello world
return 'hello world'
# Assign the hello_world() function to a variable.
greeting = hello_world()