杰瑞科技汇

Python return true 是如何实现的?

Of course! It looks like you're asking about how to make a Python function return True.

Python return true 是如何实现的?-图1
(图片来源网络,侵删)

In Python, you use the return keyword inside a function to send a value back to wherever the function was called. To return the boolean value True, you simply type return True.

Here’s a breakdown with examples.

The Basic Syntax

The fundamental structure is to define a function and use return True in its body.

def is_function_working():
  """A simple function that always returns True."""
  print("This function is running...")
  return True
# --- How to use it ---
# 1. Call the function and store the returned value in a variable
result = is_function_working()
# 2. Print the result to see what it is
print(f"The function returned: {result}")
print(f"The type of the result is: {type(result)}")
# 3. You can use the returned value in an if statement
if result:
  print("The condition is True!")

Output:

Python return true 是如何实现的?-图2
(图片来源网络,侵删)
This function is running...
The function returned: True
The type of the result is: <class 'bool'>
The condition is True!

Common Use Cases: Returning True Based on a Condition

The real power of returning True comes from using it to signal that a certain condition has been met.

Example: Checking if a Number is Even

This function checks if a number is even. If it is, it returns True. Otherwise, it returns False.

def is_even(number):
  """
  Checks if a number is even.
  Returns True if even, False otherwise.
  """
  # The modulo operator (%) gives the remainder of a division.
  # If a number divided by 2 has a remainder of 0, it's even.
  if number % 2 == 0:
    return True  # The condition is met
  else:
    return False # The condition is not met
# --- How to use it ---
print(f"Is 10 even? {is_even(10)}")   # Output: Is 10 even? True
print(f"Is 7 even? {is_even(7)}")     # Output: Is 7 even? False

A More "Pythonic" Way:

You can simplify the function above. In Python, the expression number % 2 == 0 already evaluates to either True or False. You can return that result directly.

def is_even_pythonic(number):
  """A more concise way to check for an even number."""
  return number % 2 == 0
print(f"Is 88 even? {is_even_pythonic(88)}") # Output: Is 88 even? True
print(f"Is 99 even? {is_even_pythonic(99)}") # Output: Is 99 even? False

Example: Checking for an Item in a List

This function checks if a specific item exists in a list.

def contains_item(my_list, item_to_find):
  """
  Checks if a list contains a specific item.
  Returns True if found, False otherwise.
  """
  for item in my_list:
    if item == item_to_find:
      return True  # Found it! No need to look further.
  # If the loop finishes without finding the item, it's not there.
  return False
# --- How to use it ---
shopping_list = ["apples", "bananas", "milk", "bread"]
print(f"Does the list contain 'milk'? {contains_item(shopping_list, 'milk')}")      # Output: True
print(f"Does the list contain 'eggs'? {contains_item(shopping_list, 'eggs')}")      # Output: False

Note: Python has a built-in, faster way to do this: 'milk' in shopping_list which also returns True or False.


Important: The Difference Between return and print

This is a very common point of confusion for beginners.

  • return: Sends a value out of the function. The function stops executing when it hits a return statement. The returned value can be stored in a variable or used directly.
  • print: Displays a value to the console. It's for showing information to the user, not for passing data between parts of your code. The function continues running after a print.

Example to Illustrate the Difference:

def function_with_return():
  print("This will be printed to the console.")
  return "This is the value returned by the function."
  print("This line will NEVER be executed.")
def function_with_print():
  print("This will be printed to the console.")
  print("This is also printed to the console.")
  # This function has no 'return' statement, so it implicitly returns None.
# --- Let's see the difference ---
print("--- Calling function_with_return ---")
return_value = function_with_return()
print(f"The value stored in 'return_value' is: '{return_value}'")
print("\n--- Calling function_with_print ---")
print_value = function_with_print()
print(f"The value stored in 'print_value' is: '{print_value}'")

Output:

--- Calling function_with_return ---
This will be printed to the console.
The value stored in 'return_value' is: 'This is the value returned by the function.'
--- Calling function_with_print ---
This will be printed to the console.
This is also printed to the console.
The value stored in 'print_value' is: 'None'

Notice how function_with_return never printed its last print statement because the return stopped it. Also, notice that when a function has no return statement, it automatically returns the special value None.

Summary

Keyword Purpose Example
return True Exits the function and sends the boolean value True back to the caller. def check(): return True
return False Exits the function and sends the boolean value False back to the caller. def check(): return False
print() Displays a value in the console for the user to see. The function continues. def show(): print("Hello")
分享:
扫描分享到社交APP
上一篇
下一篇