Python Coding Day 19 | The return Statement in Python Functions

The return Statement in Python Functions

Watch the lesson tutorial  ðŸ”»

In Python, functions are reusable blocks of code that perform specific tasks. While functions can perform actions (like printing text), their real power comes from their ability to process data and send a result back to the main program. This is done using the return keyword.

Here, we will look at two practical examples of how return works.

1. The Basic Return

The return keyword marks the end of a function's execution and "returns" a value to the place where the function was called. This allows you to store the result in a variable or use it immediately.

In this example, the function takes a first and last name, converts them to Title Case (where the first letter is capitalized), and returns the combined string.

def format_name(f_name, l_name):
    new_f_name = f_name.title()
    new_l_name = l_name.title()
    return f"{new_f_name} {new_l_name}"

# Calling the function and printing the returned value
print(format_name("CHIRANA", "NIMNAKA"))

# Output:
# Chirana Nimnaka

Key Takeaways:

  • Data Flow: The function receives "CHIRANA" and "NIMNAKA", processes them, and sends back "Chirana Nimnaka".

  • Replacement: You can think of the function call format_name(...) as being replaced by the value it returns.

2. Early Return & Input Validation

The return statement effectively exits the function immediately. We can use this behavior to check for errors or invalid inputs at the very beginning of a function. If the inputs are bad, we return an error message or None right away, skipping the rest of the code.

In this improved example, we check if the user provided empty strings. If they did, we stop and return a warning message.

def format_name(f_name, l_name):
    """Take a first and last name and format it 
    to return the title case version of the name."""
    
    # Validation: Check for empty strings
    if f_name == "" or l_name == "":
        return "You didn't provide valid inputs."
    
    # These lines only run if the inputs were valid
    formated_f_name = f_name.title()
    formated_l_name = l_name.title()
    return f"Result: {formated_f_name} {formated_l_name}"

# Simulating user input
print(format_name(input("What is your first name? "), input("What is your last name? ")))

# Output (Scenario 1: Valid Input):
# What is your first name? chirana
# What is your last name? nimnaka
# Result: Chirana Nimnaka

# Output (Scenario 2: Invalid Input):
# What is your first name? 
# What is your last name? nimnaka
# You didn't provide valid inputs.

Key Takeaways:

  • Multiple Returns: A function can have more than one return statement, but only one will ever be executed during a single call.

  • Guard Clauses: Using an if statement with a return at the top of a function is a common pattern to "guard" the rest of the code from running with bad data.


Comments

Popular posts from this blog

Python Coding Day 1 | The print() Function and Comments

What is Python?

Set Up an Environment to Code in Python