-2

How do I print how many times a while loop has run?

Example:

from random import*

c=0

while c<3 :

    a=randint(1,6)

    b=randint(1,6)

    if a==b:
       print(a,b)
       c=c+1
DAB
  • 7
  • 4

3 Answers3

1

You can just add another counter.

from random import *
c = 0
loop_counter = 0
while c < 3:
  a = randint(1,6)
  b = randint(1,6)
  if a==b:
     print(a,b)
     c += 1
  loop_counter += 1

print(f"The loop run {loop_counter} times.")
Vladimír Kunc
  • 379
  • 1
  • 4
0

By adding a "counter variable", something that increases for each loop.

As an example:

from random import*

c=0
counter = 0 #define

while c<3 :
    counter += 1 #add one 
    print (counter) #print
    a=randint(1,6)

    b=randint(1,6)

    if a==b:
       print(a,b)
       c=c+1

You can also just print "counter" after the while loop has ended to get a final tally.

nordmanden
  • 340
  • 1
  • 10
0
from random import *

c=0
Counter=0
while c<3 :

    a=randint(1,6)

    b=randint(1,6)

    if a==b:
       print(a,b)
       c=c+1
    Counter+=1

print (Counter)
Revisto
  • 1,211
  • 7
  • 11
  • 1
    I strongly advice against using variable names with first letter capitalized. It is wrong code style (it then looks as a class Counter) – Vladimír Kunc Aug 25 '20 at 11:36
  • 1
    Generally code-only answers are discouraged. Please [edit] to include a description of the change you made, and why you made it. Also please point it out with comments in the code. And please take some time to read about [how to write good answers](https://stackoverflow.com/help/how-to-answer). – Some programmer dude Aug 25 '20 at 11:40
  • 1
    if you are happy with the answer , I will be grateful if you vote . – Revisto Aug 25 '20 at 20:08