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: "))
2

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.