whenever life put's you in a tough situtation, never say why me! but, try me!

Functions: Definition and Usage in Python

Functions are a fundamental building block in Python that allows you to encapsulate code for reuse. Functions help organize code into reusable, logical units, improving readability and maintainability.


Subtopic 1: Defining and Calling Functions

A function in Python is defined using the def keyword, followed by the function name, parentheses, and an optional block of code that the function will execute.

Syntax for Defining a Function
def function_name(parameters):
    # Code block
    return value  # Optional
Example: Defining and Calling a Function
# Defining a function to greet a user
def greet(name):
    print(f"Hello, {name}!")

# Calling the function
greet("Alice")

Output:

Hello, Alice!
Explanation:
  • The function greet is defined to take a single parameter name and prints a greeting message.
  • The function is then called with the argument "Alice".

Subtopic 2: Function Parameters and Arguments

Functions can accept data via parameters. These are variables used in the function definition. The data passed into the function is called arguments.

  • Formal Parameters: Defined in the function header.
  • Actual Arguments: Passed to the function when calling it.
Example: Function with Multiple Parameters
def add_numbers(a, b):
    return a + b

# Calling the function with arguments
result = add_numbers(10, 20)
print(result)

Output:

30
Explanation:
  • The function add_numbers takes two parameters a and b, then returns their sum. It is called with arguments 10 and 20.

Subtopic 3: Default and Keyword Arguments

You can provide default values for function parameters. If the argument is not passed when calling the function, the default value is used.

  • Default Arguments: Arguments with predefined values.
  • Keyword Arguments: Arguments passed by explicitly specifying the parameter name.
Default Arguments Example
def greet(name, message="Hello"):
    print(f"{message}, {name}!")

# Calling the function with only one argument (message will default to "Hello")
greet("Bob")

# Calling the function with both arguments
greet("Alice", "Good Morning")

Output:

Hello, Bob!
Good Morning, Alice!
Keyword Arguments Example
def greet(name, age):
    print(f"Name: {name}, Age: {age}")

# Using keyword arguments to specify the parameters
greet(age=25, name="Charlie")

Output:

Name: Charlie, Age: 25
Explanation:
  • In the first example, the function greet has a default value for message, so if no message is provided, it defaults to "Hello".
  • In the second example, keyword arguments allow you to pass arguments in any order by explicitly specifying the parameter names.

Subtopic 4: Return Values and None

Functions in Python can return values using the return keyword. If no value is returned, the function implicitly returns None.

Example: Function with Return Value
def multiply(a, b):
    return a * b

result = multiply(4, 5)
print(result)

Output:

20
Example: Function Returning None
def print_greeting(name):
    print(f"Hello, {name}!")

result = print_greeting("Diana")
print(result)  # This will print None because the function does not return anything

Output:

Hello, Diana!
None
Explanation:
  • The multiply function returns the result of a * b, while the print_greeting function simply prints a message and does not return any value, so it implicitly returns None.

Tasks

  1. Task 1: Function to Calculate Square of a Number

    • Write a function that takes a number as a parameter and returns its square.
    def square(num):
        return num ** 2
    
    result = square(5)
    print(result)  # Output: 25
    
  2. Task 2: Function with Multiple Parameters

    • Write a function that takes two numbers and returns their sum, difference, and product.
    def calculate(a, b):
        return a + b, a - b, a * b
    
    sum, difference, product = calculate(10, 5)
    print("Sum:", sum, "Difference:", difference, "Product:", product)
    
  3. Task 3: Function with Default Argument

    • Write a function that takes a message and a name. If no message is provided, the default message should be "Welcome". Print the message with the name.
    def welcome(name, message="Welcome"):
        print(f"{message}, {name}!")
    
    welcome("David")  # Uses default message
    welcome("Eve", "Good Morning")  # Uses provided message
    
  4. Task 4: Function with Keyword Arguments

    • Write a function that accepts two parameters: first_name and last_name. Print a greeting message using keyword arguments.
    def greet_person(first_name, last_name):
        print(f"Hello {first_name} {last_name}!")
    
    greet_person(first_name="John", last_name="Doe")
    
  5. Task 5: Function with Return Value

    • Write a function that returns the larger of two numbers.
    def max_of_two(a, b):
        if a > b:
            return a
        return b
    
    print(max_of_two(10, 20))  # Output: 20
    
  6. Task 6: Function Returning None

    • Write a function that prints "Goodbye" and does not return anything. When called, print the result to verify it returns None.
    def say_goodbye():
        print("Goodbye!")
    
    result = say_goodbye()
    print(result)  # Output: None