因此,我需要一个真正有效的代码,该代码将接受用户的0到1之间的任何数字,并不断提示他们重试,直到他们的输入满足此条件。
到目前为止,这是我得到的:
def user_input():
while True:
global initial_input
initial_input = input("Please enter a number between 1 and 0")
if initial_input.isnumeric() and (0 <= float(initial_input) <= 1):
initial_input = float(initial_input)
return(initial_input)
print("Please try again, it must be a number between 0 and 1")
user_input()
这有效,但仅当数字实际为1或0时。如果您在两者之间输入小数(例如0.6),则会崩溃
最佳答案
仅当输入是介于0和1之间的数字时,才应使用try/except返回输入,将错误的输入捕获为ValueError:
def user_input():
while True:
try:
# cast to float
initial_input = float(input("Please enter a number between 1 and 0")) # check it is in the correct range and is so return
if 0 <= initial_input <= 1:
return (initial_input)
# else tell user they are not in the correct range
print("Please try again, it must be a number between 0 and 1")
except ValueError:
# got something that could not be cast to a float
print("Input must be numeric.")
另外,如果您使用自己的代码获取
"Unresolved attribute reference 'is numeric' for class 'float'".
,则说明您使用的是python2而不是python3,因为您只在等数字检查后才进行转换,因此意味着输入已被评估。如果是这种情况,请使用raw_input代替输入。
关于python-3.x - 仅接受介于0和1之间的 float -python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812703/