0

I am learning python, and foe that I create small programs, and one error I constantly find is not being able to limit the answers to inputs as numbers. When answering a number inside my requirements it works fine, but when nothing or anything besides just numbers is the output for an input it crashes, when I intended it to ask again.

#EXAMPLE

def ask(x):

    return int(float(input(x)))

def main():

    x = ask("NUMBER FROM 0 TO 5: ")

    while x > 5 or x < 0 :

        x = ask("PLEASE INPUT A NUMBER FROM 0 TO 5")

    print(x)

main()

#If the output to the x input is a number between 0 and 5 it works fine, if if a number outside of this limit it works fine and asks again, but when the output is nothing or an str it crashes down, how can I make it work and ask again?

ewokx
  • 2,204
  • 3
  • 14
  • 27
raposo
  • 1

1 Answers1

0

You can use error handling with this keyword try and except.

def ask(x):
  return int(float(input(x)))

def main():
  while 1:
    try:
      x = ask("NUMBER FROM 0 TO 5: ")
      while x > 5 or x < 0 :
        x = ask("PLEASE INPUT A NUMBER FROM 0 TO 5")
      break
    except:
      print("Please input valid input such as integer or float!")

  print(x)

if __name__ == '__main__':
  main()

Note that, while 1: loop will end by break keyword if code in try block worked without error which hit break line. If any error happened, then catch block will be executed which print warning message to user to input valid input.