mercredi 10 octobre 2018

Why does the program not break out of the while loop when I set the state to false?

Im new to python and I was just creating a simple a simple random number guessing game.

Simply, to break out of the while loop the user has to either guess the correct number or reach the maximum attempts made i.e. 3

However the code doesn't seem to break out the loop when I call the function for checking the amount of attempts made. Is there a way to break out of the while loop from calling a function?

...

import random 
print("*** RANDOM NUMBER GUESSING ***\n")
print("1. Guess the number between x and y.")
print("2. You have 3 attempts to guess the random number.\n")

x = input("The random number is generated between x: ")
x = int(x)
y = input ("and y: ")
y = int(y)

#Random number generated
randNum = random.randint(x,y)

userAttempts = 0
gameState = True

#Function checking the attempts made
#If max attempts reached then gameState = False to break out of the while loop
def maxAttempts(attempts, state):
    if attempts == 3:
        print("Max attempts reached!")
        state = False
        return state


while gameState:
    userNum = input("Guess the random: ")
    userNum = int(userNum)

    if userNum == randNum:
        print("Well done you guessed the correct number !!")
        gameState = False;
    elif userNum > randNum:
        print("Number is too high")
        userAttempts += 1
        maxAttempts(userAttempts, gameState)

        #debugging
        print("Attempts: ", userAttempts)
        print("Game state: ", gameState)
    else:
        print("Number is too low")
        userAttempts += 1
        maxAttempts(userAttempts, gameState)

        #debugging
        print("Attempts: ", userAttempts)
        print("Game state: ", gameState)

print("\nGame finished.\n")




Aucun commentaire:

Enregistrer un commentaire