用户输入后立即打印结果"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

我认为问题是,输入是浮点类型时完成的是字符串。

我也尝试使用value = raw_input(">")而不是float(raw_input(">")运行它,但将结果打印为完成

几个提示:

  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

相关内容

  • 没有找到相关文章