简体   繁体   中英

while loop is entered even though it is false

import random
print("Welcome to the Number Guessing Game!")
number=random.randint(1,100)
print("I'm thinking of a number between 1 and 100.")
print(number)

def guess(lives):
    guess_number=int(input("Make a guess: "))    
    while guess_number!=number and lives>0: 
        if guess_number>number:
            print("Too High")
          
        elif guess_number<number:
            print("Too Low")
           
        else:
            print(f"You got it! The answer was {number}")
         
        if lives==0:
            print("You are out of moves.YOu loose")
        else:
            print(f"You have {lives-1} attempts remaining to guess the number")
            print("Guess Again:")
            guess(lives-1)

def set_lives():
    level=input("Choose a difficulty.Type 'easy' or 'hard': ")
    if level=="easy":
        lives=10
    else:
        lives=5
    return lives   

guess(set_lives())

After the number of lives ==0 the while statement is false and it must come out of the loop. but in this case the loop is executed even when its false.

I can see that we can solve this problem by make the solution simpler, we need just to change guess function, here you are the code and I'll explain it:

def guess(lives):
while lives > 0:
    guess_number = int(input("Make a guess: "))
    if guess_number == number:
        print(f"You got it! The answer was {number}")
        return

    if guess_number > number:
        print("Too High")

    elif guess_number < number:
        print("Too Low")
    lives -= 1
    print(f"You have {lives} attempts remaining to guess the number")

print("You are out of moves. You loose")

now what this code says is:

1- we need to loop at least the {number of alives} times

2- if what the user guess {guess_number} is == to the number, then print "You got it. The answer was.., " then return statement will get out of the function, so we have just one success story and this is it/

3- the other 2 if conditions will still loop becouse the user didn't get the the requird guess.

4- if the loop has been finished and we still in the functions, that means that the user finished his {lives} with no correct answer, so it will print "You are out of moves. You loose"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM