-1

Here is my code:

x = 1
while x == 1:
  fav_number = int(input("Guess my favorite number: "))
  print()
  if fav_number == 8:
    print("Gongrats, you guessed it!")
    x = 2
  else:
    print("Nope, try again!")
    print()

In this example, I want it to also say "Nope, try again!" when the user inputs in a float or a string without crashing the program.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Perhaps https://stackoverflow.com/questions/8075877/converting-string-to-int-using-try-except-in-python/8075959 covers what you are asking? – Bill Lynch Jan 12 '22 at 23:06

2 Answers2

1
while True:
    try: #Use the try/except block to raise exception if value is not integer
        fav_number = int(input("Guess my favorite number: "))
        print()
    except ValueError: # if value is anything but integer, exception is raised
        print("Invalid entry. Try again.")
    else:
        if fav_number == 8:
            print("Gongrats, you guessed it!")
            break #code ends when number is guessed
        else:
            print("Nope, try again!")
            

To make it more interesting, you can add a predefined number of attempts. If attempts are exhausted, code stops:

attempts = 5
while attempts > 0:
    attempts -= 1
    try: #Use the try/except block to raise exception if value is not integer
        fav_number = int(input("Guess my favorite number: "))
        print()
    except ValueError: # if value is anything but integer, exception is raised
        print("Invalid entry. Try again.")
    else:
        if attempts > 0:
            if fav_number == 8:
                print("Gongrats, you guessed it!")
                break #code ends when number is guessed
            else:
                print("Nope, try again!")
                print(f"You have {attempts} left")
        else:
            print("You have exhausted your attempts.")
Robin Sage
  • 969
  • 1
  • 8
  • 24
-1

You can, use eval in python for the string would convert int to int and float to float without exception. Check the documentation here: https://docs.python.org/3/library/functions.html#eval

So basically you can change the int to eval:

x = 1
while x == 1:
  fav_number = eval(input("Guess my favorite number: "))
  print()
  if fav_number == 8:
    print("Gongrats, you guessed it!")
    x = 2
  else:
    print("Nope, try again!")
    print()
Honghai Mei
  • 81
  • 1
  • 4