[Tutor] Odd result from function call

Alex Hall mehgcap at gmail.com
Fri Jan 7 22:16:15 CET 2011


Cast to an int:
x=int(x)
See if that helps.

On 1/7/11, Ben Ganzfried <ben.ganzfried at gmail.com> wrote:
> 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
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


More information about the Tutor mailing list