U4
U4
• Example:
def fun():
print("Welcome to GFG")
fun()
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?
my_function("Emil", "Refsnes")#arguments
Number of Arguments
not less.
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Types of Python Function Arguments
• Default argument
• Keyword arguments (named arguments)
• Positional arguments
• Arbitrary arguments (variable-length arguments
*args and **kwargs)
Default argument
def myFun(x,y=50): x: 10
print("x: ", x) y: 50
print("y: ", y)
myFun(10)
my_function("Sweden")
my_function()
my_function("India")
Practice Question…
print("\nCase-2:")
nameAge(27, "Suraj")
Practice Question…
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)
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.")
• 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
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
False
x =
x =
• Create a lambda function that takes one parameter (a) and returns
it.
• x=x=