Python函数嵌套调用:如何插入name参数生成目标字符串?
Let's break down what's going wrong here and fix it step by step:
The Core Issue
Your get_knights_greeting function defines a name parameter but never actually uses it in the returned string. That's why when you call it with 'John', the output still says "I am of the Knights who say" instead of including the name.
Corrected Code
First, update get_knights_greeting to properly inject the name parameter into the string using an f-string:
def get_knights_greeting(name, answer='Ni'): return f"I am {name} of the Knights who say "
Then, your get_new_knights_greeting function can call this updated function with the correct name argument and append the required phrase:
def get_new_knights_greeting(): return get_knights_greeting('John') + "Ekke Ekke Ekke Ekke Ptang Zoo Boing!"
How It Works
- When
get_new_knights_greeting()runs, it callsget_knights_greeting('John'), which returns the string"I am John of the Knights who say ". - We then concatenate that result with the silly phrase, giving you the exact output you want:
"I am John of the Knights who say Ekke Ekke Ekke Ekke Ptang Zoo Boing!"
Bonus: A Cleaner Approach Using the answer Parameter
If you want to lean into the existing answer parameter instead of concatenating strings, you can adjust get_knights_greeting to include it in the returned string:
def get_knights_greeting(name, answer='Ni'): return f"I am {name} of the Knights who say {answer}!"
Then get_new_knights_greeting can simply override the default answer value:
def get_new_knights_greeting(): return get_knights_greeting('John', answer="Ekke Ekke Ekke Ekke Ptang Zoo Boing!")
This keeps all the string formatting logic contained within get_knights_greeting for a more modular setup.
内容的提问来源于stack exchange,提问作者dsapprentice

