Click here to Skip to main content
15,895,740 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This is what I've tried but my output is wrong. My program is, to sum up all the integers listed, however with this code just gives me the integer 4500.

What I have tried:

Python



num = int(input('Please Choose a number between 0 and 1000: '))
result = 0

for num in range(0,1001):
    digit = num % 10
    result = result + digit 
    num = num//10
        
    
print('The Total Sum is:',result)
Posted
Updated 17-Sep-21 22:04pm

Python
num = int(input('Please Choose a number between 0 and 1000: '))
result = 0

for num in range(0,1001): // you have just overwritten the user's input
    digit = num % 10
    result = result + digit 
    num = num//10
        
print('The Total Sum is:',result)

It should be something like:
Python
num = int(input('Please Choose a number between 0 and 1000: '))
result = 0

for i in range(1, num + 1):
    result = result + i 
print('The Total Sum is:',result)

or even
Python
num = int(input('Please Choose a number between 0 and 1000: '))
result = sum(range(num + 1))
print('The Total Sum is:',result)
 
Share this answer
 
Quote:
This is what I've tried but my output is wrong.

You forgot to tell what correct result you are expecting.
You forgot to tell what is supposed to do this code.
Quote:
My program is, to sum up all the integers listed,

You need to explain in detail what is is supposed to do the code and what result you expect.
Quote:
however with this code just gives me the integer 4500.

Your code is doing the sum of a unit digits of all integer, and 4500 is correct result.
Quote:
How do I turn this while loop into a for loop

By the way, you didn't showed any code with a while loop.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900