gpt4 book ai didi

python - 为什么 Python 函数不打印默认值?

转载 作者:行者123 更新时间:2023-11-28 19:50:11 25 4
gpt4 key购买 nike

我是 Python 新手,正在尝试打印参数的默认值集。我的代码如下;

# Functions

def shoppingcart(item='computer', *price):
print item
for i in price:
print i

shoppingcart(100,200,300)

当我运行代码时,我得到的只是值 100,200,300。我期待 computer,100,200,300。我做错了什么?

编辑

如何在 Python 2.7 中实现这一点?

编辑

我更新了我的代码

def shoppingcart(item='computer', *price):
print item
for i in price:
print i

shoppingcart(item='laptop', 100,200,300)

但是得到错误

enter image description here

最佳答案

简单地说,只有在没有其他办法时才使用默认值。这里有 item=100,其他 2 个值进入 *price

在 Python3 中你可以这样写:

def shoppingcart(*prices, item='computer'): 
print(item)
print(prices)

shoppingcart(100,200,300)
shoppingcart(100,200,300, item='moon')

在 Python2 中,您不能在 *args 之后有默认参数,因此您必须找到另一种方式来调用您的函数。

关于python - 为什么 Python 函数不打印默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13793213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com