Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

while loop is not being executed

In this code, the user is to guess a number the computer has chosen randomly between 0 and 100.
The problem is that the while loop doesn’t get executed at all. Everything was working until I put that code block into the while loop to get it repeated until the user guesses the number or runs out of attempts. How do I get the while loop to work? Please I am a beginner in python.

import random
def guessing_game():
    print('''Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.''')

    select_level = input("Choose a difficulty. Type 'easy' or 'hard': easy: ")
    if select_level == "easy":
        attempt_left = 10
        print("You have 10 attempts remaining to guess the number.")
    elif select_level == "hard":
        attempt_left = 5
        print("You have 5 attempts remaining to guess the number.")
    computer_choice = random.randint(0,100)
    #print(f"Pssst, the correct answer is {computer_choice}")

    number_guessed = False
    while number_guessed:
        user_choice = int(input("Please enter a number between 0 and 100: "))
        if computer_choice == user_choice:
            number_guessed = True
            print(f"You got it! The answer was {computer_choice}")
        else:
            attempt_left -= 1
            if user_choice > computer_choice:
                print(f"That is too high!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
            else:
                print(f"That is too low!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
            if attempt_left == 0:
                number_guessed = True
                print("You've run out of guesses, you lose.")
guessing_game()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You define number_guessed as False, so the loop does not execute at all. Try while not number_guessed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading