Home > Net >  Python input control loop
Python input control loop

Time:11-15

Python beginner here. Practicing user input control. Trying to make user input loop to the beginning if anything but a whole number between 1 and 10 is used. Been trying for hours, tried using Try and Except commands but couldn't do it correctly. What am i doing wrong? Thank you.

while True:
    print("Enter a number between 1 and 10")
    number = int(input())
    if (number > 0) and (number < 10):
        print("Thank you, the end.")
        break
    else number != (> 0 and < 10):
        print("It has to be a whole number between 1 and 10.")
        print("Please try again:")

CodePudding user response:

I have identified some problems.

First, the input statement you are using would just raise an error if a float value is entered, because the int at the start requires all elements of the input to be a number, and . is not a number.

Second; your else statement. else is just left as else:, and takes no arguments or parameters afterwards.

Now, how to check if the number is not whole? Try this:

while True:
    print("Enter a number between 1 and 10")
    number = float(input())
    if (number > 0) and (number < 10) and (round(number)==number):
        print("Thank you, the end.")
        break
    else:
        print("It has to be a whole number between 1 and 10.")
        print("Please try again:")

This accepts a float value, but only accepts it if it is equal to a whole number, hence the (round(number)==number).

Hope that answers your question.

CodePudding user response:

First of all, you can't use a condition in a else statement. Also, you need to use or operator instead of and if one of the conditions is acceptable.
So, your code needs to be like this

while True:
    print("Enter a number between 1 and 10")
    number = int(input())
    if (number > 0) and (number < 10):
        print("Thank you, the end.")
        break
    elif number < 0 or number >10:
        print("It has to be a whole number between 1 and 10.")
        print("Please try again:")
  • Related