Home > front end >  Problem with while and if statement which doesn't print answer
Problem with while and if statement which doesn't print answer

Time:01-14

I am making code to Number Guessing Game Objectives. And I have a problem because the score is not printed in my code. Do you have any another clues to improve my code?

Description of the task: Allow the player to submit a guess for a number between 1 and 100. Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer. If they got the answer correct, show the actual answer to the player. Track the number of turns remaining. If they run out of turns, provide feedback to the player. Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode).

import random

number = random.randint(0,100)
print ("Psst, secret number is: ", number )
print("\nHello. It is guesss number game where you have gueass number between 0 and 100.\n\n") 

level = input("Which level do you want to choose 'easy' or 'hard'? ")

number_of_attempts = 0

if level == "easy":
    number_of_attempts = 10
if level == "hard":
    number_of_attempts = 5

while number_of_attempts > 0:
    guess = int(input("Guess a number = "))
    if number_of_attempts == 0: # this line is not printed.
        print (f"You lost, poor sod. Correct number was {number}.")
    elif guess > number:
        print("Number is smaller.")
        number_of_attempts =number_of_attempts - 1
    elif guess < number:
        print("Number is bigger")
        number_of_attempts =number_of_attempts - 1
    elif guess == number: #This line is not printed too.
        print ("You are right")

CodePudding user response:

num = random.randint(1,10)
def num_guess():
    attempts = 3 #create a variable that will count the number of attempts
    while attempts > 0: #while loops continues as long as attempts is greater than 0
        attempts -= 1 #with each iteration, the loop subtracts 1
        try:
            userGuess = int(input("Enter a number between 1 and 10: "))
        except ValueError:
            print("Invalid input. Try again.") # a try/except block raises an exception for any value that's not an integer
            continue
        if attempts > 0: # this condition will allow the player to continue to play as long as the attempts is greater than 0
            if userGuess == num:
                print("You guessed the number!!")
                break
            elif userGuess < num:
                print(f"The number is too low.\nYou have {attempts} attempts left.")
            elif userGuess > num:
                print(f"The number is too high.\nYou have {attempts} attempts left.")
        else:
            print("You did not guess the number.\Thanks for playing!")
num_guess()
  •  Tags:  
  • Related