用户输入后立即打印结果 "done"

print the result as soon as user input "done"

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

我认为问题在于 done 是字符串,而输入是 float 类型。

我也尝试过 运行 使用 value = raw_input(">") 而不是 float(raw_input(">") 但是打印结果为 done

一些提示:

  1. 而不是立即将用户输入转换为float,为什么不先检查它是否是done

  2. 因为你要永远这样做,直到用户输入 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

编辑:编辑后的代码有两个主要问题。

  1. continue 语句应该在 except 块中。否则,比较总是会被完全跳过。

  2. 当你比较两个不同类型的值时,Python 2,不会抱怨。它只是比较值的类型。因此,在您的情况下,由于您将 largest_so_far 指定为 None,因此将 NoneTypefloat 类型进行比较。

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