杰瑞科技汇

Python return true如何使用?

Of course! In Python, the keyword return is used to exit a function and send a value back to the code that called the function.

Python return true如何使用?-图1
(图片来源网络,侵删)

When you want a function to return True, you simply use the statement return True.

Here’s a breakdown with examples.

The Basic Syntax

The return statement immediately stops the function's execution and sends the specified value back.

def is_even(number):
  """Checks if a number is even."""
  if number % 2 == 0:
    return True  # The function stops here and returns True
  else:
    return False # If the condition is false, it returns False
# --- How to use it ---
result1 = is_even(10)
print(f"Is 10 even? {result1}")  # Output: Is 10 even? True
result2 = is_even(7)
print(f"Is 7 even? {result2}")   # Output: Is 7 even? False

Returning True Based on a Condition

A very common pattern is to have a function that returns True only if a certain condition is met.

Python return true如何使用?-图2
(图片来源网络,侵删)

Example: Checking if a user is an adult

def is_adult(age):
  """Checks if a person is 18 years or older."""
  if age >= 18:
    return True
  # If the age is less than 18, the function implicitly returns None
  # (which is "falsy" in Python)
# --- How to use it ---
user_age = 21
if is_adult(user_age):
  print("Access granted. You are an adult.")
else:
  print("Access denied. You must be an adult.")
# Output: Access granted. You are an adult.

Simplifying with Direct return

You can often make your code more concise by returning the result of the condition directly. A condition in an if statement already evaluates to True or False.

This is a very "Pythonic" way to write the same functions.

# A more concise version of the is_even function
def is_even_concise(number):
  """A more concise way to check if a number is even."""
  return number % 2 == 0
# A more concise version of the is_adult function
def is_adult_concise(age):
  """A more concise way to check if a person is an adult."""
  return age >= 18
# --- How to use them ---
print(f"Is 10 even? {is_even_concise(10)}")   # Output: Is 10 even? True
print(f"Is 7 even? {is_even_concise(7)}")    # Output: Is 7 even? False
print(f"Is 25 an adult? {is_adult_concise(25)}") # Output: Is 25 an adult? True

Returning True from a Loop

You might want to loop through something and return True as soon as you find what you're looking for. The return statement will also exit the loop.

Python return true如何使用?-图3
(图片来源网络,侵删)

Example: Checking if a name exists in a list

def find_name(name_to_find, names_list):
  """Searches for a name in a list and returns True if found."""
  for name in names_list:
    if name == name_to_find:
      print(f"Found {name_to_find}!")
      return True  # Exit the function and loop immediately
  # If the loop finishes without finding the name
  return False
# --- How to use it ---
friends = ["Alice", "Bob", "Charlie"]
found = find_name("Bob", friends)
print(f"Search result: {found}") # Output: Search result: True
not_found = find_name("David", friends)
print(f"Search result: {not_found}") # Output: Search result: False

The Importance of return vs. print

This is a very common point of confusion for beginners.

  • return: Sends a value out of a function so it can be stored in a variable or used in an expression. The function call itself becomes the value.
  • print: Displays a value to the console. It's for showing output to the human user, not for passing data between parts of your program.
# Function that RETURNS True
def returns_true():
  return True
# Function that PRINTS True
def prints_true():
  print(True)
# --- The difference ---
# 1. Using the function that RETURNS
result = returns_true()
print(f"The function returned: {result}")
# You can now use the 'result' variable
if result:
  print("This code runs because the result is True.")
# Output:
# The function returned: True
# This code runs because the result is True.
# 2. Using the function that PRINTS
value = prints_true()
print(f"The function returned: {value}")
# You cannot use the 'value' variable for logic because it's None
if value:
  print("This code will NOT run.")
# Output:
# True  (this is from the print() inside the function)
# The function returned: None

Summary

Your Goal How to return True in Python Example
Basic Return return True def check(): return True
Based on a Condition return (some_condition == some_value) def is_ready(status): return status == "ready"
After a Loop (if found) Loop, check condition, return True if found, return False after def find_item(items, target): for item in items: if item == target: return True
Crucial Distinction Use return to send data out of a function. my_var = my_function()
Use print() to show data to the console. my_function()
分享:
扫描分享到社交APP
上一篇
下一篇