使用用户输入和if条件处理异常



Context:我正在学习python,我正在尝试制作一个函数,该函数接受用户输入,然后尝试将该输入转换为浮点值。如果这是不可能的(例如,如果用户键入字符串(,则函数应继续提示用户进行有效输入。该值还应介于最小值和最大值(0到100(之间。我试图这样做,但我不断地遇到错误,比如"<在"int"one_answers"str"的实例之间不支持"这是有道理的,因为我事先并没有真正将用户输入转换为int,所以它不能真正将min和max的int值与用户输入的str类型进行比较。我该怎么解决这个问题?

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()

您的每一种可能的输入模式都无法用标准输入过程进行处理。您必须编写不同的逻辑来格式化每个输入格式。

一般来说,您可以使用下面函数中的方法来实现您想要的。

def floatInput(prompt, min=0, max=100):
while True:
read_in = input(prompt)
try:
# parse a standard float representation
read_in = float(read_in)
except ValueError:
try:
# parse a fractional representation like 1/2 or 3/4
read_in = eval(read_in)
if not isinstance(read_in, float):
print("The value can't be converted to float! Try again")
continue
except:
print("The value can't be converted to float! Try again")
continue
if not min < read_in < max:
print("The value is not in the interval [0,100]! Try again")
continue
return read_in