gpt4 book ai didi

python - 对多个数字求和的函数

转载 作者:行者123 更新时间:2023-11-28 20:01:49 24 4
gpt4 key购买 nike

<分区>

我是 python 的新手,我开始学习执行函数。我开始添加数字,但我只能对两个数字求和,如果我想求和更多,就需要我编辑程序。这是我的代码

def sum(num1,num2):
return num1+num2

a=5
b=7
c=sum(a,b)
print (c)

现在我想创建一个函数,无需编辑代码即可对任意数量的数字求和。这是我所做的:

def sum(num1,num2):
return num1+num2
a=int(input("what is the number you want to add?: "))
ask="yes"
while(ask=="yes"):
b=int(input("what is the number you want to add?: "))
c=sum(a,b)
a=c
ask=input("do you want to add another number?: ")
else:
c=a
print (c)

这行得通,但我认为应该有一种更简单的方法来使用函数来做到这一点……对吗?感谢您的帮助!

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