无需使用if定义多参数函数?creepy函数编写问题求助
Hey there! Let's break down your two tech questions with practical, straightforward solutions:
if statements if statements are useful, but they’re not the only way to handle conditional logic in functions. Here are a few clean alternatives tailored to different scenarios:
Dictionary mapping for action-based logic
If your function needs to run different operations based on a parameter value, map those operations to a dictionary. For example, a calculator function that uses an operator parameter:def calculate(a, b, op): operations = { "add": lambda x, y: x + y, "subtract": lambda x, y: x - y, "multiply": lambda x, y: x * y, "divide": lambda x, y: x / y if y != 0 else None } return operations[op](a, b)Ternary expressions for simple binary returns
For straightforward "either/or" return values, use a ternary expression to keep code concise:def get_admission_status(score): return "Accepted" if score >= 75 else "Rejected"Boolean indexing for fixed result sets
Since Booleans in Python evaluate to1(True) and0(False), you can use them as indexes for a list of possible results:def get_task_outcome(succeeded): return ["Failed", "Completed"][succeeded]Direct logical/mathematical expressions
If your condition boils down to a simple boolean check, just return the expression's result directly—this is exactly what we'll do for yourcreepyfunction below.
creepy function First, let's clarify the requirement: return True if the age pair violates the acceptable dating rule, False if it’s allowed. The core acceptable rule translates to: the younger person’s age must be at least half the older person’s age plus 7.
Here’s a clean, if-free implementation that meets all your needs:
def creepy(age1, age2): older_age = max(age1, age2) younger_age = min(age1, age2) # Return True if the younger person is too young relative to the older one return younger_age < (older_age / 2) + 7
Or even more concise (same logic, just condensed):
def creepy(age1, age2): return min(age1, age2) < max(age1, age2) / 2 + 7
How this works:
- We first grab the larger and smaller of the two ages using
max()andmin(). - We check if the younger age falls below the threshold (
older_age/2 +7). If it does, the pair is "creepy" so we returnTrue; otherwise, we returnFalse. Noifstatements required!
内容的提问来源于stack exchange,提问作者Yungpythonnoob

