Skip to content

Latest commit

 

History

History
226 lines (171 loc) · 8.51 KB

Trivedh_Python_Functions.md

File metadata and controls

226 lines (171 loc) · 8.51 KB

Functions in Python

Definition:

Function is a block of code or set of statements that performs a specific task and executes only when called. Complex projects can be broken down into smaller tasks.These small tasks can contain multiple lines of code and can be used multiple times in the same program.


Syntax Example
def function-name(): def palindrome():

In the above syntax:

def - to declare/define the function
function-name- name of the function
() - required to distinguish between a variable and function and end the definition with a semi-colon

Example

def greet():
  print("Hello")
  print("Im a student")

greet()
Using the above function you can print the greet message multiple times by just calling the function multiple times instead of making the code redundant with print lines.

There are two basic types of Functions:

  • Built-in Functions
  • User Defined Functions

Built-in Functions:


Built-in functions are part of Python language.These are the functions readily available for the use.

Examples

Function Description
max() Returns the largest item in an iterable
min() Returns the smallest item in an iterable
input() To accept the input from the user

User defined Functions:


User defined functions are not in-built and are not a part of Python programming language.Any name can be given to the function.These are the functions are defined according to the need of the user to carry out the tasks.

Examples

Function Description
def sub(x,y):
  diff=x-y
  print(diff)

sub(7,4)
Prints the difference between two numbers

Functions can return values

When does a function return a value?


Consider the given two scenarios:
  1. Hey Sohal, Please inform boss that I'll be late to the office today.
  2. Hey Sohal, May i know when does the meeting start?

Clearly in the first scenario,The speaker is just asking his friend Sohal to inform his boss that he will be late today. But, he's not expecting a reply. He is just informing. Whereas in the second case, the speaker is asking his friend about the meeting time. Therefore he's expecting a reply in return.
In a similar way, the functions will also return the values required after the computation. It can be clearly explained by the below provided example.


Example:

def add(x,y):
  c=x+y
  return c

result=add(5,4)
print(result)

Output: 9
In the above example, the value returned by the function stores in the variable "result" and the desired output is printed on the console.

Function returning two values:

A function can return two values in a similar way as the first one, but two variables have to be initialized to store the two values returned by the function after computation.

Example

def add_sub(x,y):
  c=x+y
  d=x-y;
  return c,d

result1,result2=add_sub(5,4)
print(result1,result2)

Function Arguments

Arguments are used to feed information to the functions i.e to pass the information. Any number of arguments can be passed. They are declared inside the parenthesis after the function name.

Example:

def add(x,y):
  c=x+y
  print(c)

add(5,4)

In the above code, the variables x and y are Formal arguments and numbers 5,4 are Actual Arguments

Types of Function Arguments:


  • Position Arguments
  • Keyword Arguments
  • Default Arguments
  • Variable Length Arguments
  • Keyworded Variable Length Arguments

Position Arguments


Positional Arguments are the arguments passed in a positional/sequential order. The number of arguments passed should match the function definition. If the arguments are passed in a non-sequential order, then function computation will throw an error.

Example:

def student(name,age):
  print(name)
  print(age)

student('paul',28)

Output: paul
             28
In the above example 'paul' and 28 were passed as actual arguments and they were assigned to the formal arguments in the declared function without an error,as they were passed in a sequential order.

Keyword Arguments


Keyword Arguments are used in the function call which passes the arguments along with a keyword. This facilitates the user to pass the arguments in a non positional order.If the sequence of the arguments is not known, keyword arguments can be used in a function call.

Example:

def student(name,age):
  print(name)
  print(age)

student(age=28,name='paul')
Output: paul
             28

Default Arguments


It's a type of argument which assumes a default value if a particular value is not mentioned in the function call.If a user does'nt provide a particular argument the default value in the function definition will be assigned autonomously to the that particular argument.

Example:

def student(name,age=18):
  print(name)
  print(age)

student('paul')
Output: paul
             18
Variable Length Arguments

Variable Arguments are the arguments used in the function calls when a function has to compute more arguments than the arguments in the function definition or when the accuracte value of arguments is not known.They are not named like Default or positional arguments.They are named withan asterisk before the variable-name that holds multiple or nonkeyword arguments.

Example:

def sum(a,*b):   c=a;
  for i in b:
   c=c+i
  print(c)

sum(5,6,34,78)


Output: 123

Keyworded Variable Length Arguments


Keyworded Variable Arguments are the arguments with a special syntax **kwargs in function definitions in python is used to pass a keyworded,variable-length argument list.

Example:

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

myname(first ='John', mid ='Mathew', last='roy')

Output: last == John
             mid == Mathew
             first == roy

Recursion

Recursion is a process of calling a function from the same function repeatedly. It means a defined function can call itself. It reduces the complexity of a program.

Example: Factorial using Recursion


def fact(n):
  if n==0:
   return 1
  return n*fact(n-1)
result=fact(5)
print(result)

Output: 120

Lamba or Anonymous Function

As the name suggests, these are the functions without any name.It's a kind of function, which is not defined in an usual manner with def. Lamba function returns only a single value. It can accept any number of arguments.It has to be assigned to a variable

Example 1

f = lambda a: a+a
result=f(5)
print(result)
Output: 10

Example 2

g = lambda b,c: b-c
result1=g(6,5)
print(result1)
Output: 1

You can find the execution of the above mentioned examples in the following Jupyter file

Trivedh_Python_Functions.ipynb