How to call a function in Python

1. What is a Function?

A function is a block of reusable code designed to perform a specific task.

  • Inputs: Called arguments or parameters.
  • Logic: The body of the function where operations are performed.
  • Output: The output given by the function.

Example:

def greet(name):
    return f"Hello, {name}!"

Here:

  • greet is the function name.
  • name is the parameter.
  • The function processes the input and returns a greeting.

2. Defining a Function

Functions are declared by using the keyword def followed by:

  1. The function name.
  2. Parentheses ( ) containing parameters (optional).
  3. A colon : indicating the beginning of the function’s body.
  4. A block of indented code as the body.

Example:

def say_hello():  # No parameters
    print("Hello, World!")  # Function body

3. Calling a Function

Functions are invoked using their name followed by parentheses. If they need arguments, pass them inside the parentheses.

Example:

say_hello()  # Calls the function

Output:

Hello, World!

4. Function Arguments

a. No Arguments

Functions without arguments perform tasks without needing external input.

Example:

def welcome_message():
    print("Welcome to Python programming!")

welcome_message()

Output:

Welcome to Python programming!

b. Positional Arguments

Arguments are passed in the same order as the function parameters.

Example:

def subtract(a, b):
    return a - b

result = subtract(10, 5)
print(result)

Output:

5

c. Keyword Arguments

Arguments are assigned explicitly by name, making the order irrelevant.

Example:

def subtract(a, b):
    return a - b

result = subtract(b=5, a=10)  # Keyword arguments
print(result)

Output:

5

d. Default Arguments

Default arguments are used if no value is provided.

Example:

def greet(name, message="Welcome!"):
    return f"{message}, {name}"

print(greet("Alice"))  # Uses default message
print(greet("Bob", "Good Morning"))  # Overrides default

Output:

Welcome!, Alice
Good Morning, Bob

e. Variable-Length Arguments

  1. *args: Accepts multiple positional arguments as a tuple.

Example:

def add_all(*args):
    return sum(args)

print(add_all(1, 2, 3, 4))  # Adds all arguments

Output:

10

2. **kwargs: Accepts multiple keyword arguments as a dictionary.

Example:

def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

display_info(name="Alice", age=25, city="New York")

Output:

name: Alice
age: 25
city: New York

5. Return Values

Functions can return a value using the return statement. If no return is specified, the function returns None.

Example 1: Returning a Value

def multiply(a, b):
    return a * b

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

Output:

12

Example 2: Returning None

def do_nothing():
    pass

print(do_nothing())

Output:

None

6. Common Errors

a. Missing Parentheses

Calling a function without parentheses treats it as an object instead of executing it.

Example:

def greet():
    return "Hello!"

print(greet)  # Function object, not executed
print(greet())  # Executes and returns "Hello!"

Output:

<function greet at 0x...>
Hello!

b. Incorrect Number of Arguments

If a function is called with fewer or more arguments than required, Python raises an error.

Example:

def divide(a, b):
    return a / b

# print(divide(5))  # Missing one argument

Error Output:

TypeError: divide() missing 1 required positional argument: 'b'

c. Invalid Argument Types

Passing incompatible arguments can cause errors.

Example:

def multiply(a, b):
    return a * b

# print(multiply(5, "hello"))  # Invalid operation

Error Output:

TypeError: can't multiply sequence by non-int of type 'str'

7. Practical Examples

a. Calculator

def calculator(a, b, operation):
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    elif operation == "divide":
        return a / b
    else:
        return "Invalid operation"

print(calculator(10, 5, "add"))  # Output: 15
print(calculator(10, 5, "divide"))  # Output: 2.0

Output:

15
2.0

b. Temperature Conversion

def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

print(celsius_to_fahrenheit(0))  # Freezing point
print(celsius_to_fahrenheit(100))  # Boiling point

Output:

32.0
212.0

8. Scope and Nested Functions

Scope: Variables inside a function are local to that function.

Example:

def my_function():
    x = 10  # Local variable
    print(x)

# print(x)  # Error: x is not defined outside the function

Output:

10

Summary Table of Key Concepts

ConceptDescriptionExample (Output)
Function DefinitionDefine reusable code with def.def greet(name): return "Hi!"
Calling FunctionsUse function_name() to execute a function.greet("Alice") → Hi!
Positional ArgumentsPass arguments in order.add(5, 3) → 8
Keyword ArgumentsExplicitly assign arguments by name.subtract(a=10, b=5) → 5
Default ArgumentsProvide default values for parameters.greet("Bob") → Welcome, Bob!
Variable-Length ArgumentsUse *args and **kwargs for flexible arguments.add_all(1,2,3) → 6
Return ValuesUse return to send back results.multiply(2, 3) → 6
ErrorsHandle missing arguments and type issues.TypeError