Functions

Defining Functions

  • For defining a function in python we use def(define) followed by function_name() and colon

  • Make sure that the function name is meaningful and descriptive

  • Function names are generally given in snake_case in python

def greet():
    print("Hi there")
    print("Welcome abroad")
    
greet()

Arguments and Parameters

  • A parameter is an input that we define for our function

  • In the below example, first_name and last_name are parameters

  • While an argument is an actual value for a given parameter ("Ankit", "Choudhary" are arguments)

def greet(first_name,last_name):
    print(first_name + " " + last_name))
    print("Welcome aboard")  
    
greet("OoBA","Labs")

Types of Functions

Perform a Task

  • Below is a sample function in python

  • In Python, all functions by default return None values

Return a Value

Arguments in Function

  • Specifying the name of a parameter with an argument is called a keyword argument

  • For example: "number=1" is a keyword argument in the next example

Keyword Argument

Default Argument

  • All the parameters which we define for a function are required by default

  • We can make a parameter optional by specifying the default value while defining the function

  • In the below given example "by" is having 1 as default value if no value is passed as an argument

  • All the optional parameters must be defined after the required parameters.

Xargs, Variable number of arguments

  • We can pass a variable number of arguments to a function by using * before the parameter name

  • The variable arguments will be stored in a tuple and can be iterated.

  • Note that variable arguments parameter should be at the end of function parameters

XXargs

  • We can also pass multiple "key: value" pairs by using ** before the parameter name

  • Note that variable arguments parameter should be at the end of function parameters

Scope of a Function

Global Variable

  • A Global variable is will be accessible throughout the file and inside each and every function

  • Global variables stay for a longer period of time in a program until it is garbage collected, so we should not use them often

  • If the same variable is defined in a function's scope, the local variable will override the global variable

  • Here in function greet, the global variable "message" will be used While in the function send_mail as message variable is defined locally so that will be used.

Last updated

Was this helpful?