Python Function
Python 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}!")
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
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.
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}")
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}")
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.
def my_function():
"""This function demonstrates local scope."""
x = 10 # x is local to this function
print("Value inside function:", x)
my_function()
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.