如何在一行中输出两个不同函数的返回结果?
Solution: Output Both Function Results on a Single Line
Hey there! The issue with your current code is that each function uses print() directly, which sends output to a new line every time. To get both the tens and ones text on one line, we need to adjust the functions to return strings instead of printing them, then combine those strings and print them once. Here's the fixed code and breakdown:
Modified Code
print("Enter your number") Number = int(input()) def number_to_text_ones(ones): if ones == 1: return "one" elif ones == 2: return "two" elif ones == 3: return "three" elif ones == 4: return "four" elif ones == 5: return "five" elif ones == 6: return "six" elif ones == 7: return "seven" elif ones == 8: return "eight" elif ones == 9: return "nine" else: return "" # Return empty string for 0 in ones place def number_to_text_tens(tens): if tens == 2: return "twenty" elif tens == 3: return "thirty" elif tens == 4: return "forty" elif tens == 5: return "fifty" elif tens == 6: return "sixty" elif tens == 7: return "seventy" elif tens == 8: return "eighty" elif tens == 9: return "ninety" else: return "" # Return empty string for 0 or 1 in tens place (we'd handle teens separately if needed) # Extract tens and ones digits from the input number tens_digit = Number // 10 ones_digit = Number % 10 # Get text for each part and combine them tens_text = number_to_text_tens(tens_digit) ones_text = number_to_text_ones(ones_digit) # Combine with a space only if both parts exist if tens_text and ones_text: full_text = f"{tens_text} {ones_text}" else: full_text = tens_text + ones_text # Print the result in one line print(full_text)
Key Changes Explained
- Replace
print()withreturn: Instead of each function immediately outputting text, they now send the string back to the caller. This lets us control when and how we print. - Handle zero cases: Added
elseclauses to return empty strings for digits that don't need text (like 0 in the ones place, or 1 in the tens place which would be part of teen numbers). - Combine and print once: We fetch both text strings, combine them with a space only if both are non-empty, then use a single
print()to output everything on one line.
If you need to handle teen numbers (10-19), you'd add an extra check for tens_digit == 1 and map those to "ten", "eleven", etc., but the core idea of returning strings and combining them stays the same.
内容的提问来源于stack exchange,提问作者Alexander
相关产品推荐
相关产品推荐

