写入另一个函数中定义的字符串

时间:2020-04-09 11:02:21

标签: python function

编写一个函数get_knights_greeting(name,answer ='Ni'),该函数返回'我是说'的骑士'。 然后编写另一个没有输入参数的函数get_new_knights_greeting,该函数将调用上一个函数以返回“我是骑士的约翰,谁说Ekke Ekke Ekke Ekke Ptang Zoo Boing!”

除以下内容外,我找不到其他答案。我的问题是,当我进入get_new_knights_greeting()函数时,如何在给定的字符串之间写John?

我的预期结果是“我是骑士的约翰,说埃克·埃克·埃克·埃克·彭克·汤博恩!”

如何使用嵌套在第二个函数中的第一个函数获得此结果?

def get_knights_greeting(name, answer='Ni') :
    return  'I am of the Knights who say'


def get_new_knights_greeting():


    return get_knights_greeting('John')+' Ekke Ekke Ekke Ekke Ptang Zoo Boing!'

我得到的输出是“我是说Ekke Ekke Ekke Ekke Ptang Zoo Boing的骑士!”

2 个答案:

答案 0 :(得分:1)

我想知道您是否已准确记录了原始问题。当然,函数get_knights_greeting应该输出其传递的参数。它可以通过几种方式做到这一点:

  1. return 'I am %s of the Knights who say %s' % (name, answer)'
  2. return 'I am {} of the Knights who say {}'.format(name, answer)
  3. return 'I am {name} of the Knights who say {answer}'.format(answer=answer, name=name)
  4. return f'I am {name} of the Knights who say {answer}'#仅适用于Python 3

然后:

def get_new_knights_greeting():
    return get_knights_greeting('John', answer='Ekke Ekke Ekke Ekke Ptang Zoo Boing!')

答案 1 :(得分:0)

据我所知,您的问题有两种解决方法:

def get_knights_greeting(name='', answer='Ni') :
    return  'I am {} of the Knights who say'.format(name)

def get_new_knights_greeting():
    return get_knights_greeting('John')+' Ekke Ekke Ekke Ekke Ptang Zoo Boing!'

Python还支持内部函数,因此您也可以这样做

def get_new_knights_greeting():

    def get_knights_greeting(name='', answer='Ni') :
        return  'I am {} of the Knights who say'.format(name)

    return get_knights_greeting('John')+' Ekke Ekke Ekke Ekke Ptang Zoo Boing!'


>> I am John of the Knights who say Ekke Ekke Ekke Ekke Ptang Zoo Boing!