Reputation: 169
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?
Upvotes: 0
Views: 745
Reputation: 6356
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)
Upvotes: 0
Reputation: 29121
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))
Upvotes: 0
Reputation: 1123610
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.
Upvotes: 5