简体   繁体   中英

Trying to calculate the sum of numbers using while loop

I'm trying to calculate the sum of multiple numbers using a while loop. When a negative number is entered the sum of the numbers should be printed. When I run the code all it does is print the last positive number entered. Here is the current non-working code:

sum = 0
number = 1
while number > 0:
    number = int(input('Enter a positive number: '))
    if number > 0:
        tot = sum + number
print("The sum of the numbers is", tot)

You keep modifying a variable called tot but it gets overwritten each time with sum (0) plus number (the current number).

Instead, add the total to sum each time as follows:

sum = 0
number = 1
while number > 0:
    number = int(input('Enter a positive number: '))
    if number > 0:
        sum = sum + number
print("The sum of the numbers is", sum)

Now sum will keep growing as you enter positive numbers. You don't need the variable tot at all!

You can even use this cool " += " operator to increment the value of sum directly and save you some typing:

sum = 0
number = 1
while number > 0:
    number = int(input('Enter a positive number: '))
    if number > 0:
        sum += number
print("The sum of the numbers is", sum)

You might have confused the variable names tot and sum . If you replace tot with sum , your output will be the correct sum. This way, sum is correctly updated, based on its previous value:

sum = 0
number = 1
while number > 0:
    number = int(input('Enter a positive number: '))
    if number > 0:
        sum = sum + number
print("The sum of the numbers is", sum)

In each iteration you are add the number with the sum variable which is initialised as 0 . so need to change the addition expression & add update the sum variable in each iteration with the previous iteration sum + the new entered number in each iteration.

Code :

sum = 0
number = 1
while number > 0:
    number = int(input('Enter a positive number: '))
    if number > 0:
        sum = sum + number
print("The sum of the numbers is", sum)

Output :

在此处输入图片说明

It's because sum is always 0 - try this instead;

tot = 0
number = 1
while number > 0:
    number = int(input('Enter a positive number: '))
    if number > 0:
        tot = tot + number
print("The sum of the numbers is", tot)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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