Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (16.4k 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 (26.4k 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, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Jul 22, 2019 in SQL by Tech4ever (20.3k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...