2

While entering the negative numbers as below, I want to extract the max value. I expect that value to be -0.123, but the actual value (in Python 3.6.0 shell) is -45.02. Here is my code:

x=input("Enter value of X :")
y=input("Enter value of y :")
Z=input("Enter value of Z :")

print("Display of max value")
print(max(x,y,Z))

input("Please press enter to exit")

And its output:

Enter value of X :-45.02
Enter value of y :-0.123
Enter value of Z :-1.136
Display of max value
-45.02

Can you help me figure out that result?

1
  • 2
    You're comparing strings using lexicographic order, when you want to be comparing numbers instead. Convert your inputs to floats before taking the max. Commented Mar 2, 2017 at 12:55

1 Answer 1

3

As @MarkDickinson says, you have to convert to floats to compare numbers. If you don't the numbers are compared as strings ("10" comes before "7" for example because it compares one character at a time; in this case "1" and "7"). So try this:

try:    
    x=float(input("Enter value of X :"))
    y=float(input("Enter value of y :"))
    Z=float(input("Enter value of Z :"))
except ValueError:
    print('Could not convert to float!')
    exit()  
else:
    print("Display of max value:", max(x,y,Z))

In your case, comparing "-0.123" with "-45.02":

The "-" gets neglected because it is common and it then boils down to finding the max of "0" and "4" which is of course "4". As a result, "-45.02" is the max of the two.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.