0

I want to do a while loop which ask user to enter value until the value is a float value between 0 and 1

Current code is

while True:
   seuil =input("Please enter a threshold between 0 and 1 (e.g 0.7):")
   try:
       seuil = float(seuil)
   except ValueError as e:
       print("Enter  numeric value")
   if (seuil <0 or seuil >1):
      raise ValueError('Please enter value between 0 and 1') 
   else:
       break



Problems:

if value is not between 0 and 1 I have an error message but the code doesnt ask again to user to enter a value

if value is a string then got following error message

TypeError: '<' not supported between instances of 'str' and 'int'

any help appreciated

akhetos
  • 686
  • 1
  • 10
  • 31

1 Answers1

2

When you catch an exception you should not continue treating the variable as int. Here's the corrected code:

while True:
   seuil = input("Please enter a threshold between 0 and 1 (e.g 0.7):")
   try:
       seuil = float(seuil)
   except ValueError as e:
       print("Enter numeric value")
       continue
   if (seuil < 0 or seuil > 1):
      print('Please enter value between 0 and 1')
   else:
       break
ababak
  • 1,685
  • 1
  • 11
  • 23