Python Forum

Full Version: input data validation
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
while True:
     try:
         x = int(input("Please enter a number: "))
         break
     except ValueError or x>10:
         print("Oops!  That was no valid number.  Try again...")
Copied from python.org.

I added in the "or x>10" as I need to keep the number below 10.

The data validation should be before the except ValueError step. How can I add the additional criterion?

Thanks.

P/S

Realised a backdoor to my problem.

while True:
     try:
         x = int(input("Please enter a number: "))
         if x < 10:
            break
     except ValueError or x>10:
         print("Oops!  That was no valid number.  Try again...")
Any better or proper way to solve this? Thanks.
Add if block inside try
while True:
     try:
         x = int(input("Please enter a number: "))
         if 0 < x < 10:
              break
         else:
             print('Please, enter number between 0 and 10')
     except ValueError:
         print("Oops!  That was no valid number.  Try again...")
or inside else block

while True:
     try:
         x = int(input("Please enter a number: "))
     except ValueError:
         print("Oops!  That was no valid number.  Try again...")
     else:
         if 0 < x < 10:
              break
         else:
             print('Please, enter number between 0 and 10')
(Aug-11-2021, 10:04 AM)buran Wrote: [ -> ]Add if block inside try
while True:
     try:
         x = int(input("Please enter a number: "))
         if 0 < x < 10:
              break
         else:
             print('Please, enter number between 0 and 10')
     except ValueError:
         print("Oops!  That was no valid number.  Try again...")
or inside else block

while True:
     try:
         x = int(input("Please enter a number: "))
     except ValueError:
         print("Oops!  That was no valid number.  Try again...")
     else:
         if 0 < x < 10:
              break
         else:
             print('Please, enter number between 0 and 10')
Noted and many thanks!

Cheerio.