0

I'm just starting to learn while loops.

I'm trying to iterate same number 10 times using a while loop.

I figured out how I can utilize while loop in order to stop at a certain point as it increases

But I can't figure out how to stop at a certain point without having to add 1 and setting a limit.

Here is my code

i = 1
total = 0
while i < 11:
    print i
    i += 1
    total = i + total
print total

This prints

1,2,3,4,5,6,7,8,9,10,65

in a separate line

How could I modify this result?

1,1,1,1,1,1,1,1,1,1,10?

3 Answers 3

5

Just print a literal 1 and add 1 to the total:

while i < 11:
    print 1
    i += 1
    total += 1

You need to keep track of how many times your loop is run, and using i for that is fine, but that does mean you need to increment it on each run through.

If, during each loop, you only want to add one to the total, just do that and don't use the loop counter for that.

Sign up to request clarification or add additional context in comments.

2 Comments

That'll still print 65 instead of 10 at the end . . .
Ah, I see. This did the job. I understand. Thanks
0
i = 1
total = 0
res = []
while i < 11:
    res.append(1)
    i += 1
print ', '.join(res) +', '+ str(sum(res))

or with for:

vals = [1 for _ in range(10)]
print ', '.join(vals) +', '+ str(sum(vals))

Comments

0

The whole point of a while loop is to keep looping while a certain condition is true. It seems that you want to perform an action n times then display the number of times the action was performed. As Martijn mentioned, you can do this by printing the literal. In a more general sense, you may want to think of keeping your counter separate from your variable, e.g.:

count = 1
number = 3
while count <11:
  print number*count
print "While loop ran {0} times".format(count)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.