Search code examples
pythonfunctionwhile-loopcounter

Python counter confusion for while loop


import random, string

goal='methinks it is like a weasel'

def simulation(length):
   return ''.join(random.choice('abcdefghijklmnopqrstuvwxyz ') for i in range(length))

def score(stri):
    if stri==goal:
        print(100)
    else:
        print(0)

n=0
stri='abcd'
while score(stri) != 100:
      n += 1
      stri = simulation(28)
print(n)

For the final while loop, as long as score(stri) not equal to 100, it'll iterate and accumulate n, correct? Then I'll printout the accumulated n , when score(stri) happened to equal 100.

But I got results like:

0
0
0
0
0
0
...

Obviously it's always outputing 'n=0'; it's because this is global variable?

But I then tried extremely easy while loop:

n=0
while n <= 5:
    n += 1
print(n)

It's successfully outputs 6

I don't know why my first code goes wrong, guess while loop gets sth wrong because of def()?


Solution

  • You need to return from score instead of printing:

    def score(stri):
        if stri == goal:
            return 100
        else:
            return 0
    

    This is failing herewhile score(stri) != 100: because when you call the function score it is only printing (displaying output) and not returning a value to be used in the while loop condition.