-13

How would I go about adding lets say numbers from 1 to 100 inclusively using a while loop and then doing using a for loop to do the program again

matebende
  • 503
  • 7
  • 18
imapython
  • 1
  • 1
  • 3
  • 9
    "Kinda confused" is a bit unspecific - which part is confusing? Have you read a basic tutorial on [`while`](https://docs.python.org/2/tutorial/introduction.html#first-steps-towards-programming) and [`for`](https://docs.python.org/2/tutorial/controlflow.html#for-statements) loops - and if so, what is still unclear? – Tim Pietzcker Nov 24 '14 at 17:15
  • @imapython Here is another similar question: http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python It will answer your question. – AHuman Nov 24 '14 at 18:02

5 Answers5

1

Here is an example of one of the many ways to do it with a while-loop.

iteration = 0
sum = 0
while iterations<len(range(1,101)): #You may need to add or subtract one from the left side of the inequality 
    sum+=range(1,101)[iteration] 
    iteration+=1

The for-loop is very very similar.

sum = 0
for num in range(1,101):
    sum+=num
AHuman
  • 1,597
  • 3
  • 16
  • 27
0
my_list = [0]
count = 0
while count < 100:
    count = count + 1
    my_list.append(count)
print (sum(my_list))



count = 0
total = 0
for count in range(0,101):
    total = total + count
print (total)
0

This will work:

sum(xrange(101))
StackG
  • 2,560
  • 5
  • 26
  • 45
-1

Using while

count=0
b=0
while count <100:
    count+=1
    b+=count

and for:

b=0
for i in range(1,101):
    b+=i
print (b)
  • 6
    This is just flat out wrong. You are making lists that would print out 1, 2, 3, 4 ... when the question is asking for sums. – takendarkk Nov 24 '14 at 17:25
  • There is also the great way that takes only one line: `lst = range(1,101)` – AHuman Nov 24 '14 at 17:47
  • Where is the sum in the question? – Rodriguesms Nov 24 '14 at 17:48
  • 1
    "How would I go about adding lets say numbers 1 to 100..." – AHuman Nov 24 '14 at 17:50
  • Now edit your answer accordingly without looking at the code I made. There are SOOOO many ways to add numbers 1 to 100. Oh, fix it again. This is like a Fibonacci number FYI. – AHuman Nov 24 '14 at 17:52
  • No, you did not fix your answer. But, you are very close on your second example. Hint: You need another variable called `sum`. – AHuman Nov 24 '14 at 17:55
  • @Rodriguesms No you did not. All you code you have above is the same as `lst = range(1,101)`. What you need to do is add all of these values together. Go to your python editor and run your code when you have solved it. The value of the added sum should be: `5050`. – AHuman Nov 24 '14 at 18:00
-1

Using reduce:

>>> from itertools import *
>>> reduce(lambda x,y:x+y,range(1,101))
    5050

Using sum:

>>> sum(range(1,101))
    5050
Jamal
  • 750
  • 7
  • 22
  • 31