Reputation:
I have a homework to create a program that counts the amount of adding the numbers from 1 to 100 (1+2+3+4+5.....), using the while loop!
I tried the code provided down below! But the problem with it is that I already know the amount, but I need to make the program calculate it!
Code I tried:
amount = 0
while amount <= 5050:
amount += 1
print("The amount is: " + str(amount))
Upvotes: 0
Views: 2611
Reputation: 24691
So what you're doing now is adding 1 until you reach 5050. Instead, you want to add the numbers 1 through 100. The solution, then, is to have two variables - one representing the total sum so far (this can be amount
), and another representing the number you're adding. You continue to increase the amount you add, for each iteration, until you've added 100 to your running total.
amount = 0
to_add = 1
while to_add <= 100:
amount += to_add
to_add += 1
A more traditional way to do this would be to use a for
loop, which can let you iterate over "the list of numbers from 1 through 100" (which you get by using the built-in range()
function):
amount = 0
for i in range(1, 101):
amount += i
Upvotes: 1