【问题标题】:Python: Can't get it to loop back to where I want itPython:无法让它循环回到我想要的地方
【发布时间】:2013-11-30 22:33:58
【问题描述】:

当用户输入总和大于 2000 的数字时,代码应该重置回 0,然后继续询问数字,直到总和正好等于 2000。我的代码将总和重置回 0,但保持在 0并且不会将任何用户输入添加到总数中。我知道这是一个循环问题,我只是不知道如何让它循环回 0 并重新开始。我特意将“print(total)”作为最后一行代码,这样我就可以看到总数发生了什么。

my_list = []
print "Rules of the game, keep adding numbers to get exactly 2000!"

while True:
     numbers = raw_input(" Please enter a number: ")

     total = 0

     for num in numbers.split():
         my_list.append(int(num))

     for value in my_list:
         total += int(value)

     if total < 2000:
        print "Current total:"
        print(total)
     elif total == 2000:
        print " Congratulations!"
        break
     elif total > 2000:
        total = 0
        print "Sorry you went over. Try Again."
        print(total)

执行示例)

Rules of the game, keep adding numbers to get exactly 2000!
 Please enter a number:  2002
Sorry you went over. Try Again.
0
 Please enter a number:  10
Sorry you went over. Try Again.
0
 Please enter a number:  50
Sorry you went over. Try Again.
0
 Please enter a number:   

【问题讨论】:

    标签: python loops while-loop add


    【解决方案1】:

    那是因为您每次都将其重置为零。将总变量的 decleration 放在将解决它的循环之外:

    total = 0
    while True:
         numbers = raw_input(" Please enter a number: ")
         ...etc...
    

    您遇到的另一个问题是 value_list 保持相同。你不断地向它添加数字,并且每轮都添加所有数字。假设您在第一轮插入 1?所以现在 total 也是 1。再次加 1,现在总数将是 3 而不是 2。因为您在上一轮的基础上加了 1。因此,不要附加到 mylist,而是重新创建 if 每个循环。换句话说 - 将 mylist 放入循环中:

    total = 0
    while True:
        numbers = raw_input(" Please enter a number: ")
        mylist = []
    

    【讨论】:

    • 我将变量的声明移到循环的外部,但它仍然重置为 0 并保持为 0。例如)游戏规则,不断添加数字以得到 1001!请输入一个数字:1000 当前总数:1000 请输入一个数字:1000 对不起,您过去了。再试一次。 0 请输入一个数字: 10 对不起,你走了。再试一次。 0 请输入一个数字:50 对不起,你走了。再试一次。 0 请输入一个数字:
    • 将此作为对您原始帖子的编辑发布,我真的无法这样阅读。
    • 另外,我复制粘贴了代码,它对我有用(在像我的答案一样更改之后)。您需要更改、保存然后重新运行程序。您是否遵循了这些确切的步骤?
    • 好了。 total 和 mylist 交换位置和 shazam!另外,由于您使用的是 python 3.x,因此约定是使用 input 而不是 raw_input
    • 啊,好吧,这么小的错误,哈哈,现在可以了。谢谢!!
    【解决方案2】:
    elif total > 2000:
        total = 0
    

    当你将总数重置为 0 时,my_list 仍然包含所有以前的数字 (其总数超过 2000),因此,从此时起,您的总数将始终 超过2000。

    解决方案:您也必须重置 my_list。

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 2021-11-29
      相关资源
      最近更新 更多