Context: I'm learning python and I'm trying to make a function that takes a user input and then tries to convert this input into a float. If this is not possible (for example, if the user types a string), the function should keep prompting the user for valid input. This value should also be between min and max values (0 and 100). I was trying to do this, but I keep getting errors such as "< not supported between instances of 'int' and 'str'" which makes sense since I'm not really converting the user input as an int beforehand so it can't really compare the int value from min and max with the str type of the user input. How could I fix this?
import math
def floatInput(prompt, min=0, max=100):
is_float = False
while not is_float:
try:
if min < prompt < max:
res = float(input(prompt))
return res
else:
if prompt > max or prompt < min:
print("The value is not in the interval [0,100]! Try again")
res = float(input(prompt))
except ValueError:
print("The value can't be converted to float! Try again")
res = float(input(prompt))
if type(res) == float:
is_float = True
return res
retornar res
def main():
print("a) Try entering invalid values such as 1/2 or 3,1416.")
v = floatInput("Value? ")
print("v:", v)
print("b) Try entering invalid values such as 15%, 110 or -1.")
h = floatInput("Humidity (%)? ", 0, 100)
print("h:", h)
print("c) Try entering invalid values such as 23C or -274.")
t = floatInput("Temperature (Celsius)? ", min=-273.15)
print("t:", t)
return
if __name__ == "__main__":
main()