Functions in Python
What are Functions?
Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code.
How do you write functions in Python?:
Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:
def my_function(): print "Hello From My Function!"
Functions may also receive arguments (variables passed from the caller to the function). For example:
def function_with_args(username, greeting): print "Hello, %s , via Function!, I wish you %s" %(username, greeting)
Functions may return a value to the caller, using the keyword- 'return' . For example:
def sum(a, b): return a + b
How do you call functions in Python?
Simply write the function's name followed by (), placing any required arguments within the brackets. For example, lets call the functions written above (in the previous example):
# print a simple greeting my_function() #prints - "Hello, John Doe, From My Function!, I wish you a great year!" function_with_args("John Doe", "a great year!") # after this line x will hold the value 3! x = sum(1,2) print x