Day 09 - Class Work

Understanding Python Functions

Syntax of a Python Function

def function_name(parameters):
    # code block
    return value

def → keyword to define a function
function_name → name of the function
parameters → input values (optional)
return → value returned by the function (optional)

Function vs Without Function

Without Function With Function
print("Hello, Arun")
print("Hello, Hasvanth")
print("Hello, Ayyappan")
def greet(name):
    print("Hello,", name)

greet("Arun")
greet("Hasvanth")
greet("Ayyappan")

10 Examples of Python Functions with Output

1. Function without parameters

def say_hello():
    print("Hello World!")

say_hello()
# Output:
# Hello World!

2. Function with one parameter

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

greet("Arun")
# Output:
# Hello, Arun

3. Function with two parameters

def add(a, b):
    print("Sum:", a + b)

add(5, 3)
# Output:
# Sum: 8

4. Function that returns a value

def square(num):
    return num * num

result = square(4)
print("Square:", result)
# Output:
# Square: 16

5. Function with default parameter

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

greet()
greet("Hasvanth")
# Output:
# Welcome, Guest
# Welcome, Hasvanth

6. Function with multiple return values

def calculator(a, b):
    return a+b, a-b, a*b

s, d, m = calculator(5, 3)
print("Sum:", s, "Diff:", d, "Mul:", m)
# Output:
# Sum: 8 Diff: 2 Mul: 15

7. Function with a loop inside

def print_numbers(n):
    for i in range(1, n+1):
        print(i)

print_numbers(5)
# Output:
# 1
# 2
# 3
# 4
# 5

8. Recursive function (factorial)

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

print("Factorial of 5:", factorial(5))
# Output:
# Factorial of 5: 120

9. Function with *args

def display(*names):
    for name in names:
        print("Hello", name)

display("Arun", "Hasvanth", "Ayyappan")
# Output:
# Hello Arun
# Hello Hasvanth
# Hello Ayyappan

10. Function with **kwargs

def student_info(**details):
    for key, value in details.items():
        print(key, ":", value)

student_info(name="Arun", age=21, grade="A")
# Output:
# name : Arun
# age : 21
# grade : A