-
Hajipur, Bihar, 844101
A function is a block of code that runs only when it is called.
It can take inputs (parameters) and return an output (return value).
def greet():
print("Hello!")
Call the function:
greet()
def greet(name):
print("Hello", name)
greet("John")
def greet(name="Guest"):
print("Hello", name)
greet() # Hello Guest
greet("Anil") # Hello Anil
def add(a, b):
return a + b
print(add(2, 3)) # 5
def show_names(*names):
for name in names:
print(name)
show_names("A", "B", "C")
def student(name, age):
print(name, age)
student(age=18, name="Priya")
def details(**info):
print(info["name"])
details(name="Amit", age=25)
Use pass
to avoid empty function errors.
def test():
pass
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
Q1. Write a Python program to create a function that prints "Welcome to Python"
.
Q2. Write a Python program to create a function that takes a name as input and prints a greeting like "Hello, CodePractice!"
.
Q3. Write a Python program to use a default parameter in a function, such as greet(name="Guest")
.
Q4. Write a Python program to create a function that returns the square of a number.
Q5. Write a Python program to call a function using keyword arguments (e.g., info(name="Sanju", age=27)
).
Q6. Write a Python program to use *args
to accept multiple values and print their total.
Q7. Write a Python program to use **kwargs
to pass and print key-value pairs inside a function.
Q8. Write a Python program to create a function that returns the sum of two numbers.
Q9. Write a Python program to create a function to multiply 3 numbers using default arguments (e.g., multiply(a, b=1, c=1)
).
Q10. Write a Python program to write a recursive function to calculate the factorial of a number.
Q1: What keyword is used to define a function?
Q2: What does a function return if there’s no return statement?
Q3: What are args used for?
Q4: How do you call a function named greet?
Q5: What does kwargs mean?
Q6: Which function call is correct?
Q7: What is the purpose of a return statement?
Q8: What is recursion in Python?
Q9: What happens if a function is defined but never called?
Q10: Can a function return multiple values?