问题
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
I think problem with this is that done is string while input is float type.
I have also tried it running using value = raw_input(">") instead of float(raw_input(">") but that prints the result as done
回答1:
Few hints:
Instead of converting the user input to
floatimmediately, why don't you check if it isdonefirst?Since you are going to do this forever, until user enters
doneor there is a value error, use an infinite loop and atry..except, like this
# 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
Edit: The edited code has two main problems.
The
continuestatement should be within theexceptblock. Otherwise, the comparisons are always skipped at all.When you compare two values of different types, Python 2, doesn't complain about it. It simply, compares the type of the values. So, in your case, since you assigned
largest_so_farasNone, theNoneTypeis compared with thefloattype.>>> type(None) <type 'NoneType'> >>> None > 3.14 False >>> None < 3.14 TrueSince, the
floattype is always lesser thanNonetype, the conditionif value > largest_so_far: largest_so_far = valueis never met. So you will be getting
None. Instead, usefloat("- inf")like I have shown in my answer.
回答2:
I would do this as follows:
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
来源:https://stackoverflow.com/questions/30098514/print-the-result-as-soon-as-user-input-done