A Simple Python Function
Creating reusable code
In a previous lesson we learned that in Python a module is just a file with Python code and we learned about modules with useful functions that came when you installed Python.
What is a function? In Python a function is a piece of reusable code.
Let’s go back to our hello_world module and rewrite it to create our first function.
A function is created with the command def. Def is short for define.
Let’s call our new function pr_hworld.
def pr_hworld():
print ("Hello world!)Now run the program. It doesn’t do anything.
In order to use a function, you have to call it.
Notice that when you created the module with Idle 5 spaces were added in front of the word print. This is to show that you are creating a block of code (usually more than one line). In other computer languages it is recommended best practice. In Python it is mandatory. If you don’t have the spacing it won’t run.
You can call the function pr_hworld from within the module.
def pr_hworld():
print ("Hello world!:)
pr_hworld()Now if you run the program it will print Hello world! This is of course, rather silly since if you wanted to print Hello World! you could just write
print ("Hello World")But it does give you an idea of how functions work.
You can also import the module hello_world and use the function in any other module that you create.
In following lessons we are going to look at the import command and explore creating functions in a bit more detail.
Jim McAulay🍁 says, “ I called my wife from work and said that I wanted to eat out. She left a sandwich on the front doorstep.”
43–44
11–09






