In Python, it is necessary to provide at least one argument in a function.
Answer
False
Reason — A function can take any number of arguments or none. If a function does not accept any arguments, the parentheses are left empty while defining the function. Therefore, it is not necessary to provide at least one argument in a Python function.
Within a function, the parameters act as placeholders for the passed argument.
Answer
True
Reason — Within the function, the parameters act as placeholders for the arguments. The actual values are passed during the function call, and the parameters receive and represent those values inside the function body.
All other arguments to the right side of default argument must also have default values.
Answer
True
Reason — Non-default arguments should not follow default arguments. This means that once a default argument is specified in a function definition, all arguments to its right must also have default values.
The return statement in Python function cannot return multiple values.
Answer
False
Reason — In Python, a function is allowed to return more than one value using a single return statement by separating the values with commas.
Python allows you to combine different types of arguments in a function call.
Answer
True
Reason — Python provides different types of arguments such as fixed length arguments, variable length arguments (*args and **kwargs), and default arguments. Python allows the use of different types of arguments together in a function call.
Non-fruitful functions use the return statement to return values.
Answer
False
Reason — Non-fruitful functions (void functions) do not return any value. They may or may not contain a return statement, but if present, it returns no value and hence returns None. Therefore, non-fruitful functions do not use the return statement to return values.
Invoking a function is similar as calling a function in a program.
Answer
True
Reason — The process of using a function in a program after defining it is called calling a function or invoking a function. Both terms are used interchangeably and refer to the same action of executing a function.
'*args' keyword allows to pass a variable number of arguments and arguments are stored in a tuple.
Answer
True
Reason — The *args keyword is used to pass a variable number of arguments to a function. The arguments passed using *args are automatically stored in a tuple, which can be accessed inside the function.
'**kwargs' keyword allows to pass variable number of arguments in a function and store the provided arguments in tuple.
Answer
False
Reason — The **kwargs keyword is used to pass a variable number of arguments to a function, but the provided arguments are stored in a dictionary, not in a tuple.
In Python, functions can be defined to accept variable length of arguments.
Answer
True
Reason — Python allows functions to accept a variable length of arguments using *args and **kwargs.
Functions in programming:
- allow modular approach
- improve program readability
- help in code reusability
- All of these
Answer
All of these
Reason — Functions help in achieving modularity by breaking a large program into smaller manageable parts. They promote code reusability by allowing the same block of code to be used multiple times, and they improve program readability by organising code into logical blocks.
The structure of function header in Python is:
- "def" keyword followed by the function name and parameters
- "func" keyword followed by the function name and parameters
- "def" keyword followed by the return type, function name and parameters
- "define" keyword followed by the function name and parameters
Answer
"def" keyword followed by the function name and parameters
Reason — A Python function header consists of the def keyword, followed by the function name, a list of parameters enclosed in parentheses, and ends with a colon.
A function in Python is called by:
- using the "call" keyword followed by the function name and parameters
- using the "invoke" keyword followed by the function name and parameters
- using the function name followed by parenthesis and arguments
- using the "run" keyword followed by the function name and parameters
Answer
using the function name followed by parenthesis and arguments
Reason — A function in Python is called or invoked by writing the function name followed by parentheses, with the required input values passed as arguments inside the parentheses.
What is the purpose of return statement in Python functions?
- It is used to terminate the execution of a function
- It is used to define the output of a function
- It is used to import modules into a function
- None of these
Answer
It is used to terminate the execution of a function
Reason — The return statement ends the execution of a function and transfers the control back to the place where the function was called. Once the return statement is executed, no further statements in the function body are executed.
What would be output of the following code snippet?
def multiply(x, y=2):
return x * y
result = multiply(5)
print(result)- 5
- 10
- 2
- Error
Answer
10
Reason — Default arguments are used when a value is not provided during the function call. In the given function multiply(x, y=2), the parameter y has a default value of 2. When the function is called as multiply(5), the value 5 is assigned to x and the default value 2 is assigned to y. Therefore, the function returns 5 × 2 = 10, which is printed as the output.
In the following code snippet, what does 5 in the argument list represent?
def add(x, y=5):
return x + y- return value
- default value
- input value
- None of these
Answer
default value
Reason — Default arguments allow a function parameter to have a predefined value. In the given function definition def add(x, y=5):, the value 5 is assigned to parameter y as its default value, which is used when no value is provided for y during the function call.
Which keyword is used to define function with variable length arguments?
- *args
- **kwargs
- *var
- Both a and b
Answer
Both a and b
Reason — Python allows functions to accept a variable number of arguments using *args and **kwargs.
Which of the following is not a built-in function in Python?
- input()
- print()
- len()
- add()
Answer
add()
Reason — Built-in functions are functions that are already defined in Python, such as input(), print(), and len(). The function add() is not listed as a built-in function.
What would be the return type of the following function in Python?
def mul(x, y):
return x * y
result= multiply(5, 2)
print(result)- int
- float
- char
- string
Answer
int
Reason — The return type of a function depends on the type of value returned by the return statement. In the given function, the statement return x * y returns the product of two integer values. Since the multiplication of integers results in an integer value, the return type of the function is int.
What would be the return type of the following function in Python?
def is_positive(number):
if number > 0:
return True
else:
return False- int
- float
- bool
- char
Answer
bool
Reason — The return type of a function depends on the value returned by the return statement. In the given function, the return statements return either True or False, which are Boolean values. Therefore, the return type of the function is bool.
Which of the following keywords is used to create a user-defined function?
- None
- define
- def
- func
Answer
def
Reason — The def keyword is used to define or create a user-defined function in Python.
The structure of a Python function contains a function header and ............... .
- return Statement
- Indented Block
- Function Body
- def Statement
Answer
Function Body
Reason — The structure of a Python function consists of two parts: the function header and the function body. The function body contains the statements that define what the function does.
Which of the following is not a part of function header?
- Keyword def
- Function_name
- Parameters
- Keyword return
Answer
Keyword return
Reason — A function header includes the def keyword, the function name, and the list of parameters enclosed in parentheses, followed by a colon. The return keyword is used inside the function body, not in the function header.
The multiple values returned by the return statement are packed into the ............... data type.
- List
- Tuple
- Set
- None of these
Answer
Tuple
Reason — When a function returns multiple values using a single return statement, those values are automatically grouped together into a tuple. Therefore, the multiple values returned by a function are packed into the tuple data type.
Which of the following statements is true for functions in Python?
- Function is a reusable code segment of program.
- Function does not provide better modularity for your program.
- You cannot create your own functions in Python.
- All of these
Answer
Function is a reusable code segment of program.
Reason — Functions allow reusability of code by enabling a block of code to be defined once and used multiple times in a program.
Fill in the blanks:
- Function can accept inputs called ................ .
- The ................ arguments allow to specify a default value for a function parameter.
- The ................ statement is used to return a value from a function.
- A function can have ................ parameters, which have default values assigned to them.
- In a ................, a large program is broken down into individual blocks of code that work together to complete a task.
- ................ functions refer to those functions that are already defined in Python and user can use them directly without referring to any module or library.
- The ................ keyword is used to define a user-defined function.
- The two parts of a function are ................ and ................ .
- ................ are the names given to variables that are given in the parentheses in the function definition.
- Multiple values are returned by a function in the form of the ................ data type.
- The function is called ................ if it does not return any value or has an empty return statement.
- The functions that return some value using the return statement after execution are called ................ functions.
Answer
- Function can accept inputs called arguments or parameters.
- The default arguments allow to specify a default value for a function parameter.
- The return statement is used to return a value from a function.
- A function can have default parameters, which have default values assigned to them.
- In a function, a large program is broken down into individual blocks of code that work together to complete a task.
- Built-in functions refer to those functions that are already defined in Python and user can use them directly without referring to any module or library.
- The def keyword is used to define a user-defined function.
- The two parts of a function are function header and function body.
- parameters are the names given to variables that are given in the parentheses in the function definition.
- Multiple values are returned by a function in the form of the tuple data type.
- The function is called void or non-fruitful function if it does not return any value or has an empty return statement.
- The functions that return some value using the return statement after execution are called Non-void or fruitful functions.
Write a Python program to calculate the area of a square and a rectangle by defining a function.
def area(length, breadth=-1):
if breadth == -1:
return length * length
else:
return length * breadth
s = int(input("Enter side of square: "))
result_square = area(s)
print("Area of square:", result_square)
l = int(input("Enter length of rectangle: "))
b = int(input("Enter breadth of rectangle: "))
result_rectangle = area(l, b)
print("Area of rectangle:", result_rectangle)Enter side of square: 4
Area of square: 16
Enter length of rectangle: 5
Enter breadth of rectangle: 6
Area of rectangle: 30
Write a Python program to print the table of a given number by using a function.
def print_table(n):
for i in range(1, 11):
print(n, "x", i, "=", n * i)
num = int(input("Enter a number: "))
print_table(num)Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Write a Python program to demonstrate the concept of default arguments in a function.
def add_numbers(a, b=5):
print(a + b)
add_numbers(3)
add_numbers(9, 4)8
13
Is the return statement mandatory for every function?
Answer
No, the return statement is not mandatory for every function. If a function does not contain a return statement, it does not return any value and is called a void (or non-fruitful) function. In such cases, the function returns None automatically.
Write a function that returns the greater of two numbers passed as arguments.
def greater(a, b):
if a > b:
return a
else:
return b
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
result = greater(x, y)
print("Greater number is:", result)Enter first number: 80
Enter second number: 82
Greater number is: 82
Write a function called ice_water that takes a number as input. Perform the following operations:
- If the number is divisible by 3, then it should return "ice".
- If it is divisible by 5, then it should return "water".
- If it is divisible by both 3 and 5, then it should return "icewater".
- Otherwise, it should return the same number.
def ice_water(n):
if n % 3 == 0 and n % 5 == 0:
return "icewater"
elif n % 3 == 0:
return "ice"
elif n % 5 == 0:
return "water"
else:
return n
num = int(input("Enter a number: "))
result = ice_water(num)
print(result)Enter a number: 15
icewater
Enter a number: 9
ice
Enter a number: 20
water
Write a function for checking the speed of drivers. This function should have one parameter: speed.
- If speed is less than 70, it should print "OK".
- Otherwise, for every 5 km above the speed limit (70), it should give the driver one demerit point. Calculate and print the total number of demerit points at the end. For example, if the speed is 80, it should print: "Demerit Points: 2".
- If the driver gets more than 12 demerit points, the function should print: "License suspended".
def check_speed(speed):
if speed < 70:
print("OK")
else:
points = (speed - 70) // 5
print("Demerit Points:", points)
if points > 12:
print("License suspended")
speed = int(input("Enter speed: "))
check_speed(speed)Enter speed: 85
Demerit Points: 3
Enter speed: 60
OK
Enter speed: 140
Demerit Points: 14
License suspended
Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter). For example, if the limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20.
def sum_multiples(limit):
s = 0
for i in range(0, limit + 1):
if i % 3 == 0 or i % 5 == 0:
s = s + i
return s
limit = int(input("Enter limit: "))
result = sum_multiples(limit)
print(result)Enter limit: 20
98
What are the various parameter passing techniques?
Answer
Python supports the following parameter passing techniques:
- Fixed Length Arguments: These are the arguments defined in the function header. While calling the function, the values must be passed in the same order and number as specified in the function definition.
- Variable Length Arguments: Python allows a function to accept a variable number of arguments. There are two types:
*args: Stores the passed arguments in a tuple.**kwargs: Stores the passed arguments in a dictionary.
- Default Arguments: These arguments have a default value assigned in the function definition. If no value is provided during the function call, the default value is used. Default arguments must appear after non-default arguments.
Describe user-defined functions in Python with the help of an example.
Answer
A user-defined function is a function that is defined by the user to perform a specific task. It enables the user to write their own code and reuse it whenever required. User-defined functions help in reducing repetition of code and make programs easier to understand and maintain.
In Python, a user-defined function is created using the def keyword, followed by the function name, parameters enclosed in parentheses, and a colon. The statements that define the task of the function form the function body.
Example:
def add(a, b):
return a + b
result = add(5, 6)
print(result)In the above example, the function add() is a user-defined function that takes two parameters and returns their sum using the return statement. This function can be called any number of times with different arguments.
Distinguish between void functions and non-void functions with the help of an example.
Answer
Void functions are those functions that do not return any value. They may or may not contain a return statement, but even if the return statement is present, it returns no value. When such a function is called, it automatically returns None. Void functions are also called non-fruitful functions.
Example of a void function:
def msg():
print("Welcome")
msg()In this example, the function msg() only prints a message and does not return any value. Hence, it is a void (non-fruitful) function.
A non-void function is a function that returns a value using the return statement after execution. The value returned is passed back to the calling statement. Non-void functions are also known as fruitful functions.
Example of a non-void function:
def add(a, b):
return a + b
result = add(4, 6)
print(result)In this example, the function add() returns the sum of two numbers using the return statement. Hence, it is a non-void (fruitful) function.
Discuss the structure of a Python function with the help of an example.
Answer
The structure of a Python function consists of two main parts: Function Header and Function Body.
The function header includes the def keyword, followed by the function name, a list of parameters enclosed within parentheses, and ends with a colon. It defines the name of the function and the parameters that the function can accept.
The function body consists of an indented block of statements that specify what the function does. It may include one or more statements and can optionally contain a return statement to return a value to the calling statement.
Example:
def square(n):
return n * n
result = square(6)
print(result)In this example, def square(n): is the function header, where square is the function name and n is the parameter. The indented statement return n * n forms the function body, which calculates and returns the square of the given number when the function is called.
Write a function which returns if a number passed as as argument is a perfect number or an Armstrong number.
def check_number(n):
s = 0
temp = n
digits = len(str(n))
while temp > 0:
d = temp % 10
s = s + d ** digits
temp = temp // 10
p = 0
for i in range(1, n):
if n % i == 0:
p = p + i
if p == n:
return "Perfect Number"
elif s == n:
return "Armstrong Number"
else:
return "Neither Perfect nor Armstrong"
num = int(input("Enter a number: "))
result = check_number(num)
print(result)Enter a number: 9474
Armstrong Number
Enter a number: 28
Perfect Number
Write a function which returns if a number passed as an argument is a prime or composite number.
def prime_composite(n):
if n <= 1:
return "Neither Prime nor Composite"
count = 0
for i in range(1, n + 1):
if n % i == 0:
count = count + 1
if count == 2:
return "Prime Number"
else:
return "Composite Number"
num = int(input("Enter a number: "))
result = prime_composite(num)
print(result)Enter a number: 7
Prime Number
Enter a number: 12
Composite Number
Write a function which counts and displays the number of vowels, consonants, uppercase, and lowercase characters in a string entered as input.
def count_characters(s):
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0
for ch in s:
if 'A' <= ch <= 'Z':
uppercase += 1
if ch in 'AEIOU':
vowels += 1
else:
consonants += 1
elif 'a' <= ch <= 'z':
lowercase += 1
if ch in 'aeiou':
vowels += 1
else:
consonants += 1
print("Vowels:", vowels)
print("Consonants:", consonants)
print("Uppercase letters:", uppercase)
print("Lowercase letters:", lowercase)
text = input("Enter a string: ")
count_characters(text)Enter a string: HelloWorld
Vowels: 3
Consonants: 7
Uppercase letters: 2
Lowercase letters: 8
Write a function which deletes all the negative values from a list passed as an argument.
def remove_negative(lst):
new_list = []
for x in lst:
if x >= 0:
new_list.append(x)
return new_list
numbers = eval(input("Enter list: "))
result = remove_negative(numbers)
print(result)Enter list: [2, -5, 6, -3, 0, 8]
[2, 6, 0, 8]
Write a function which takes a number and a list as arguments and counts the occurrence of that number in the given list.
def count_occurrence(num, lst):
count = 0
for x in lst:
if x == num:
count = count + 1
return count
numbers = eval(input("Enter list: "))
num = int(input("Enter the number to count: "))
result = count_occurrence(num, numbers)
print("Occurrence:", result)Enter list: [2, 4, 5, 2, 7, 2, 9]
Enter the number to count: 2
Occurrence: 3