Basic Examples of Functions in Python
Example 1: Function Without Arguments
def greet(): print("Hello, Welcome to Python!") greet() # Output: Hello, Welcome to Python!
Example 2: Function With Arguments
def add(a, b): print("Sum is:", a + b) add(5, 3) # Output: Sum is: 8
Example 3: Function With Return Value
def square(x): return x * x result = square(6) print("Square is:", result) # Output: Square is: 36
Example 4: Default Parameters
def greet(name="User"): print("Hello,", name) greet() # Uses default value greet("Vaibhav") # Uses
given value # Output: Hello, User Hello, Vaibhav
Example 5: Function Returning Multiple Values
def calc(a, b): return a+b, a-b, a*b s, d, m = calc(10, 5) print("Sum:", s) print("Difference:", d)
print("Multiplication:", m) # Output: Sum: 15 Difference: 5 Multiplication: 50
Example 6: Using Functions in a Loop (Factorial)
def factorial(n): fact = 1 for i in range(1, n+1): fact *= i return fact print("Factorial of 5 is:",
factorial(5)) # Output: Factorial of 5 is: 120