Python Functions (def)

A function is a reusable block of code that performs a specific task. It is executed only when it is called. You can pass data, known as arguments, into a function to customize its behaviour. A function can also return a value as a result.

In Python, a function is defined using the def keyword followed by the function name, parentheses for arguments (if any), and a colon. The function body, containing the code to be executed, is indented below the definition.

def my_ctry(country = "Singapore"): # default is Singapore
    print("I am from " + country)

my_ctry("Sweden")
my_ctry("India")
my_ctry() # No argument. Use default (Singapore)
Sweden
India
Singapore

The above example also shows how to use a default parameter value. If we call the function without argument, it uses the default value, Singapore.

def times_five(x):
    return 5 * x

print(my_function(3))
print(my_function(5))
15
25

In this example, the return statement lets the function return a value.


Previous     Next

Use the Search Bar to find content on MarketingMind.