Python Day- 6
Python Day- 6
Introduction to functions and function calls, Function arguments (positional, default, keyword,
arbitrary arguments), Mutability and immutability, Built-in functions. Problems on above
concepts.
Function
A function is a block of reusable code that performs a specific task. Functions help in
modularizing code, making it more readable, reusable, and easier to debug.
● A function is a block of organized, reusable code that is used to perform a single, related
action.
● Functions provide better modularity for your application and a high degree of code reusing.
● There are two types of functions in Python: Built-in functions and User defined functions
● Python gives many built in functions like print(), len() etc. But we can also create our own
functions. These functions are called user defined functions.
# Function definition
def function_name(parameters):
"""Optional docstring to describe the function."""
# Function body
return value # Optional
# Function call
function_name(arguments)
Creating a Function
Function for addition of two numbers:
Note: a,b are called formal arguments while x, y are called actual arguments.
Positional Arguments
● During function call, values passed through arguments should be in the order of
parameters in the function definition. This is called positional 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.
keyword arguments
Default Arguments
● Default arguments are values that are provided while defining functions.
● The assignment operator = is used to assign a default value to the argument.
● Default arguments become optional during the function calls.
● If we provide value to the default arguments during function calls, it overrides the default
value.
● Default arguments should follow non-default arguments.
● If we call the function without argument, it uses the default value.
Variable-length positional arguments
● Variable-length arguments are also known as Arbitrary arguments.
● If we don’t know the number of arguments needed for the function in advance, we can
use arbitrary arguments
● For arbitrary positional argument, an asterisk (*) is placed before a parameter in function
definition which can hold non-keyword variable-length arguments.
● These arguments will be wrapped up in a tuple. Before the variable number of
arguments, zero or more normal arguments may occur.
Syntax:
def functionname(*var_args_tuple ):
function_statements
return [expression]
Variable length Keyword Arguments
● If you do not know how many keyword arguments that will be passed into your function,
add two asterisk (**) before the parameter name in the function definition.
● This way the function will receive a dictionary of arguments, and can access the items
accordingly.
What is Mutability?
Examples:
my_list = [1, 2, 3]
my_list[0] = 10
print(my_list) # Output: [10, 2, 3]
my_string = "hello"
# my_string[0] = "H" # Error: Strings are immutable
Example:
def modify_list(lst):
lst.append(4) # Modifies the original list
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # Output: [1, 2, 3, 4]
Built-in Functions
Python provides a wide range of built-in functions that are ready to use. Some commonly used
ones include:
Examples:
6. Mathematical Functions:
# Combining conversions
mixed_string = "123.45"
converted_float = float(mixed_string)
converted_int = int(float(mixed_string)) # Converts to float first, then to int
print(f"The string '{mixed_string}' converted to a float is {converted_float}, and to an
integer is {converted_int}")
8. Input/Output Functions:
Problems on Functions
1. Write a function to find the factorial of a number.
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
num = 5
result = factorial(num)
print(f"Factorial of {num} is {result}")
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6)) # Output: 8
def sum_of_digits(n):
"""Calculate the sum of the digits of a number."""
return sum(int(digit) for digit in str(n))
5. Check Palindrome.
def is_palindrome(s):
return s == s[::-1]
def count_vowels(s):
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels)
def is_armstrong(n):
num_str = str(n)
num_digits = len(num_str)
return sum(int(digit) ** num_digits for digit in num_str) == n