jpspork
jpspork

Reputation: 3

Calling an iterated variable outside of a loop in Python

I am making a simple guessing game.

I have a variable inside a function called guess_left which is preset with a value. Inside the while loop, each time the person guesses wrong that value gets decremented by 1 until no more guesses are available and the loop breaks.

How do I get that decremented variable out of the loop and print it when the person wins as a winning message as in print(f"Congrats. You won with {guess_left} tries left.") Or after a certain amount of tries?

Full code:

from random import randint


def generator():
    return randint(1, 1024)


def rand_guess():

    random_number = generator()

    guess_left = 25

    flag = 0

    while guess_left > 0:
        guess = int(input("Please enter your lucky number: "))
        if guess == random_number:
            flag = 1
            break
        elif guess < random_number:
            guess_left -= 1
            print(f"Wrong Guess. Your number should be higher! You have {guess_left} tries left.")
        else:
            guess_left -= 1
            print(f"Wrong Guess. Your number should be lower! You have {guess_left} tries left.")

    if flag == 1:
        return True
    else:
        return False


if __name__ == '__main__':
    if rand_guess() is True:
        print(f"Congrats! You won.")
    else:
        print("Sorry, you lost the game!")

Upvotes: 0

Views: 121

Answers (4)

rewire
rewire

Reputation: 81

Well, defining a global variable is possible, but often considered bad style since they tend to be hard to keep track of the larger your project grows. Scoping is a beautiful thing! Why don't you try doing it like this, returning the number of guesses left:

def rand_guess():
    random_number = generator()

    for i in range(25, 0, -1):
        guess = int(input("Please enter your lucky number: "))
        if guess == random_number:
            return i-1
    return 0

if __name__ == '__main__':
    guesses_left = rand_guess()
    if guesses_left:
        print(f"Congrats! You won with {guesses_left} guesses left.")
    else:
        print("Sorry, you lost the game!")

Upvotes: 0

Mallik Kumar
Mallik Kumar

Reputation: 550

This is an example of returning more than one result from a function.

    if flag == 1:
        return [True, guess_left]
    else:
        return [False, guess_left]

    if __name__ == '__main__':
        result = rand_guess()
        if result[0] is True:
            guess_left = result[1]
            print(f"Congrats. You won with {guess_left} tries left.")
        else:
            print("Sorry, you lost the game!")

Upvotes: 0

Matt
Matt

Reputation: 818

There are many different ways to solve a problem like this, you will have to consider them and decide which is the best for your style of programming.

Making guess_left a global variable: From a purely technical standpoint you could make guess_left a global variable in order to have access to it outside of the rand_guess function,

Returning the amount of guesses left However it is generally best not to create to many global variables as it can lead to difficult to read (and because of that often buggy) code. Have you considered perhaps making the rand_guess returning the amount of guesses left.

Moving the game ending state print messages into the rand_guess function: You could also just move the all the print statements for the end of the game to inside the rand_guess function to where you currently return either true or false.

When considering which solution to choose consider things like: Will I still understand what this code does a month from now? Can other people understand what this code does?

Upvotes: 1

schezfaz
schezfaz

Reputation: 339

You can initialise guess_left as a global variable, and keep making updates to that inside your function.

Like this:

from random import randint
guess_left = 25

def generator():
    return randint(1, 1024)

def rand_guess():
    random_number = generator()
    flag = 0

    global guess_left
    while guess_left > 0:
        guess = int(input("Please enter your lucky number: "))
        if guess == random_number:
            flag = 1
            break
        elif guess < random_number:
            guess_left -= 1
            print(f"Wrong Guess. Your number should be higher! You have {guess_left} tries left.")
        else:
            guess_left -= 1
            print(f"Wrong Guess. Your number should be lower! You have {guess_left} tries left.")

    if flag == 1:
        return True
    else:
        return False

if __name__ == '__main__':
    if rand_guess() is True:
        print(f"Congrats. You won with str(guess_left) tries left.")
    else:
        print("Sorry, you lost the game!")

Upvotes: 0

Related Questions