Equivalent while loop block for a for loop block

Viewed 46

I am a novice trying to learn python from Automate The Boring Stuff with Python by Al Sweigart and I came across his block of code to answer a math problem: "What is the sum of all the numbers from 0 to 100?" Apparently, this was a question Gauss got when his teacher wanted to keep him busy.

Sweigart used a for loop and range() function to get the answer:

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

A page later he states that "you can actually use a while loop to do the same thing as a for loop; for loops are more concise."

How would this statement be rendered in a while loop?

I tried replacing the for with while but got an error: "name 'num' is not defined." I also tried to set up a summation math equation using another block of code from another forum, but completely got lost.

print('Gauss was presented with a math problem: add up all the numbers from 0 to 100. What was the total?')
a=[1,2,3,4,5,...,100]
i=0
while i< len(a)-1:
    result=(a[i]+a[i+1])/2
    print(result)
    i +=1

Then, I tried to setup i in an equation that would loop until each number was added, but got stuck.

print('Gauss was presented with a math problem: add up all the numbers from 0 to 100. What was the total?')
i=0
while i<101:
    i=i+1
    a=i

Would the while statement be too complex to warrant the effort?

2 Answers

Your last example comes close.

A for loop of this form:

for x in range(N):
    # ...

can be replaced by a while loop like this:

x = 0
while x < N:
    # ...
    x += 1  # equivalent to x = x + 1

Just make sure you leave the rest of the code unchanged!

The for loop is more concise. Notice how we need a "counter" variable , in this case i with the while loop. That's not to say we don't need them in a for loop, however they're integrated nicely into the syntax to make for cleaner code.

i = 0
total = 0
while i < 101:
    total += i
    i += 1
print(total)

Python's for loop syntax is also a foreach equivalent:

for eachItem in list:
# Do something
Related