[Tutor] Bug in python
Alan Gauld
alan.gauld at freenet.co.uk
Mon Feb 20 00:31:06 CET 2006
>>>> 8*a%2
> 0
>>>>
>
> The * is being given equal priority to %.
>
> Why isn't % given higher priority than *?
Because that's the way Guido designed I guess. ;-)
Although why would you expect % to be higher precedence than *?
You can always use parentheses, and if in any doubt should
do so.
> Also, why am I getting a syntax error in the following?
>
> The def in the definition of the second function is being highlighted.
Its always good to send the complete error message.
Python errors are extremely informative whemn you can see them
in their entirety.
>>>> def transfac(v):
> a = v[0]
> b = v[1]
> c = v[2]
> d = v[3]
> m = v[4]
> n = v[5]
> z = v[6]
> k = v[7]
> k = k + 1
> a2 = a%2
> b2 = b%2
> c2 = c%2
> d2 = d%2
> ma = ((d - n * c)/(a*m + b))/2
> na = ((d - m * b)/(a * n +c) )/2
> j = 8 * a2 + 4 * b2 + 2 * c2 + d2
> if j == 0: a,b,c,d,m,n = a/2,b/2,c/2,d/2,m,n
> if j == 1: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1
> if j == 2: a,b,c,d,m,n = a,b/2,c,d/2,m,2*n
> if j == 3: a,b,c,d,m,n = a,(a+b)/2,c,(d-c)/2,2*n+1
It might be better to use an elif chain here. It makes little differemce in
this
case but is more conventional for long chains like this.
if x == 1: f(y)
elif x == 2: g(y)
elif x == 3: ...etc
else: catch errors here
> comment: the def in the following line has been highlighted.
Comments in Python startt with a # character and extend
to the end of line. I appreciate its not part of the code but
I thought I'd point it out :-)
> def gcd(a,b):
> r2 = a
> r3 = b
> flag = 1
> while flag>0:
> if r3 == 0:
> return r2
When you doi a return execution leaves the function so
any lines after return will be ignored. This is like C.
Buit its not your error, Python simply ignores them.
However the error may be above the indicated line but
since your post has lost all indentation its hard to tell.
>
> SyntaxError: invalid syntax
We really need to see the full error plus the actual code
with indentation etc for say 10 lines above and below the
marked line.
Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list