0% found this document useful (0 votes)
15 views16 pages

Python Day 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views16 pages

Python Day 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

PYTHON FUNTIONS

INTRODUCTION
• A function is a block of organized, reusable code that is used to perform a single, related action. Functions
provide better modularity for your application and a high degree of code reusing.

Defining a Function
• You can define functions to provide the required functionality. Here are simple rules to define a function
in Python.
• Function blocks begin with the keyword def followed by the function name, parentheses ( ( ) ) and
colon(:) and statements are intended.
• Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation string of the function
or docstring.
• The statement return [expression] exits a function, optionally passing back an expression to the caller. A
return statement with no arguments is the same as return None.
FUNCTION SYNTAX
• By default, parameters have a positional behavior and you need to inform them in the same order
that they were defined.

def functionname( parameters ):


#"function_docstring"
Body of the function
return [expression]

• EXAMPLE : A example of the function declaration is given below which prints the str.
def printme( strg):
string=strg
return string
Var=printme("This prints a passed string into this function" )
print(Var)

• OUTPUT : This prints a passed string into this function


ARGUMENT PASSING
• A function is passed by the following types of formal arguments:

i. Positional argument - Arguments passed to a function in a correct position order.


ii. Default argument – It takes the default value of the argument provided in the function definition if a
function call has no argument at that place.
iii. Keyword argument - Using the keyword argument, the argument passed in a function call will match
with the function defined on the basis of the name of the parameter.
iv. Variable-length argument - Process a function with more arguments than we have specified in the
function definition.
POSITIONAL ARGUMENT PASSING
• Positional arguments are the arguments passed to a function in a correct position order.
• The number of arguments in the function call and function definition should be matched.

# function definition
def add(x,y):
x,y=15,20
print(x+y)

# call to the function


add(x,10)
add(x,x)
add(y,x)

OUTPUT
25
30
35
DEFAULT ARGUMENT PASSING
• Default argument takes the default value of the argument provided in the function definition if
a function call has no argument at that place.

def stu(Name,Id,Age=20):
print( "Name of the student:",Name)
print("Id of the student:",Id)
print("Age of the student:",Age)

# function call 1
print("Details of student 1 is:")
stu('Apoorva','16/Ibs/013',18)

OUTPUT
Details of student 1 is:
Name of the student: Apoorva
Id of the student: 16/Ibs/013
Age of the student: 18
KEYWORD ARGUMENT PASSING

• Using the keyword argument, the argument passed in a function call will
match with the function defined on the basis of the name of the parameter.

def stu(Name,Id,Age):
print( "Name of the student:",Name)
print("Id of the student:",Id)
print("Age of the student:",Age)
# Function call 1
print("Details of student 1 is:")
stu(Name='Apoorva',Id='16/Ibs/013',Age=18)

OUTPUT
Details of student 1 is:
Name of the student: Apoorva
Id of the student: 16/Ibs/013
Age of the student: 18
VARIABLE ARGUMENT PASSING
• To process a function with more arguments than we have specified in the function definition.
These types of arguments are called variable length argument. These are represented as
*args and **kargs.
i. Compare(*cmp) will take any number of arguments.
ii. The function call will take the argument as a tuple.
iii. The for loop will get all the values from the tuple.

def compare(*cmp):
print(type(cmp))
print(cmp)
for arg in cmp:
print(arg)
# function call 1
compare( 10,20,'str')

OUTPUT
<class 'tuple'>
(10, 20, 'str')
10
20
str
PRE – DEFINED FUNCTIONS

Python provides many built-in functions


1. print ()
2. abs ()
3. round ()
4. map ()
5. range ()

1. Print () :
 It is used to print the given content inside the command prompt.
 The default functionality of Python print is that it adds a newline character at the end.

EXAMPLE

print("Hello World")
2. abs() :
 It returns the absolute value for the given number. Absolute value of a number is the value without considering
its sign.
 If the input is an integer, the return value also will be an integer.
 If the input is a float, the return value will also be float.
 If the input is a complex number, the return value will be the magnitude of the input.

EXAMPLE:

int_num = -25
float_num = -10.50

print("The absolute value of an integer number is:", abs(int_num))


print("The absolute value of a float number is:", abs(float_num))
3. round ():
It will return you a float number that will be rounded to the decimal places which are given as input.
If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.

SYNTAX: round(float_num, num_of_decimals)


PARAMETERS:
• float_num: the float number to be rounded.
• num_of_decimals: (optional) The number of decimals to be considered while rounding. It is optional, and if not specified, it
defaults to 0, and the rounding is done to the nearest integer.

EXAMPLE: OUTPUT:
import decimal Using round() 15.46
round_num = 15.456

final_val = round(round_num, 2)
print("Using round()", final_val)
4. map()
It applies a function on all the items of an iterator given as input. An iterator, for example, can be a list, a tuple, a set,
a dictionary, a string, and it returns an iterable map object.
Syntax:
map(function, iterator1,iterator2 ...iteratorN)
Parameters
•function: A mandatory function to be given to map, that will be applied to all the items available in the iterator.
•iterator: An iterable compulsory object. It can be a list, a tuple, etc. You can pass multiple iterator objects to map()
function.

EXAMPLE: OUTPUT:
def myMapFunc(n): [20, 30, 40, 50, 60, 70, 80, 90]
return n*10
my_set = {2,3,4,5,6,7,8,9}
finalitems = map(myMapFunc, my_set)
print(list(finalitems))
5. range()
it gives a sequence of numbers based on the start and stop index given. In case the start
index is not given, the index is considered as 0, and it will increment the value by 1 till the
stop index.
 Syntax
range(start, stop, step)
Parameters
• start: (optional) The start index is an integer, and if not given, the default value is 0.
• stop: The stop index decides the value at which the range function has to stop. It is a
mandatory input to range function. The last value will be always 1 less than the stop value.
• step: (optional).The step value is the number by which the next number is range has to
be incremented, by default, it is 1.

EXAMPLE: OUTPUT:
print(list(range(10))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
IMPORTING FUNCTIONS BETWEEN TWO FILES

 SYNTAX
from file_name import function_name
exec(open(‘file_name').read()) // To read the imported file

 There are different ways to import a module and function in python. Lets discuss about that
in detail.
 In the above example, we have imported a module named PySimpleGUI and accessing the
module using the variable ‘sg’.
 We can also import a python script into an another python script.
from filename import *
[* will import all the function of the imported file]
ASSIGNMENT

1. Write a Python function that accepts a string and calculates and returns the number of upper case and lower case letters.
Example string: “Hello All, welcome to Python”.
2. Write a Python function to print the even numbers from a given list.
Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9]
3. Write a Python function to create and print a list where the values are square of numbers between 10 and 50(both included).
4. Write a python function to find the largest number in a separate file and import that script in another file and find the square.
5. Write a python function to get an input paragraph from the user:
i) count the number of letter “a”.
ii) Replace the letter with “r”
iii) count the number of words in paragraph.
THANK YOU

You might also like