Let’s first look at a void function, as they are the simplest form of function. Additionally, we’re not going to pass any variables into this function. That means, every time it is called, the exact same thing will run.
#define our function, hello_world
def hello_world() :
print("hello world")
# call our function
hello_world()
The first line of our function, is called the function header. It starts with def, letting python know we are defining a function, and gives the name of the function, as well as the parameters, if any.
The indented lines are the function body, or block. Everything indented after the def, will execute as a normal set of Python commands. You can call other functions, if statements, loops, etc.
A function can even call itself. This is called recursion. Typically you want to avoid this if possible, but sometimes it is necessary. If don’t poorly, it will create an infinite loop of calling the function, and hang your application.
To call a function, you specify the function name, with a set of parenthesis after it, in this case, hello_world()
.
A Function calling another Function
Since we’ve mentioned that a function can call another function, let’s see an example of this.
def foo() :
print("inside foo, about to call hello_world")
hello_world()
print("done calling hello_world")
#define our function, hello_world
def hello_world() :
print("hello world")
# call our functions
hello_world() # we can still call the first function directly
foo() # we call our second function, which calls our first function
Local Variables
Inside a function, you can define a variable which is only accessible inside the function.
Scope is the term that describes where a variable can be used. Variables can be used only inside the functions where they are created. This helps minimize issues in case two functions use the same variable name.
def hello() :
name = input("What is your name:")
print("Hello, ", name)
hello()
# name is not accessible here because it is not in the right scope,
# as it was created in the hello function
Calling Simple Functions in Python was originally found on Access 2 Learn