govardhan nalluri
govardhan nalluri

Reputation: 21

python max negative values

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?

Upvotes: 2

Views: 8713

Answers (1)

Ma0
Ma0

Reputation: 15204

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.

Upvotes: 3

Related Questions