Python Functions


function is a block of code that runs only when it is called.
It can take inputs (parameters) and return an output (return value).


🔹 Create a Function

def greet():
    print("Hello!")

Call the function:

greet()

🔹 Function with Parameters

def greet(name):
    print("Hello", name)

greet("John")

🔹 Default Parameter Value

def greet(name="Guest"):
    print("Hello", name)

greet()        # Hello Guest
greet("Anil")  # Hello Anil

🔹 Return Values

def add(a, b):
    return a + b

print(add(2, 3))  # 5

🔹 Arbitrary Arguments (*args)

def show_names(*names):
    for name in names:
        print(name)

show_names("A", "B", "C")

🔹 Keyword Arguments

def student(name, age):
    print(name, age)

student(age=18, name="Priya")

🔹 Arbitrary Keyword Arguments (**kwargs)

def details(**info):
    print(info["name"])

details(name="Amit", age=25)

🔹 Pass Statement

Use pass to avoid empty function errors.

def test():
    pass

🔹 Recursion Example

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # 120

Practice Questions

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.



Go Back Top