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

Python Function

The document provides an overview of functions in Python, explaining their definition, advantages, and types including built-in, user-defined, and lambda functions. It also covers concepts such as pass by value and reference, recursion, and variable scope and lifetime. Examples illustrate how to define and use functions effectively in Python programming.

Uploaded by

riyalmens
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Python Function

The document provides an overview of functions in Python, explaining their definition, advantages, and types including built-in, user-defined, and lambda functions. It also covers concepts such as pass by value and reference, recursion, and variable scope and lifetime. Examples illustrate how to define and use functions effectively in Python programming.

Uploaded by

riyalmens
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

1.What is Function?

Python Function
A function in Python is a block of code that performs a specific task. It is defined using the def keyword followed by the function name, parentheses, and a
colon.
Functions can take arguments as input and may return a value as output. They help to organize code, make it reusable, and improve readability.
Here's a basic example of a function:

def greet(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!")

greet("World") # Call the function


2. Advantage of function
Functions in Python provide several advantages:
Code Reusability: Functions allow you to write a block of code once and reuse it multiple times throughout your program, avoiding code duplication.
Modularity: They help break down complex tasks into smaller, manageable chunks, improving code organization and readability.
Maintainability: If you need to update a specific functionality, you only need to modify the function's code, and the changes will reflect everywhere the
function is called.
Overall, using functions makes your code more efficient, organized, and easier to understand and maintain.
3.Built in Function
Advantages
Efficiency: Built-in functions are generally optimized for performance and can be faster than writing your own code.
Convenience: They readily provide solutions for common tasks, saving you time and effort.
Readability: Using well-known built-in functions can make your code more concise and easier to understand.

Disadvantages
Limited Customization: Built-in functions may not always offer the precise functionality you need, requiring you to write your own functions or adapt your
logic.
Here are a few examples of built-in functions:
abs (): Returns the absolute value of a number.
x = -5
print(abs(x)) # Output: 5
max (): Returns the largest item in an iterable.
numbers = [1, 5, 2, 8]
print(max(numbers)) # Output: 8
sum (): Returns the sum of all items in an iterable.
numbers = [1, 2, 3, 4]
print(sum(numbers)) # Output: 10

all():Returns True if all items in an iterable object are true


numbers = [1, 2, 3, 4]
print(all(numbers)) # Output: True

ascii():Returns a readable version of an object and replaces non-ASCII characters with an ‘escape’ character
def print_ascii(text):
"""This function prints the ASCII representation of the given text."""
print(ascii(text))

print_ascii("Hello, world!")
print_ascii("你好,世界!")

Explanation
This code defines a function named print_ascii that takes a string as an argument and prints its ASCII representation. When called with the string "Hello,
world!", it will print the same string as it contains only ASCII characters. However, when called with the string " 你 好 , 世 界 ! ", which contains non-ASCII
characters, it will print a string with escaped characters like '\u4f60\u597d\uff0c\u4e16\u754c\uff01'.
About ASCII
ASCII stands for American Standard Code for Information Interchange. It's a character encoding standard used for electronic communication. ASCII codes
represent text in computers, telecommunications equipment, and other devices.
Essentially, it assigns a unique number to each letter, number, and symbol used in written English. These numbers are then used by computers to store and
process text.
However, ASCII has a limited set of characters and can't represent characters from other languages or many special symbols. This limitation led to the
development of broader encoding standards like Unicode.

bin(): Returns the binary version of a number

def print_binary(number):
"""This function prints the binary representation of a number."""
binary_number = bin(number)
print(f"The binary representation of {number} is {binary_number}")

# Get input from the user


number = int(input("Enter an integer: "))

# Call the function to print the binary representation


print_binary(number)

bool(): Returns the Boolean value of a specified object

This code defines a function called print_boolean that accepts any object as an argument.
Inside the function, it uses the bool() function to determine the object's boolean value (True or False) and prints the result to the console.
The code then demonstrates the usage of print_boolean by calling it with various objects like integers, strings, and lists. Each call shows how different objects
are evaluated in a boolean context (e.g., 0 is False, non-empty strings are True).
def print_boolean(obj):
"""This function prints the boolean value of an object."""
boolean_value = bool(obj)
print(f"The boolean value of {obj} is {boolean_value}")

# Test with different objects


print_boolean(0)
print_boolean(1)
print_boolean("")
print_boolean("Hello")
print_boolean([])
print_boolean([1, 2])
#### Find more Built in function if any then do the program!!!
User Defined Function
A user-defined function in Python is a block of reusable code that performs a specific task, defined by the user using the def keyword.
These functions enhance code organization, promote reusability, and make programs easier to read and maintain.
Here's an example:

def calculate_area(length, width):


"""This function calculates the area of a rectangle."""
area = length * width
return area

# Get input from the user


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
# Calculate the area using the function
area = calculate_area(length, width)

# Print the result


print(f"The area of the rectangle is: {area}")
Explanation
This code defines a function calculate_area that takes two arguments, length and width.
It calculates the area of a rectangle and returns the result.
The code then gets the length and width from the user, calls the function to calculate the area, and prints the result.
This demonstrates how user-defined functions encapsulate specific tasks, making code more modular and reusable.
We can call this function with different length and width values without rewriting the calculation logic each time.

Anonymous Function or Lambda Function


A lambda function in Python is a small, anonymous function defined using the lambda keyword. It can take any number of arguments but can only have one
expression.
Lambda functions are often used when you need a simple function for a short period and don't want to define a formal function using def.
Here's an example demonstrating the use of a lambda function:

# Define a lambda function to double a number


double = lambda x: x * 2

# Call the lambda function


result = double(5)

# Print the result


print(result) # Output: 10
In this code, lambda x: x * 2 defines a lambda function that takes one argument (x) and returns its value doubled. This lambda function is assigned to the
variable double.
We then call double(5), which executes the lambda function with the argument 5, resulting in 10 being printed to the console.
Lambda functions are particularly useful when used with functions like map, filter, and reduce where short, anonymous functions are needed for specific
operations on iterables.
NOTE: - In Python, an iterable is any object that can be looped over. It's a collection of items that can be accessed one by one.
Examples of iterables include lists, tuples, strings, dictionaries, and sets.

Pass by Value

In Python, integers are immutable. This means that when you pass an integer to a function, the function receives a copy of the integer. Any changes made to
the integer within the function will not affect the original integer.
Explanation:
The change_value function takes an integer x as an argument. Inside the function, the value of x is incremented by 1. The value of x is printed inside the
function. The value of x is printed outside the function. The output shows that the value of x inside the function is 6, but the value of x outside the function
remains 5. This is because the function received a copy of the integer x, and any changes made to the copy did not affect the original.
Code:
def change_value(x):
x=x+1
print("Inside function:", x)

x=5
change_value(x)
print("Outside function:", x)

Output: Tell me

Pass by Reference
In Python, lists are mutable. This means that when you pass a list to a function, the function receives a reference to the original list. Any changes made to the
list within the function will affect the original list.
Explanation:
The change_list function takes a list lst as an argument. Inside the function, the value 4 is appended to the list. The list is printed inside the function. The list
is printed outside the function. The output shows that the list inside the function is [1, 2, 3, 4], and the list outside the function is also [1, 2, 3, 4]. This is
because the function received a reference to the original list, and any changes made to the list within the function affected the original list.

def change_list(lst):
lst.append(4)
print("Inside function:", lst)

lst = [1, 2, 3]
change_list(lst)
print("Outside function:", lst)

Recursion

Recursion in programming is a technique where a function calls itself within its own definition. It's a powerful way to solve problems that can be broken
down into smaller, self-similar subproblems.
One of the main advantages of recursion is that it can make code more concise and easier to read for problems that naturally lend themselves to recursive
solutions.
For example, consider calculating the factorial of a number:

#Recursion
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
number = 5
result = factorial(number)
print("The factorial of", number, "is", result)
Explanation:
The function factorial(n) calculates the factorial of a non-negative integer n. Base Case: If n is 0, it returns 1 (factorial of 0 is 1). Recursive Step: If n is not 0,
it returns n multiplied by the factorial of n-1. This step breaks down the problem into smaller subproblems until it reaches the base case. When you run this
code with number = 5, it calculates 5! (5 factorial) which is 120.
How recursion works:
The factorial(5) function is called. Since 5 is not 0, it calculates 5 * factorial(4). factorial(4) is called, and it calculates 4 * factorial(3), and so on. This
continues until factorial(0) is called, which returns 1 (base case). The values are then returned back up the chain: 1 * 2 * 3 * 4 * 5, resulting in 120. This is a
classic example of how recursion can be used to solve problems by breaking them down into smaller, self-similar subproblems.

Scope and Life time of a variable


Scope of a variable refers to the region of the code where the variable is accessible.
Lifetime of a variable is the period during which the variable exists in memory.
Here's a program illustrating these concepts:

def my_function():
"""This function demonstrates local scope."""
x = 10 # x is local to this function
print("Value inside function:", x)

my_function()

# print("Value outside function:", x) # This would cause an error

y = 20 # y is global

def another_function():
"""This function demonstrates global scope."""
global y
print("Value inside function:", y)
y = 30

another_function()
print("Value outside function:", y)

In this code:
 x has a local scope – it only exists within my_function(). Trying to access it outside would cause an error.
 y has a global scope – accessible throughout the code. another_function() uses the global keyword to modify the global y.
The lifetime of x is limited to the execution of my_function(), while y exists as long as the program runs.
This example showcases how scope and lifetime differ for variables depending on where they're defined and how they're used.

You might also like