如何在每一步接收一个num,一直到输入0;然后这个程序应该输出输入nums的和



如何编写一个程序,在每一步从输入中接收一个数字,并继续工作,直到输入零。输入零数字后,该程序应打印输入数字的总和。我想在n条不同的线上得到n个不同的数字当它到达0

时它就停止了例:(输入:)

3

4

5

0

输出:

12

实际上我有这个代码,但它不工作:"巨蟒">

Sum= 0
Num = int(input())
While num!=0 :
Num = int(input())
Sum+= num
Print(sum)

但是它给出的是' 9 '而不是' 12 '

代码:-

total_sum=0
n=int(input("Enter the number: "))
while n!=0:
total_sum+=n
n=int(input("Enter the number: "))
print("The total sum until the user input 0 is: "+str(total_sum))

输出: -

# Testcase1User_input:- 10,0

Enter the number: 10
Enter the number: 0
The total sum until the user input 0 is: 10

# Testcase2User_input:- 3,4,5,0

Enter the number: 3
Enter the number: 4
Enter the number: 5
Enter the number: 0
The total sum until the user input 0 is: 12

#即兴创作- {删除上述代码中n初始化的冗余(在while循环之前和while循环内部执行两次)}

代码:

total_sum=0
while True:
n=int(input("Enter the number: "))
total_sum+=n
if not n:
break
print("The total sum until the user input 0 is: "+str(total_sum))

输出: -

同上

这里我使用了一个while循环,它一直持续到用户输入为0,然后打印出总和。

res = 0
user_input = int(input('Input a number: '))
while user_input != 0:
res+= user_input
user_input=int(input('Input a number: '))
print("You entered 0 so the program stopped. The sum of your inputs is: {}".format(res))

相关内容

最新更新