如何在Python上的For循环中添加输入请求的数字?

2024-09-30 20:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我的家庭作业是用“For循环”计算用户输入的一系列数字的总和,但我似乎无法成功地将输入的数字相加。在

我尝试过打印保存循环重复的数字量的变量,并使用“1+2+3+4+5”之类的方法,但它要么每次代码循环都打印,要么打印“15”。代码如下:

listo = (1,2,3,4,5)

for num in range(len(listo)) :
 float(input("Enter a number: "))
 krab = #This is where I'm struggling, as I don't know how to add the inputted numbers.
print "Your total sum is" , krab

输出应该是每次循环的总和,所以如果输入的数字是5到10,程序应该打印“35”。在


Tags: 方法代码用户inforlenisrange
1条回答
网友
1楼 · 发布于 2024-09-30 20:34:10
listo = [1,2,3,4,5] #or you can just do x=5

krab = 0.0

for n in range(len(listo)) :   #range(0,x):

      num = float(input("Enter a number: "))

      krab = num + krab '''this will add the provided number with the present value of krab'''

 print("Your sum is " , krab)

相关问题 更多 >