hunt67241
hunt67241

Reputation: 15

What is wrong with my implementation of this sentinel value?

Here is the problem: This program reads a sequence of floating-point values and computes their average. A value of zero is used as the sentinel. Improve the loop so that the loop is only exited if the user enters the letter Q.

Here is my code:

total = 0.0
count = 0

# TODO: Fix this program so that it only stops reading numbers
# when the user enters Q.

value = float(input("Enter a real value or Q to quit: "))
while value != "Q" :
   total = total + value
   count = count + 1
   value = float(input("Enter a real value or Q to quit: "))
  
avg = total / count
print(avg)

Here is my error message: File "/tmp/codecheck.zUZpqo8apX/computesum.py", line 11, in value = float(input("Enter a real value or Q to quit: ")) ValueError: could not convert string to float: 'Q'

Upvotes: 0

Views: 889

Answers (1)

paxdiablo
paxdiablo

Reputation: 881653

Regarding your code:

value = float(input("Enter a real value or Q to quit: "))

If you want to handle a non-float value like Q, you should be treating it as a string at that point, not immediately trying to convert it to a float (which will fail for Q, as you've discoverd).

In other words, something like:

value = input("Enter a real value or Q to quit: ")
while value != "Q" :
    total = total + float(value)
    count = count + 1
    value = input("Enter a real value or Q to quit: ")

That will still cause problems if you enter a value that is neither Q nor a valid float but you could handle this by catching an exception and adjusting behaviour:

value = input("Enter a real value or Q to quit: ")
while value != "Q" :
    try:
        total = total + float(value)
        count = count + 1
    except ValueError:
        print("Not a valid float value, try again.")
    value = input("Enter a real value or Q to quit: ")

If the float() call fails in that case, neither total nor count will be updated and the except block will be executed, letting the user know there was a problem.


The only other thing I'll mention is that you should think about the case where the first thing you do is enter Q. In that case, count will still be set to zero so you probably don't want to divide by it. Instead, you could do something like:

if count == 0:
    print("No values entered therefore no average.")
else:
    avg = total / count
    print(avg)

Upvotes: 1

Related Questions