Passing Arguments to Functions and Returning Values in Python

Function Arguments:

Functions in Python can accept arguments, which are values passed to the function when it is called. These arguments provide data to the function, allowing it to perform specific tasks based on the provided values.

        
            # Function with arguments
            def greet(name):
                print("Hello, " + name + "!")

            # Function with multiple arguments
            def add(a, b):
                return a + b
        
    

Calling Functions with Arguments:

When calling a function that takes arguments, you provide the values for those arguments inside the parentheses.

        
            # Calling the greet() function with an argument
            greet("Alice")

            # Calling the add() function with arguments
            result = add(5, 3)
            print("Sum:", result)
        
    

Returning Values:

Functions can also return values using the return keyword. The return statement specifies the value that the function should return to the caller. The function can then be used in expressions or assigned to variables.

        
            # Function with return value
            def square(x):
                return x * x

            # Calling the square() function and using the returned value
            num = 4
            squared_num = square(num)
            print("Square of", num, "is", squared_num)
        
    

Multiple Return Values:

Python functions can return multiple values by separating them with commas in the return statement. The returned values are treated as a tuple, and you can unpack them into individual variables.

        
            # Function with multiple return values
            def min_max(numbers):
                return min(numbers), max(numbers)

            # Calling the min_max() function and unpacking the returned values
            numbers_list = [10, 5, 20, 15]
            min_val, max_val = min_max(numbers_list)
            print("Minimum value:", min_val)
            print("Maximum value:", max_val)
        
    

Passing arguments to functions and returning values allow you to create more flexible and powerful functions that can perform different tasks based on input and provide useful results for further processing.

Using Functions in Python YouTube Video