在Python中添加和

在Python中添加和,python,sum,Python,Sum,我必须制作一个代码,用户输入的数字总和将达到1001。但它不能超过这个数字,否则它会重置为零。我遇到的唯一问题是获取它,这样当用户到达1001时,代码将打印一条祝贺消息。这是到目前为止我的代码 我是Python新手,非常感谢您提供的任何帮助 编辑 到目前为止,我有这个,它的工作,以增加总和 print ("Want to play a game? Add numbers until you reach 1001!") print ("Current total is 0!") total=0 w

我必须制作一个代码,用户输入的数字总和将达到1001。但它不能超过这个数字,否则它会重置为零。我遇到的唯一问题是获取它,这样当用户到达1001时,代码将打印一条祝贺消息。这是到目前为止我的代码

我是Python新手,非常感谢您提供的任何帮助

编辑

到目前为止,我有这个,它的工作,以增加总和

print ("Want to play a game? Add numbers until you reach 1001!")
print ("Current total is 0!")
total=0
while total < 1001:
    store=raw_input("Enter a number!") 
    num=int(store)
    total=total+num
    print total
print ("Congratulations! You won!") 
在您的例子中,while1001>0,这总是正确的,因此您得到一个无限循环。此外,虽然1001==sum也将产生一个无限循环,但考虑到一旦到达该循环,就永远不会更改sum。以下是代码的简化和固定版本:

#sum is a function, so name it something else,  I chose sum_ for simplicity's sake
while sum_ != 1001:
    #instead of using an intermediate, I just combined the two lines
    num=int(raw_input("Enter a number!"))

    #This is equivalent to sum = sum + num
    sum_ += num
    print sum_

    #Need to reset if sum_ goes above 1001
    if sum_ > 1001:
        sum_ = 0

#By the time you get here, you know that _sum is equal to 1001
print ("Congratulations! You won!") 

您的两个while循环都将永远运行,因为它们的条件将始终计算为True。实际上,您甚至永远不会到达第二个while循环,因为第一个将永远运行

以下是脚本的固定版本:

print "Want to play a game? Add numbers until you reach 1001!"
print "Current total is 0!"
# Don't name a variable `sum` -- it overrides the built-in
total = 0
# This will loop until `total` equals 1001
while total != 1001:
    store = raw_input("Enter a number!") 
    num = int(store)
    # This is the same as `total=total+num`
    total += num
    print total
    # If we have gone over 1001, reset `total` to 0
    if total > 1001:
        print "Oops! Too Far! Start Again!"
        total = 0
# When we get here, the total will be 1001
print "Congratulations! You won!"

还有一段时间的原因是什么?恒定的表达条件令人惊讶!!!当前代码永远不会离开第一个循环,因为1001>0始终为真。另外,第二个while应该是一个if-你不想在sum是1001时无休止地打印消息。@Jack-不,你现在看到的是我几分钟前写的一篇不正确的帖子。对不起,我没有仔细阅读这个问题。我当前的帖子或史蒂夫的帖子按照你想要的方式工作。@iCodez,我现在明白了。谢谢现在一切似乎都正常了!非常感谢。我认为有一个惯例,即在内置名称后应加下划线。我记不起链接了…@iCodez你是对的,这是答案。Ctrl-F以避免使用约定
print "Want to play a game? Add numbers until you reach 1001!"
print "Current total is 0!"
# Don't name a variable `sum` -- it overrides the built-in
total = 0
# This will loop until `total` equals 1001
while total != 1001:
    store = raw_input("Enter a number!") 
    num = int(store)
    # This is the same as `total=total+num`
    total += num
    print total
    # If we have gone over 1001, reset `total` to 0
    if total > 1001:
        print "Oops! Too Far! Start Again!"
        total = 0
# When we get here, the total will be 1001
print "Congratulations! You won!"