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:

Example:-

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

Calling a Function

To call a function, use the function name followed by parenthesis:

Example:-

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

my_function()

Function types

There are four types of functions in python
  • with argument and with return
  • with argument and without return
  • without argument and with return
  • without argument and without return

with argument and with return

def sum(a,b):
return a+b

x=int(input("Enter first number="))
y=int(input("Enter second number="))
print(sum(x,y))

with argument and without return

def sum(a,b):
print(a+b)

x=int(input("Enter first number="))
y=int(input("Enter second number="))
sum(x,y)

without argument and with return

def sum():
x=int(input("Enter first number="))
y=int(input("Enter second number="))
return x+y

print(sum())

without argument and without return

def sum():
x=int(input("Enter first number="))
y=int(input("Enter second number="))
print(x+y)

sum()

Argument types

There are three types of Arguments in python
  • Required (Positional) Arguments
  • Default Arguments
  • Arbitrary Keyword Arguments

Required (Positional) Arguments

Required arguments are the arguments passed to a function in correct positional order.The number of arguments in the function call should match exactly with the function definition.

Default Arguments

A default parameter is defined with a fallback value as a default argument. Such parameters are optional during a function call. If no argument is provided, the default value is used, and if an argument is provided, it will overwrite the default value.

def sum(a=2,b):
print(a+b)

x=int(input("Enter first number="))
sum(x)

Arbitrary Keyword Arguments

In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of arguments to a function using special symbols. There are two special symbols:

  • *args in Python (Non-Keyword Arguments)
  • **kwargs in Python (Keyword Arguments)

*args in Python (Non-Keyword Arguments)

def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'MKtutorial')

**kwargs in Python (Keyword Arguments)

def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

myFun(first='m', mid='k', last='tutorial')

Anonymous Functions in Python

In Python, an anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.
def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

print(cube(7))
print(cube_v2(7))

Python Variable Scope

In Python, we can declare variables in three different scopes: local scope, global, and nonlocal scope.

Python Local Variables

When we declare variables inside a function, these variables will have a local scope (within the function). We cannot access them outside the function.
def greet():
# local variable
message = 'Hello'
print('Local', message)

greet()

Python Global Variables

In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.
# declare global variable
message = 'Hello'

def greet():
# declare local variable
print('Local', message)

greet()
print('Global', message)

Python Nonlocal Variables

In Python, nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.
# outside function
def outer():
message = 'local'

# nested function
def inner():

# declare nonlocal variable
nonlocal message

message = 'nonlocal'
print("inner:", message)

inner()
print("outer:", message)

outer()

Python Packages

We usually organize our files in different folders and subfolders based on some criteria, so that they can be managed easily and efficiently. For example, we keep all our games in a Games folder and we can even subcategorize according to the genre of the game or something like this. The same analogy is followed by the packages in Python.

What is a Python Package?

Python modules may contain several classes, functions, variables, etc. whereas Python packages contain several modules. In simpler terms, Package in Python is a folder that contains various modules as files.

Creating Package

Let’s create a package in Python named mypckg that will contain two modules mod1 and mod2. To create this module follow the below steps:
  • Create a folder named mypckg.
  • Inside this folder create an empty Python file i.e. __init__.py
  • Then create two modules mod1 and mod2 in this folder.

mod1.py

def mk():
print("Welcome to MK")

mod2.py

def sum(a, b):
return a+b

Import Modules from a Package

We can import these Python modules using the from…import statement and the dot(.) operator.

Syntax:

import package_name.module_name
Now We will import the modules from the above-created package and will use the functions inside those modules.

from mypckg import mod1
from mypckg import mod2

mod1.mk()
res = mod2.sum(1, 2)
print(res)