Functions – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Sun, 17 May 2020 05:22:39 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg Functions – Shishir Kant Singh https://shishirkant.com 32 32 187312365 Python Functions https://shishirkant.com/python-functions/?utm_source=rss&utm_medium=rss&utm_campaign=python-functions Sun, 17 May 2020 04:28:48 +0000 http://shishirkant.com/?p=321 FUNCTIONS

If a group of statements is repeatedly required then it is not recommended to write these statements every timeseparately.We have to define these statements as a single unit and we can call that unit any number of times based on our requirement without rewriting. This unit is nothing but function.

The main advantage of functions is code Reusability.

Note:
In other languages functions are known as methods, procedures, subroutines etc.

Python supports 2 types of functions

  1. Built in Functions
  2. User Defined Functions

Built in Functions:
The functions which are coming along with Python software automatically, are called built in functions or pre-defined functions

Ex:
id()
type()
input()
eval()
etc..

User Defined Functions:
The functions which are developed by programmer explicitly according to business requirements ,are called user defined functions.

Syntax to create user defined functions:
def function_name(parameters) :
       doc string"""
---------
---------
return value

Note:
While creating functions we can use 2 keywords

  • def (mandatory)
  • return (optional)
Ex 1: Write a function to print Hello
test.py

def wish():
    print("Hello Good Morning")
wish()
wish()
wish()

Parameters
Parameters are inputs to the function. If a function contains parameters,then at the time of calling,compulsory we should provide values otherwise,otherwise we will get error.

Ex: Write a function to take name of the student as input and print wish message by name.

def wish(name):
    print("Hello",name," Good Morning")
wish("SEED")
wish("DHARSHI")

D:\Python_classes>py test.py
Hello SEED Good Morning
Hello DHARSHI Good Morning

Return Statement:
Function can take input values as parameters and executes business logic, and returns output to the caller with return statement.

Q. Write a function to accept 2 numbers as input and return sum.

def add(x,y):
    return x+y
result=add(10,20)
print("The sum is",result)
print("The sum is",add(100,200))

D:\Python_classes>py test.py
The sum is 30
The sum is 300

If we are not writing return statement then default return value is None

Ex:
def f1():
print(“Hello”)
f1()
print(f1())

Output
Hello
Hello
None

Returning multiple values from a function:

In other languages like C,C++ and Java, function can return atmost one value. But in Python, a function can return any number of values.

Ex 1:
def sum_sub(a,b):
sum=a+b
sub=a-b
return sum,sub
x,y=sum_sub(100,50)
print(“The Sum is :”,x)
print(“The Subtraction is :”,y)

Output
The Sum is : 150
The Subtraction is : 50

Types of arguments

def f1(a,b):
---------
---------
f1(10,20)

a,b are formal arguments where as 10,20 are actual arguments

There are 4 types are actual arguments are allowed in Python.

  • positional arguments
  • keyword arguments
  • default arguments
  • Variable length arguments

These are the arguments passed to function in correct positional order.

def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)

The number of arguments and position of arguments must be matched. If we change the order then result may be changed.

If we change the number of arguments then we will get error.

keyword arguments:
We can pass argument values by keyword i.e by parameter name.

Ex:
def wish(name,msg):
print(“Hello”,name,msg)
wish(name=”SEED”,msg=”Good Morning”)
wish(msg=”Good Morning”,name=”SEED”)

Output
Hello SEED Good Morning
Hello SEED Good Morning

Here the order of arguments is not important but number of arguments must be matched.

Note:
We can use both positional and keyword arguments simultaneously. But first we have to take positional arguments and then keyword arguments, otherwise we will get syntaxerror.

def wish(name,msg):
print(“Hello”,name,msg)
wish(“SEED”,”GoodMorning”) ==>valid

wish(“SEED”,msg=”GoodMorning”) ==>valid wish(name=”SEED”,”GoodMorning”) ==>invalid

SyntaxError: positional argument follows keyword argument

Default Arguments:
Sometimes we can provide default values for our positional arguments.

Ex:
def wish(name=”Guest”):
print(“Hello”,name,”Good Morning”)
wish(“SEED”)
wish()

Output
Hello SEED Good Morning
Hello Guest Good Morning

If we are not passing any name then only default value will be considered.

Note:
After default arguments we should not take non default arguments

def wish(name=”Guest”,msg=”Good Morning”): ===>Valid
def wish(name,msg=”Good Morning”): ===>Valid
def wish(name=”Guest”,msg): ==>Invalid

SyntaxError: non-default argument follows default argument

Variable length arguments:
Sometimes we can pass variable number of arguments to our function,such type of arguments are called variable length arguments.

We can declare a variable length argument with * symbol as follows

def f1(*n):

We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.

Ex:
def sum(*n):
total=0
for n1 in n:
total=total+n1
print(“The Sum=”,total)
sum()
sum(10)
sum(10,20)
sum(10,20,30,40)

Output
The Sum= 0
The Sum= 10
The Sum= 30
The Sum= 100

Note:
We can mix variable length arguments with positional arguments.

Ex:
def f1(n1,*s):
print(n1)
for s1 in s:
print(s1)
f1(10)
f1(10,20,30,40)
f1(10,”A”,30,”B”)

Output
10
10
20
30
40
10
A
30
B

Note: After variable length argument, if we are taking any other arguments then we should provide values as keyword arguments.

Ex:
def f1(*s,n1):
for s1 in s:
print(s1)
print(n1)
f1(“A”,”B”,n1=10)

Output
A
B
10

f1(“A”,”B”,10) ==>Invalid
TypeError: f1() missing 1 required keyword-only argument: ‘n1’

Types of Variables

Python supports 2 types of variables.

  1. Global Variables
  2. Local Variables

Global Variables

  • The variables which are declared outside of function are called global variables.
  • These variables can be accessed in all functions of that module.

Ex:
a=10 # global variable
def f1():
print(a)
def f2():
print(a)
f1()
f2()

Output
10
10

Local Variables:

  • The variables which are declared inside a function are called local variables.
  • Local variables are available only for the function in which we declared it.i.e from outside of function we cannot access.

Ex:
def f1():
a=10
print(a) # valid
def f2():
print(a) #invalid
f1()
f2()

NameError: name ‘a’ is not defined

global keyword:

We can use global keyword for the following 2 purposes:

  • To declare global variable inside function
  • To make global variable available to the function so that we can perform required modifications

Ex 1:
a=10
def f1():
a=777
print(a)
def f2():
print(a)
f1()
f2()

Output
777
10

]]>
321
Programming C- Functions https://shishirkant.com/programming-c-functions/?utm_source=rss&utm_medium=rss&utm_campaign=programming-c-functions Tue, 12 May 2020 18:02:47 +0000 http://shishirkant.com/?p=156 FUNCTIONS

Function:-  It is a self contained block of statements and it can be used at several multiple times in a program but defined only once.

Library function or Predefined functions:-  The functions which are in built with the C-compiler is called as library functions. Ex:- printf, scanf, getch(), clrscr(); etc.,

User defined function:-  User can defined functions to do a task relevant to their programs.  Such functions are called as user defined functions.

            Any function has three things.  They are…

1. Function declaration

2. Function definition

3. Function calling.

            In case of pre-defined functions the function declaration is in header files, definition is in C Libraries and calling is in your source program.

            But in case of user defined functions all the three things are in your source program.

Function declaration:-

Syntax:-
  Returntype func_name([Arg List]);

Example:-Void test();
Int sum(int , int );
Function definition:-
Syntax:- 
returntype func_name([Arg List])
{
Body;
}

Function calling:-
Syntax:- func_name([Arg List]);

The arguments which we given at the time of function declaration or  definition are called arguments or formal arguments.

The arguments which are given at the time of function calling are called actual arguments or parameters.

void:- (Empty data type)

#include<stdio.h>
#include<conio.h>
void main()
{
  void test( ); /declaration/
  clrscr();
  test( ); /calling/
  getch();
}
void test() /definition/
{
   printf(“welcome to c functions:”);
}

Rules for creating and accessing user defined functions:-   

  1. A function can be called by any number of times.
  2. A function may or may not receive arguments.
  3. A function may or may not return a value.
  4. If a function does not return any value the function return data type will be specified as “void”
  5. If a function returns a value only one value can be returned.
  6. We cannot specify any return data type, the function returns on integer value by default.
  7. The returning value must be return with a statement “return”.
  8. If a function returns a value, the execution of return statement should be last
  9. If a function returns a value, the returning value should match with the function return data type.
  10. A function is executed when a function is call by its name.
  11. Before a function call, function declaration or definition must and should
  12. A function definition may be placed before or after the main function.
  13. If a function call, function definition can be specified any where in the program
  14. If a function definition is specified before the function called then the function declaration is not necessary.
  15. The function definition should not be terminated with semicolon( ; )

Return:- Exits immediately from the currently execution of function to the calling rotated optionally returning a value.

Syntax:- return [<expression>];

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
 int sum(int,int);
 int a,b,n;
 clrscr();
 printf("Enter any two values:");
 scanf("%d%d",&a,&b);
 n=sum(a,b);
 printf("Sum is %d",n);
 getch();
}
int sum(int x,int y)
{
 return x+y;
}

Function Prototypes and category of functions:

A Function depending and whether arguments are present or not and a value is returned or not, may belong to one of the following categories.

  • Category 1: Function with no arguments and no return value
  • Category 2: Function with arguments and no return value
  • Category 3: Function with arguments and return value.
  • Category 4: Function with no arguments and return value.
  1. Function with no arguments and no return value:-

When a function has no arguments it does not receive any data from the calling function.  Similarly when it does not return a value the calling function does not receive any data from the called function. In affect there is no data transfer between the calling function and the called function.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void sum(); /declaration;/
clrscr();
sum(); /calling;/
getch();
}
void sum() /* definition*/
{
  int a,b;
  printf("Enter any two values:");
  scanf("%d%d",&a,&b);
  printf("Sum is %d\n",a+b);
}

2.Function with arguments and no return value:-

In this type the function has some arguments, it receive data from the calling function but it does not return any value.  The calling function does not receive data from the called function.  So there is one way data communication calling function and the called function.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void sum(int, int); /declaration;/
int a,b;
clrscr();
printf("Enter any two values:");
scanf("%d%d",&a,&b);
sum(a,b); /calling;/
getch();
}
void sum(int x, int y) /* definition*/
{
   printf("Sum is %d\n",x+y);
}

3.Function with arguments and return value:-

In this type the function has some arguments. It receives data from the calling function.  Similarly it returns a value.  The calling function receive data from the called function.  So it is a two way data communication between the calling function and the called function.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int sum(int,int);
int a,b,n;
clrscr();
printf("Enter any two values:");
scanf("%d%d",&a,&b);
n=sum(a,b);
printf("Sum is %d",n);
getch();
}
int sum(int x,int y)
{
  return x+y;
}

4. Function with no arguments and return value:-

In this type the function has no arguments. It does not receive data from the calling function.  But it returns a value the calling function receive data from the called function.  So it is a one way data communication between called function and the calling function.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int sum(); /declaration;/
int s;
clrscr();
s=sum(); /calling;/
printf("Sum is %d",s);
getch();
}
int sum() /* definition*/
{
  int a,b;
  printf("Enter any two values:");
  scanf("%d%d",&a,&b);
  return a+b;
}

CALL BY VALUE:

  • In call by value method, the value of the variable is passed to the function as parameter.
  • The value of the actual parameter can not be modified by formal parameter.
  • Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter.

Note:

  • Actual parameter – This is the argument which is used in function call.
  • Formal parameter – This is the argument which is used in function definition
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY VALUE):
  • In this program, the values of the variables “m” and “n” are passed to the function “swap”.
  • These values are copied to formal parameters “a” and “b” in swap function and used.
#include<stdio.h>
  // function prototype, also called function declaration
void swap(int a, int b);
int main()
{
  int m = 22, n = 44;
   // calling swap function by value
  printf(" values before swap m = %d \nand n = %d", m, n);
  swap(m, n);
}
void swap(int a, int b)
{
  int tmp;
  tmp = a;
  a = b;
  b = tmp;
  printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22

CALL BY REFERENCE:

  • In call by reference method, the address of the variable is passed to the function as parameter.
  • The value of the actual parameter can be modified by formal parameter.
  • Same memory is used for both actual and formal parameters since only address is used by both parameters.
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):
  • In this program, the address of the variables “m” and “n” are passed to the function “swap”.
  • These values are not copied to formal parameters “a” and “b” in swap function.
  • Because, they are just holding the address of those variables.
  • This address is used to access and change the values of the variables.

#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf(“values before swap m = %d \n and n = %d”,m,n);
swap(&m, &n);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf(“\n values after swap a = %d \nand b = %d”, *a, *b);
}

OUTPUT:
values before swap m = 22 and n = 44
values after swap a = 44
and b = 22
]]>
156