Getting error when checking input against values

Viewed 28

I am totally new to Python and I'm trying to write a little program.

It consists of entering a score between 0.0 and 1.0. In the code I have written, it's very basic, I can get it to come up in terminal and it says enter score: but, when I do enter one, I get the error message:'>=' not supported between instances of 'str' and 'float'.

Now I know I need to do something to fix it but i am having a brain freeze. Any ideas?

score = input("Enter score: ")

if score >= 0.9:
    print('Error, try again!')

if score >= 0.85:
    print('Well Done!!')

if score >= 0.7:
    print('Error, try again')

if score >= 0.6:
    print('Error, try again')

if score <= 0.6:
    print("Error, invalid answer")
1 Answers

This statement creates a string called score, not a numeric value (such as a float):

score = input("Enter score: ")

If you want a numeric value, you need something like:

score = float(input("Enter score: "))

Though you probably want to wrap it in an exception handler in case they enter bad data:

score = None
while score is None:
    try:
        score = float(input("Enter score: "))
    except ValueError:
        print("*** That was NOT a valid score, try again.")
        score = None # possibly not needed but just to be safe
now_do_something_with(score)

Additionally, if you only want one of those strings to print, you'll need a slight adjustment, something like:

if score >= 0.9:
    print('Error, try again!')
elif score >= 0.85:
    print('Well Done!!')
elif score >= 0.7:
    print('Error, try again')
elif score >= 0.6:
    print('Error, try again')
else # score <= 0.6:
    print("Error, invalid answer")

By the way, I'm unsure why you think a score at or above 90% (and below 85%) is somehow unobtainable. But I make no value judgement on that assumption, I assume you know what you're doing with the value checks :-)

Related