python - 多函数参数 - learnpython.org

标签 python python-2.7

Python 新手。 2天了都不知道这个问题的答案.. 会很感激一些帮助,谷歌搜索没有帮助。

填写“foo”和“bar”函数,以便它们可以接收可变数量的参数(3 个或更多)“foo”函数必须返回接收到的额外参数的数量。如果带有关键字“magicnumber”的参数值为 7,则“bar”必须返回“True”,否则返回 False。

# edit the functions prototype and implementation
def foo(a, b, c):
    pass

def bar(a, b, c):
    pass


# test code
if foo(1,2,3,4) == 1:
    print "Good."
if foo(1,2,3,4,5) == 2:
    print "Better."
if bar(1,2,3,magicnumber = 6) == False:
    print "Great."
if bar(1,2,3,magicnumber = 7) == True:
    print "Awesome!"

我想.. 一些部分代码会很好,但很难理解 **kwargs 和所有这些:\

最佳答案

我不确定您是否只是想让别人给您代码,但既然您已经说过您正在尝试学习,我现在就为您指明正确的方向。您想使用 Python 的关键字参数。

Thisthis应该可以帮助您入门。

[编辑]

代码如下:

def foo(a, b, c, *args):
    return len(args)

def bar(a, b, c, **kwargs):
    if kwargs["magicnumber"] == 7:
      return True
    return False

关于python - 多函数参数 - learnpython.org,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19257467/

相关文章:

python - 如何使用 Python 提取在 HTML 页面 javascript block 中定义的 JSON 对象?

python - 当使用 Dill 和与 Pickle 配合良好的代码时,出现 "pickle exhausted before end of frame"

python - django.conf.global_settings 何时加载?

python - Flask-pymongo 运行时错误 : Working outside of application context

python - 守护线程启动软件不会死

python-2.7 - ValueError : The number of classes has to be greater than one (python)

python-2.7 - 如何解决 lmdb.Error : mdb_txn_commit: Input/output error?

Python Pandas Dataframe 在单元格中搜索文本

python - 在异常期间从所有堆栈帧检索所有事件变量

python - 如何让 pip 默认安装到 HOME 中?