所以我正在练习python编码。我的问题是“因此,我制作了一个程序,将用户输入的所有数字相加,但是程序的输出不是用户输入的所有数字的总和。
答案 0 :(得分:1)
第一个sum_num需要一个初始值
sum_num = 0
,并且每次都需要在循环中更改sum_num:
sum_num = sum_num + num
所有基于您的代码:
i = 0
sum_num = 0
while 1 == 1:
num = int(input('enter a number :'))
sum_num = sum_num + num
i = i + 1
if i > 5:
print('Total number is :' + str(sum_num))
break
如果有帮助,请接受。
答案 1 :(得分:0)
您可以通过其他代码完成相同的工作 如果您要计算用户要输入的数字,则可以使用以下代码:
#create a variable that store the total value
sum_num = 0
#for loop take a the number in range to repeat the code by it
for i in range(5):
#take the number from user and store it
num = int(input("Enter a number: "))
#add the number to total variable
sum_num += num
#at the end of the loop print the total
print("Total Number Is " + str(sum_num))
如果您没有数量,用户将输入“使用这种方式”:
#create a variable that store the total value
sum_num = 0
#create flag that tell me if user won't enter any other numbers or he want to
#enter more numbers
flag = True
#while loop take a flag and will be in the loop while flag is true
while(flag):
#take the number from user and store it
num = int(input("Enter a number: "))
#add the number to total variable
sum_num += num
#ask user if he want to continue
ask = input("Do you want to continue : ")
if(ask.lower() == 'no' or ask.lower() == 'n') :
flag = False
#at the end of the loop print the total
print("Total Number Is " + str(sum_num))