Home > Blockchain >  Counter is not increasing python
Counter is not increasing python

Time:12-08

I'm making a simple python app to make my skill good. so I'm creating an app Guess the number but there is a problem with counter code is below it doesn't update the value

import random

def guess_the_number():
    counter = 0
    rand = random.randint(0, 5)
    a = int(input('enter the number between 0 to 5'))
    if a==rand:
        counter = counter   1
        print('your total points are: '   str(counter))
        print('Do you want to play again PRESS Y for yes and N for No')
        yn = input('enter Y or N')
        if (yn == 'Y' or yn == 'y'):
            guess_the_number()
        elif (yn == 'N' or yn == 'n'):
            print('bye')
            return
    elif a!=rand:
        counter = counter - 1
        print('your total points are: '   str(counter))
        print('Do you want to play again PRESS Y for yes and N for No')
        yn = input('enter Y or N')
        if (yn == 'Y' or yn == 'y'):
            guess_the_number()
        elif (yn == 'N' or yn == 'n'):
            print('bye')
            return

        else:
            print('ah bad words')
    else:
        print('not include')

guess_the_number()

CodePudding user response:

You should define counter outside of the function. Each call to guess_the_number() resets the counter = 0 variable.

Therefore; (remember to include counter to function calls guess_the_number(counter))

import random;
    
counter = 0    
def guess_the_number(counter):
    
    rand = random.randint(0, 5)
    a = int(input('enter the number between 0 to 5: '))
    if a==rand:
        counter = counter   1
        print('your total points are: '   str(counter))
        print('Do you want to play again PRESS Y for yes and N for No: ')
        yn = input('enter Y or N: ')
        if (yn == 'Y' or yn == 'y'):
            guess_the_number(counter)
        elif (yn == 'N' or yn == 'n'):
            print('bye')
            return
    elif a!=rand:
        counter = counter - 1
        print('your total points are: '   str(counter))
        print('Do you want to play again PRESS Y for yes and N for No: ')
        yn = input('enter Y or N: ')
        if (yn == 'Y' or yn == 'y'):
            guess_the_number(counter)
        elif (yn == 'N' or yn == 'n'):
            print('bye')
            return

        else:
            print('ah bad words')
    else:
        print('not include')

guess_the_number(counter)
  • Related