0 votes
1 view
in Python by (12.5k points)

I made a straightforward number guessing game, yet every time I don't type in a number the framework crashes. Would someone be able to kindly assist!

import random

randNum = random.randint(1, 100)

guesses = 0

for i in range(1, 8):

    guesses = guesses + 1

    print("hi human guess a number 1-100! \n")

    guess = input()

    guess = int(guess)

    if guess > randNum:

        print("your guess is too high")

    elif guess < randNum:

        print("your guess is too low")

    elif guess == randNum:

        print("duuude you're a genius \n")

        print("you needed " + str(guesses) + " guesses")

1 Answer

0 votes
by (26k points)

The framework crashes since Python can't typecast the characters to numbers when you typecast them. You ought to unequivocally compose a condition to check for characters for example in the event that the input string is anything aside from numbers, your code should print something like "Attempt Again" or "Invalid Input".

import random

randNum = random.randint(1, 100)

guesses = 0

for i in range(1, 8):

    guesses = guesses + 1

    print("hi human guess a number 1-100! \n")

    guess = input()

    if guess.isdigit():

        if int(guess) > randNum:

            print("your guess is too high \n")

        elif int(guess) < randNum:

            print("your guess is too low \n")

        elif int(guess) == randNum:

            print("duuude you're a genius \n")

            print("you needed " + str(guesses) + " guesses")

    else:

        print("Invalid Input! Try a number. \n")

Try to use the above code. 

Are you interested to learn the concepts of Python? Join the python training course fast!

Related questions

0 votes
1 answer
asked Feb 8 in Python by ashely (50.5k points)
0 votes
1 answer
asked Jul 22, 2019 in SQL by Tech4ever (20.3k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...