杰瑞科技汇

python return done

Of course! In Python, the return statement is a fundamental part of writing functions. It's used to send a value back from a function to the part of the code that called it.

python return done-图1
(图片来源网络,侵删)

Let's break it down into simple concepts, clear examples, and some important rules.

The Core Idea: return Sends a Value Back

Think of a function like a small, specialized factory.

  • You give it raw materials (this is the input, or arguments).
  • The factory does some work inside (the code in the function).
  • It then produces a finished product and sends it out the door. This finished product is the return value.

The return statement is what "sends the product out."


Basic Syntax and Example

The simplest use of return is to send a single value back.

python return done-图2
(图片来源网络,侵删)
def add_two_numbers(a, b):
  """This function takes two numbers and returns their sum."""
  result = a + b
  return result # Send the value of 'result' back
# --- How to use it ---
# Call the function and store the returned value in a variable
sum_result = add_two_numbers(5, 7)
# Now you can use the returned value
print(f"The sum is: {sum_result}") 
# Output: The sum is: 12
# You can also use it directly in another expression
print(f"Double the sum is: {add_two_numbers(5, 7) * 2}")
# Output: Double the sum is: 24

In this example, when add_two_numbers(5, 7) is called, the function calculates 12 and uses return 12 to send that value back. The sum_result variable then holds this value.


What Happens If You Don't Use return?

If you define a function but don't have a return statement, it will still run, but it will implicitly return a special value called None.

def print_message(message):
  """This function just prints a message but doesn't return anything."""
  print(f"Message: {message}")
# --- How to use it ---
return_value = print_message("Hello, World!")
# Let's see what return_value is
print(f"The function returned: {return_value}")
# Output:
# Message: Hello, World!
# The function returned: None

This is a very common source of bugs for beginners. If you expect a function to give you a value to use later, but you forget the return statement, you'll end up with None.


Returning Multiple Values

Python has a neat feature where you can "return" multiple values at once. In reality, it bundles them into a tuple, and Python's syntax makes it look like you're returning separate items.

def get_user_info():
  """Returns a user's name and age."""
  name = "Alice"
  age = 30
  return name, age # This is actually returning the tuple ("Alice", 30)
# --- How to use it ---
# Unpack the returned tuple into separate variables
user_name, user_age = get_user_info()
print(f"User Name: {user_name}")
print(f"User Age: {user_age}")
# You can also see the returned value as a tuple
user_tuple = get_user_info()
print(f"The returned tuple is: {user_tuple}")

Output:

User Name: Alice
User Age: 30
The returned tuple is: ('Alice', 30)

The return Statement Exits the Function Immediately

The moment a return statement is executed, the function stops running. Any code after the return statement will be ignored.

def check_number(number):
  if number > 10:
    print("The number is greater than 10.")
    return "Found a large number" # Function stops here
  else:
    print("The number is 10 or less.")
    return "Found a small number" # This line is only reached if the first 'if' is false
  print("This line will NEVER be printed.") # This is unreachable code
# --- How to use it ---
result1 = check_number(15)
print(f"Result 1: {result1}\n")
result2 = check_number(5)
print(f"Result 2: {result2}")

Output:

The number is greater than 10.
Result 1: Found a large number
The number is 10 or less.
Result 2: Found a small number

Returning None Explicitly

You can also use return by itself with no value. This is the same as returning None explicitly. It's useful for signaling that a function has completed its action without producing a meaningful result.

def greet(name):
  if not name:
    print("Hello, stranger!")
    return # Exits the function, returning None
  print(f"Hello, {name}!")
# --- How to use it ---
greeting_value = greet("Bob")
print(f"The function returned: {greeting_value}\n")
greeting_value_none = greet("")
print(f"The function returned: {greeting_value_none}")

Output:

Hello, Bob!
The function returned: None
Hello, stranger!
The function returned: None

Returning Different Types of Data

A return statement can send back any type of data: numbers, strings, lists, dictionaries, or even other functions!

def get_book_details():
  # Return a dictionary
  return {
      "title": "The Hitchhiker's Guide to the Galaxy",
      "author": "Douglas Adams",
      "pages": 224
  }
# --- How to use it ---
book = get_book_details()
print(book["title"]) # Output: The Hitchhiker's Guide to the Galaxy

Summary Table

Statement What it Does Example
return value Sends value back to the caller and exits the function. return 42
return Exits the function and sends None back. return
return a, b Sends back a tuple (a, b). return 1, "hello"
(no return) Function runs to the end and implicitly returns None. def f(): pass

The return statement is the primary way a function communicates its result to the rest of your program. Mastering it is key to writing clean, modular, and reusable Python code.

分享:
扫描分享到社交APP
上一篇
下一篇