TOPIC: Python functions - Function definition, function call, parameters and arguments
Python function
A function is a reusable block of code that performs a specific task or set of tasks. Functions are
essential for organizing and modularizing your code, making it more readable, maintainable, and
efficient.
Need for functions:
1. Code Reusability: Functions allow you to reuse code, reducing duplication and making programs
more
efficient.
2. Abstraction: Functions provide a higher-level view of operations, simplifying complex processes
and
improving code readability.
3. Modularity: Functions break down programs into manageable modules, enhancing design and
maintenance.
4. Parameterization: Functions accept parameters, making them adaptable for different scenarios and
data.
5. Encapsulation: Functions encapsulate functionality, enabling changes within a function's scope
without affecting the rest of the code.
def greet(): print("Hello, World!")
def greet_person(name): print(f"Hello, {name}!")
greet()
greet()With parameters:
greet_person("Alice")We can also return the values as:
result = add(5, 3) print("5 + 3 =", result)Default Parameters:
def greet_with_default(name="World"): print(f"Hello, {name}!")Arbitrary Arguments:
def sum_numbers(*args): total = 0 for num in args: total += num return total
LAMBDA Functions or Anonymous Functions
Lambda functions are not defined as other functions using the def keyword, rather they are created
using the lambda keyword. They have no function name, and can take any number of arguments. But they
can return just one value in the form of an expression. They are a one-line version of a function and hence cannot contain multiple expressions. They also cannot access the global variables.
For your understanding, kindly go through the video and also the code example below...
Code as discussed in the video:
# functions
# user-defined functions
# '''function definition'''
# def function_name():
# pass
# '''function call'''
# function_name()
# print("this is a statement")
# parameter - variables to be used in the function
# def newFunc(x, y):
# return x - y
# a = 10
# b = 5
# callFunc = newFunc(a, b)
# print("the value is", callFunc)
# def func():
# for i in range(4):
# print("Hello world")
# func()
'''
def newFuncs(x, y):
return x * y
# newFuncs(5) will give error because the argument and the parameter do not match
printValue = newFuncs(5, 10)
print(printValue)
'''
# default argument
# def display(name, course="BCA"):
# print("Name:", name)
# print("Course:", course)
# my_name = "Rajjit"
# display(my_name)
# lambda function
'''
syntax: lambda argument: expression
'''
# def sum(x, y):
# print(x + y)
# sum(12, 8)
# sum2 = lambda x, y : x + y
# print(sum2(12, 12))
# Q. write a program to check whether two number are equal or not
def check(a, b):
if(a == b):
print("a and b are equal")
elif (a > b):
print("a is greater than b")
else:
print("a is lesser than b")
check(5, 12)
You can copy and run this code