In python we can declare a function using the syntax def function_name():
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 :.
def
()
:
Here is a very simple function that when it is called will return hello world.
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
+
New File
^ 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.
file > save
command + s
lab_1_hello_world.py
To run the program, enter the following command in the terminal:
python lab_1_hello_world.py.
python lab_1_hello_world.py
This should return hello world.
Congratulations! You have just written your first python program. Things to note:
hello_world
hello_world()
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.
return
# 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)
print()
greeting
print(hello_world