0

This code takes the users input and changes it to an integer and then checks if the int is between 0 and 10. I would also like this code to validate the users input against floats and non-numerical strings and loop back if the user enters a bad input. EX: user inputs 3.5 or "ten" and gets an Error and loops again.

 pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))

while pyramid < 0 or pyramid > 10:
    print("That value is not in the correct range. Please try again.")
    pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))
Jenkins
  • 37
  • 11
  • 1
    Possible duplicate of [Python: Analyzing input to see if its an integer, float, or string](https://stackoverflow.com/questions/22214313/python-analyzing-input-to-see-if-its-an-integer-float-or-string) – Sheldore Sep 25 '18 at 01:23
  • More [here](https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number) and [here](https://stackoverflow.com/questions/45650945/how-to-check-if-the-user-input-is-a-string-in-python-3) – Sheldore Sep 25 '18 at 01:25

1 Answers1

0

I'd suggest to try to:

  1. loop indefinitely (while 1)
  2. Cast the input to a float, if this succeeds you can check if it has any decimals (pyramid % 1 != 0) and print the appropriate error in this case.
  3. Cast the input to a integer and break the loop, if it is.
  4. print an error that the input is not an integer
while 1:

    str_in = input("Please enter an integer between 0 and 10 to begin the sequence: ")

    try:
        pyramid = float(str_in)
        if(pyramid % 1 != 0):
            print("That value is a float not an integer. Please try again.")
            continue
    except:
        pass

    try:
        pyramid = int(str_in)
        if pyramid >= 0 and pyramid <= 10:
            break
    except:
        pass

    print("That value is a string not an integer. Please try again.")

print("Your value is {}".format(pyramid))
DerMolly
  • 464
  • 5
  • 17