如何检查函数是否无返回值及Python无特质数字统计程序bug排查
Let's break down your two questions clearly:
In Python, if a function has no explicit return statement, or uses return without a value, it will default to returning None. To check if a function has "no return value" (i.e., returns None), you can directly compare its result to None:
def no_return_func(): pass result = no_return_func() if result is None: print("This function has no return value")
Important distinction: Don't confuse returning an empty value (like '' or []) with having no return value (returning None). Your find_personality function always has a return value—when a number has no traits, it returns an empty string '', not None.
Your code's logic for counting dull numbers is flawed, let's fix that:
Root Cause
Your check for dull numbers uses if '' in trts:—but in Python, an empty string '' is a substring of any string, whether trts is empty or has traits. For example:
print('' in 'odd') # Outputs True print('' in '') # Also outputs True
This is why every number gets counted as dull.
Fixed Solution
The correct check is to verify if trts is exactly an empty string with if trts == ''. I also fixed a minor grammar issue where empty traits would produce awkward output like "X is an number.".
Here's the revised full code:
arrogant_numbers = [3, 6, 7, 23, 25, 35, 39, 66, 68, 112, 119, 254, 259, 732, 737, 4565, 4663, 13330, 13730, 29880, 29998, 79670, 80015, 230054, 239068, 1534301, 1607352, 2060587, 21700891, 99167753, 99873125] def find_personality(number): traits = '' # Find the traits of the number if number % 2 != 0: traits = traits + 'odd ' # Check for other traits after this if number > 10000: traits = traits + 'excessive ' if '3' in str(number): traits = traits + 'irksome ' if number in arrogant_numbers: traits = traits + 'arrogant ' return traits # Write the rest of your program after this dullcounter = 0 numbers = input('Enter numbers: ') number_list = numbers.split() for word in number_list: num = int(word) trts = find_personality(num) if trts: # Clean up trailing space for nicer output clean_traits = trts.strip() print(f"{word} is an {clean_traits} number.") else: print(f"{word} is a dull number.") dullcounter += 1 print(f'Dull numbers: {dullcounter}')
Extra Improvements
- Added
strip()to remove trailing spaces from traits (so output looks like "X is an odd number." instead of "X is an odd number.") - Stored
int(word)in anumvariable for readability - Used
if trts:instead ofif trts != ''—empty strings evaluate toFalsein boolean checks, which is more Pythonic
内容的提问来源于stack exchange,提问作者PurpleHyacinth

