-1

My very first post, trying to behave according to guidelines, if not pls lmk.

I've written some code for the "Guess a number between 0 and X" game. However, whenever I input type(str) as answer into the input box the game crashes. How do I make sure it does not crash, and instead prompts another input box telling the user to type a number?

Is it an else statement I need to wrap it all together? Snippet of the code block thats bothering me:

while gæt != b:
gæt = input("Venligst indtast et tal mellem 1 og " + str(num) + ": ")
if gæt.isdigit():
    gæt=int(gæt)
if gæt == b:
    print("Korrekt!")
if gæt < b:
    print("For lavt - prøv igen")
if gæt > b: 
    print("For højt - prøv igen")
    count += 1
if gæt.isstr():
    print("Ugyldig indtastning - forsøg igen: ")
    

print("Du brugte", antal, "forsøg på at gætte tallet")

2 Answers2

0

You could use a additional input condition, like

try:
    gæt = int(input("Name a Number"))
except:
    print("Number was no integer")

This way, if the given number is a float it will be converted to an int, and if it's no number at all the error message gets printed.

Wolfmercury
  • 104
  • 1
  • 3
  • 11
0
while gæt != b:
    count = 0
    try:
        gæt = int(input("Venligst indtast et tal mellem 1 og " + str(num) + ": "))
        if gæt == b:
            print("Korrekt!")
        if gæt < b:
            count += 1
            print("For lavt - prøv igen")
        if gæt > b: 
            count += 1
            print("For højt - prøv igen")
    except:
        print("Ugyldig indtastning - forsøg igen: ")

Have you tried something like this? This way youre asking directly for an int value from your input. If that fails, the except block will trigger and send you back to start.

Marius
  • 16
  • 1