Python3 Comparison, Script Execution on linux, wrong output

A couple of things.

  • You’re comparing strings rather than integers, and for strings “9” > “10” is True because strings are compared digit by digit (or letter by letter). If you want to compare the actual numbers, you need to parse the strings to integers, e.g. like this: x = int(x), y = int(y), etc.
  • In the second example it should have printed the y value but the situation looked like this: y>=z>=x, but this case wasn’t handled so your code hit the else and it returned z.

Overall, unless what you’re doing is some kind of exercise, I suggest using the built-in max function:

>>> max([1, 2, 3])

If you’re just practicing then still, writing conditionals is not the best way of finding the maximum value of a set of numbers. This problem is typically solved with an algorithm using a for loop, which can handle arbitrarily large collections of numbers with just a single if, e.g.:

In [1]: def my_max(arr):
   ...:     retval = None
   ...:     for x in arr:
   ...:         if retval is None or x > retval:
   ...:             retval = x
   ...:     return retval

In [2]: my_max([1, 2, 3])
Out[2]: 3

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top