Functions Practice Problems
Python Practice Set: Functions (Related Questions)
Test your knowledge on defining functions, using arguments, return values, and scope.
1. Conceptual Questions
Q1: What is the difference between print() and return inside a function?
Answer:
print()simply displays a value on the console but doesn't "give" it back to the program.returnsends a value back to the caller, allowing it to be stored in a variable or used in further calculations.
Q2: What is "Scope" in Python functions?
Answer: Scope determines where a variable can be accessed. A variable created inside a function is local (only accessible inside that function). A variable created outside a function is global (accessible everywhere).
Q3: Predict the output:
def my_func(x):
x = x + 5
return x
val = 10
my_func(val)
print(val)
Output:
10(Note: The variablevaloutside the function remains unchanged because Python passes values, andxinside the function is a local copy)
2. Arguments & Parameters
Q4: What happens if you call a function with fewer arguments than it expects?
Answer: Python will raise a
TypeErrorunless the missing parameters have default values defined in the function signature.
Q5: When should you use *args and **kwargs?
Answer: Use
*argswhen you want a function to accept a variable number of positional arguments (received as a tuple). Use**kwargsfor a variable number of keyword arguments (received as a dictionary).
Q6: Predict the output:
def greet(name, msg="Good morning!"):
print(f"Hello {name}, {msg}")
greet("Tanis", "How are you?")
greet("Alice")
Output: Hello Tanis, How are you? Hello Alice, Good morning!
3. Lambda Functions
Q7: What is a Lambda function?
Answer: A small, anonymous function defined without a name using the
lambdakeyword. It can have any number of arguments but only one expression. Example:square = lambda x: x * x
4. Coding Challenges
Task 1: Check for Palindrome
Write a function is_palindrome(s) that returns True if a string is a palindrome and False otherwise.
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
print(is_palindrome("Madam")) # True
print(is_palindrome("Python")) # False
Task 2: Factorial using Recursion
Write a recursive function to find the factorial of a number.
def factorial(n):
if n == 1 or n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Task 3: Sum of Arbitrary Numbers
Write a function that takes any number of arguments and returns their sum.
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # Output: 15