繁体   English   中英

如何使我的代码循环并将以前的结果与新结果相加

[英]How do I make my code loop and add the previous result with the new result

所以我的问题是:编写一个程序,要求用户输入两个数字。 应将数字相加并显示总和。 然后程序会询问用户是否要继续输入。 如果他或她回答“y”或“yes”,程序将要求用户重新输入两个数字并再次计算总和(总和将被累加)。
否则,程序将终止。

现在我的代码是这样的:

number1 = int(input("Please enter the first number: "))
number2 = int(input("Please enter the second number: "))
result = number1 + number2
print("\nThe sum is:", result)

while True:
   a = input("Do you want to continue (Yes or No): ").lower()
   if a == "yes":
       print(
  
   elif a == "no":
       print(
       break

但我不知道如何再次要求用户输入两个新数字,然后将它们添加到之前的结果中。

你几乎拥有它。 只需将输入移动到循环内部并将结果存储在循环外部:

result = 0

while True:
    number1 = int(input("Please enter the first number: "))
    number2 = int(input("Please enter the second number: "))

    result = result + number1 + number2

    print("\nThe sum is:", result)

    a = input("Do you want to continue (Yes or No): ").lower()
    if a != "yes":
       break

因为,你想继续输入, input语句应该进入while循环。 此外, result变量应该被初始化以便更新。 如果答案是yes您可以在if条件中添加continuerestart while 循环。 此外,即使您不写yesno ,您的程序也会运行。 为了解决这个问题,我们可以添加一个else语句。 这是更新后的代码:

result=0 #initializing the 'result' variable
while True:
   number1 = int(input("Please enter the first number: "))
   number2 = int(input("Please enter the second number: "))
   result += number1 + number2 #updating the result
   print("\nThe sum is:", result )
   a = input("Do you want to continue (Yes or No): ").lower()
   if a == "yes":
      continue #continuing the loop if the answer is yes
   elif a == "no":
       print("bye")
       break
   else:
      print("wrong input !! please try again")
      a = input("Do you want to continue (Yes or No): ").lower()

测试

Please enter the first number: 2
Please enter the second number: 2

The sum is: 4
Do you want to continue (Yes or No): ll
wrong input !! please try again
Do you want to continue (Yes or No): yes
Please enter the first number: 2
Please enter the second number: 2

The sum is: 8
Do you want to continue (Yes or No): no
bye

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM