简体   繁体   中英

can't figure out why the program stops running (try/exception in a while loop)

for some reason, the code stops if you add a string i don't see or understand what's going wrong in the program

import random
import math

def start_game():
    pass

    guesses = 1 

    random_number = (random.randint(1,10)) #limiting the number only from one to ten 



    try:
        number = int(input("Welcome new player! Pick a number between 1 to 10:   "))
    except ValueError:
        print("Please only use numbers between 1-10")
    else:
        
     
        while number != random_number :

            try:

                if random_number > number:
                    print("A little too low")
                    number = int(input("Pick a number between 1 to 10:   "))
                    guesses = guesses+ 1
                            
                            
                elif random_number < number:
                    print("A little too high")
                    number = int(input("Pick a number between 1 to 10:   "))
                    guesses = guesses+ 1
                        
            except ValueError:
                print("Sorry please only use numbers between 1 - 10")
            else:
                pass
                number == random_number
                guesses = guesses+ 1 
                
                            
        print("Good job! you guessed the right number")
        print ("The amount of guesses were {}".format(guesses))


start_game()

First problem you have here is that you are not even using the math module you can delete it.

Second problem is your second except clause is ending the program. It prints out this message print("Sorry please only use numbers between 1 - 10") and there is no input to put in to continue the game.

Third problem is even if you don't input any strings and play the game correctly the else statement at the end of each while iteration is making guesses to add another 1 on top of the 1 that you are already adding in the if and elif clauses.

The forth problem is not a problem at first sight but it is important for you to understand what the code is doing. The code here looks really complex for no reason. I've applied the same game in a code below. You can simplify everything like the below code i've suggested for you.

import random

def validate_input_between(sentence: str, n: int) -> int:
    while True:
        try:
            number = int(input(f"{sentence} {n}: "))
            if 1 <= number <= n:
                return number
            raise ValueError()
        except ValueError:
            print(f"Input must be an integer between 1 and {n}.")


def start_game(n: int) -> None:
    guesses = 1
    random_number = random.randint(1, n)
    num = validate_input_between("Enter a number between 1 and", n)
    while True:
        if random_number > num:
           print("Your guess was too low.")
           num = validate_input_between("Guess another number between 1 and", n)
           guesses += 1
        elif random_number < num:
            print("Your guess was too high.")
            num = validate_input_between("Guess another number between 1 and", n)
            guesses += 1
        else:
            print("Good job! you guessed the right number!")
            print(f"The amount of guesses were {guesses}.")
            break

start_game(5)

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