[Tutor] Odd result from function call

Ben Ganzfried ben.ganzfried at gmail.com
Fri Jan 7 18:38:52 CET 2011


When I call one of my functions from the shell (ie compare(10, 5)) it
produces the correct output.  However, when I run the program after calling
the method later in the script, the result is bizarre.  I'm curious why the
wrong result is printed.  Here is an example:

def compare(x,y):
    if x < y:
        print (x, " is less than ", y)
        print("x is ", x, "y is ", y)
    elif x > y:
        print(x, " is greater than ", y)
    else:
        print(x, " and ", y, " are equal.")


x = input("First x is: ")
y = input("First y is: ")
print("x is ", x)
print("y is ", y)
compare(x,y)
a = input("Second x is: ")
b = input("Second y is: ")
print("x is ", a)
print("y is ", b)
compare(a,b)
c = input("Third x is: ")
d = input("Third y is: ")
print("x is ", c)
print("y is ", d)
compare(c,d)

Sample (and incorrect) output w/ 10, 5:

First x is: 10
First y is: 5
x is  10
y is  5
10  is less than  5
x is  10 y is  5
Second x is:

When I do simply compare(10, 5) from the shell, I get the correct output (ie
10 is greater than 5).  I had thought I had narrowed the problem down to the
fact that when I run the script only the first digit is counted-- however,
it seems as if only the first digit is counted (ie anything starting w/ a 9
will be greater than anything starting with a 1 (even if the numbers are 9
and 1324234)), and THEN, the second digit is counted (such that 89 is
correctly identified at 81).

Anyway I'm wondering:
1) Why does the script run correctly when I simply call the function from
the shell but not when I try to call the function from within the script?
2) What is actually going on such that only the first digit is being
evaluated?  That is, the interpreter knows that x is 10 and y is 5-- and
yet, for some reason the 5 is being tested against the 1 and since 5 is
bigger than 1, it concludes that 5 is greater than 10.

thanks!

Ben
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110107/469e94bf/attachment.html>


More information about the Tutor mailing list