-2

How could I change the print statement to another input statement that says: "Try again. Your number must be between 1 and 50: " if num does not equal 1-50 or is not an integer?

while True:
    num = input('Enter a whole number between 1 and 50: ')
    try:
        num = int(num)
        if num<1 or num>50:
            print("Your number must be between 1 and 50, try again.")
            continue
        break
    except ValueError:
        print("You did not enter a number, try again.")
Biffen
  • 6,249
  • 6
  • 28
  • 36
  • Possible duplicate of https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – tripleee Mar 23 '22 at 07:39

1 Answers1

1

Simply change the message after you used it once:

message = 'Enter a whole number between 1 and 50: '
while True:
   
    num = input( message )
    try:
        # change the message
        message = "Your number must be between 1 and 50, try again: "

        num = int(num)
        if 1 <= num <= 50:
            break

    except ValueError:
        pass
 

Test:

Enter a whole number between 1 and 50: dont want to
Your number must be between 1 and 50, try again: 99
Your number must be between 1 and 50, try again: -2
Your number must be between 1 and 50, try again: 1 
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • @JasonWada This will loop until you input a valid value. You do not get a special error message if you input "Hugo" instead of a number, instead the prompt will repeat. – Patrick Artner Feb 26 '22 at 18:46