Python Functions

Python Functions

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Creating and Calling a Function

def my_function():
  print("Hello from a function")

// Call the function my_function()


Arguments

Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

Arguments Example

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil") my_function("Tobias") my_function("Linus")


Return Values

To let a function return a value, use the return statement:

Return Value Example

def my_function(x):
  return 5 * x

print(my_function(3)) print(my_function(5)) print(my_function(9))


Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly.