0% found this document useful (0 votes)
11 views

U4

Uploaded by

moimr8866
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)
11 views

U4

Uploaded by

moimr8866
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/ 52

UNIT IV

FUNCTIONS, FILES AND MODULES

Functions - Introduction, inbuilt functions, user


defined functions, passing parameters -
positional arguments, default arguments,
keyword arguments, return values, local scope,
global scope and recursion. Files -Text files,
reading and writing files. Modules - create –
import.
Functions - Introduction
• Python Functions is a block of statements that return the
specific task.
• You can pass data, known as parameters, into a function.
• Python Function Declaration
Types of Functions in Python

• Built-in library function: These are Standard functions in Python


that are available to use.
• User-defined function: We can create our own functions based
on our requirements.
• Lambda functions : These are small anonymous functions
that can be defined in a single line of code. Lambda functions are
often used for quick, simple operations that don’t require a full
function definition.
• Recursive Functions: These functions call themselves to perform a
task repeatedly until a certain condition is met. Recursive functions
can be useful in situations where a problem can be broken down into
smaller sub-problems.
Calling a Function in Python

• After creating a function in Python we can call it by using the name

of the functions Python followed by parenthesis containing

parameters of that particular function. Below is the example for

calling def function Python.

• Example:

def fun():

print("Welcome to GFG")

fun()
Arguments

• Information can be passed into functions as arguments.

• Arguments are specified after the function name, inside the parentheses.

You can add as many arguments as you want, just separate them with a

comma.
• Example:
def my_function(fname):
print(fname)

my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?

• The terms parameter and argument can be used for the


same thing: information that are passed into a function.
• From a function's perspective:
• A parameter is the variable listed inside the parentheses in
the function definition.
• An argument is the value that is sent to the function when it
is called.
Example
def my_function(fname, lname):#Parameter
print(fname + " " + lname)

my_function("Emil", "Refsnes")#arguments
Number of Arguments

• By default, a function must be called with the

correct number of arguments. Meaning that if

your function expects 2 arguments, you have to

call the function with 2 arguments, not more, and

not less.
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Types of Python Function Arguments

• Python supports various types of arguments that can


be passed at the time of the function call.

• Default argument
• Keyword arguments (named arguments)
• Positional arguments
• Arbitrary arguments (variable-length arguments
*args and **kwargs)
Default argument

• A default argument is a parameter that assumes a default value if a value

is not provided in the function call for that argument.


• The default value is assigned by using the assignment(=) operator of the
form keyword name=value.

def myFun(x,y=50): x: 10
print("x: ", x) y: 50
print("y: ", y)
myFun(10)

Non-default arguments must be listed before default arguments in a


function's parameter list.
def myFun(x=12,y):
print("x: ", x)
print("y: ", y)
myFun(10)
Example
def greet(name, age=25):
print(f"Hello, {name}! You are {age} years old.")
greet("Alice", 30)
greet("Raja")
Find the Output????

def my_function(country = "Norway"):


print("I am from " + country)

my_function("Sweden")
my_function()
my_function("India")
Practice Question…

• Write a Python function to calculate the area of a rectangle.


The function should accept two arguments: length and
width. If the width is not provided, the function should
assume a default width of 5 units. The function should then
return the area of the rectangle.
Keyword Arguments

keyword arguments are arguments passed to a


function by explicitly specifying the parameter
name and its value. This allows you to pass
arguments in any order and makes the code more
readable, especially when a function has many
parameters.
Syntax of Keyword Arguments:
parameter_name=value
Example

def student(firstname, lastname):


print(firstname, lastname)
student(firstname='Geeks', lastname='Practice')
student(lastname='K', firstname='Hema')
Example

def my_function(child3, child2, child1):


print("The young child:" + child2)
my_function(child1="Ram",child2="Ramya",child3="Raja")
Practice Question…

• Write a function named introduce that takes three keyword

arguments: name, age, and city. The function should print a

sentence introducing the person using the provided

information. Then, call the function by passing the

arguments in different orders.


Positional arguments

• Position-only arguments mean whenever we pass


the arguments in the order we have defined
function parameters in which if you change the
argument position then you may get the
unexpected output.
Example
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
print("Case-1:")
nameAge("Suraj", 27)

print("\nCase-2:")
nameAge(27, "Suraj")
Practice Question…

• Write a function named add_numbers that takes three


positional arguments: num1, num2, and num3. The function
should return the sum of these three numbers. Call the
function by passing arguments in the correct order.
Arbitrary Arguments, *args

• If you do not know how many arguments that will be passed

into your function, add a * before the parameter name in

the function definition.

• *args in Python (Non-Keyword Arguments)

• **kwargs in Python (Keyword Arguments)

def my_function(*kid):
• Syntax:
*args in Python (Non-Keyword Arguments)

def my_function(*kids):
print("The youngest child:" + kids[2])
my_function("Ram","Ramya","Raja")
Example 2

def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
**kwargs in Python (Keyword Arguments)

• The double asterisk form of **kwargs is used to


pass a keyworded, variable-length argument
dictionary to a function.
• The reason is that the double star allows us to
pass through keyword arguments (and any
number of them).
Example 3
def myFun(**kwargs):
for key, value in kwargs.items():
print(value)
myFun(arg1='Hello', arg2='Welcome', arg3='to',
arg4='GeeksforGeeks')
Example
(Combining *args and **kwargs

def mixed_function(*args, **kwargs):


print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
mixed_function(1, 2, 3, name="Alice", age=25)
Scenario based Question

Write a Python function named process_data that accepts arbitrary


positional arguments (*args) and keyword arguments (**kwargs), and
performs the following tasks:
Positional arguments (*args):
Print the sum of all the numeric positional arguments passed to
the function.
Keyword arguments (**kwargs):
Print the count of keyword arguments.
Print each key-value pair on a new line in the format: key: value.
If no positional arguments are passed, the function should print "No
numeric arguments were passed.". If no keyword arguments are
passed, the function should print "No keyword arguments were
passed.".
def process_data(*args, **kwargs):
if args:
total=0
for value in args:
if isinstance(value, (int, float)):
total =value+total
print(f"Sum of positional arguments: {total}")
else:
print("No numeric arguments were passed.")

if kwargs:
print(f"Number of keyword arguments: {len(kwargs)}")
for key, value in kwargs.items():
print(f"{key}: {value}")
else:
print("No keyword arguments were passed.")

process_data(10, 20, 30,40, name='Alice', age=25)


Return values

• A return statement is used to end the execution of the


function call and “returns” the result (value of the
expression following the return keyword) to the caller.
The statements after the return statements are not
executed. If the return statement is without any
expression, then the special value None is
returned. Return statement can not be used outside the
function.
Syntax

• def fun():
statements
.
.
return [expression]
Example-1
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Example-2
def cube(x):
r=x**3
return r
print(cube(2))
Practice Question

• Define a function called add_numbers that takes two


parameters (e.g., num1 and num2).Inside the function,
calculate the sum of the two numbers. Use the return
statement to return the sum.
Python Local Variables

• Local variables in Python are those which are initialized

inside a function and belong only to that particular function.

It cannot be accessed anywhere outside the function.


Example:
def f():
s = "I love Geeksforgeeks"
print(s)
f()
Can a local variable be used outside a function?

• No, a local variable cannot be used outside of a function


in Python. Local variables are only accessible within the
function in which they are defined. Once the function
execution finishes, the local variable goes out of scope and
is destroyed.
def f():
• Example:
s = "I love Geeksforgeeks"
print(s)
f()
print(s)
Python Global Variables

• Variables which are defined outside any function and which


are accessible throughout the program, i.e., inside and
outside of every function.
• Example:

s = "I love Geeksforgeeks"


def f():
print(s)
f()
print(s)
s = "I love Geeksforgeeks"
def f():
s='Hello World'
print(s)
f()
print(s)
Quiz1??
x = 'awesome'
def myfunc():
x = 'fantastic'
myfunc()
print('Python is ' + x)

Python is awesome

Python is fantastic
Quiz2??
Insert the correct keyword to make the variable x belong to the global
scope.??

def myfunc():
-------- x
x = "fantastic"
What will be the printed result?

x = 'awesome'
def myfunc():
global x
x = 'fantastic'
myfunc()
print('Python is ' + x)

Python is awesome
Python is fantastic
Recursion
Example
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 5
print("The factorial of", num, "is: ",
factorial(num))
lambda function
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can
only have one expression.

Syntax:
lambda arguments : expression
Example
x = lambda a : a + 10
print(x(5))
Output:
15
x = lambda a, b : a * b
print(x(5, 6))
Output:
30
• True or False: Lambda functions can take multiple
arguments.

True
False

True or False: Lambda functions can have multiple expressions.

True
False
x =
x =

• Create a lambda function that takes one parameter (a) and returns
it.
• x=x=

You might also like