largest_so_far = None
smalest_so_far = None
value = float(raw_input(">"))
while value != ValueError:
value = float(raw_input(">"))
if value > largest_so_far:
largest_so_far = value
elif value == "done":
break
print largest_so_far
我认为问题是,输入是浮点类型时完成的是字符串。
我也尝试使用value = raw_input(">")
而不是float(raw_input(">")
运行它,但将结果打印为完成
几个提示:
-
而不是立即将用户输入转换为
float
,为什么不首先检查它是done
? -
由于您将永远执行此操作,直到用户输入
done
或有一个值错误,请使用无限循环和try..except
,例如此
# Start with, the negative infinity (the smallest number)
largest_so_far = float("-inf")
# the positive infinity (the biggest number)
smallest_so_far = float("+inf")
# Tell users how they can quit the program
print "Type done to quit the program"
# Infinite loop
while True:
# Read data from the user
value = raw_input(">")
# Check if it is `done` and break out if it actually is
if value == "done":
break
# Try to convert the user entered value to float
try:
value = float(value)
except ValueError:
# If we got `ValueError` print error message and skip to the beginning
print "Invalid value"
continue
if value > largest_so_far:
largest_so_far = value
if value < smallest_so_far:
smallest_so_far = value
print largest_so_far
print smallest_so_far
编辑:编辑的代码有两个主要问题。
continue
语句应在except
块内。否则,比较总是会跳过。当您比较不同类型的两个值时,Python 2时不会抱怨它。简单地,比较值的类型。因此,在您的情况下,由于您将
largest_so_far
分配为None
,因此将NoneType
与float
类型进行了比较。>>> type(None) <type 'NoneType'> >>> None > 3.14 False >>> None < 3.14 True
由于
float
类型总是比None
类型要小,条件if value > largest_so_far: largest_so_far = value
永远不会满足。因此,您将获得
None
。而是像我在答案中显示的那样使用float("- inf")
。
我会如下这样做:
largest_so_far = smallest_so_far = None
while True:
value = raw_input(">")
# first deal with 'done'
if value.lower() == 'done':
break
# then convert to float
try:
value = float(value)
except ValueError:
continue # or break, if you don't want to give them another try
# finally, do comparisons
if largest_so_far is None or value > largest_so_far:
largest_so_far = value
if smallest_so_far is None or value < smallest_so_far:
smallest_so_far = value