Javed Ahmed
Javed Ahmed

Reputation: 21

Python code error with sum() function -- syntax works on one platform not another

I'm having an error using Python (inherited code). A Sum() function call that works on one platform is not working on another -- I think it is due to some syntax that is incompatible across platforms. The error I am getting is:

bsrlx1(112)% /usr/bin/python run-print.py init data
  File "run-print.py", line 105
    val = sum(1 if x >= 0.5 else 0 for x in metricC[key]);
                 ^
SyntaxError: invalid syntax

Although this syntax works elsewhere. Anyone know of a syntax change or what the issue might be??

The version of Python I am calling is: Python 2.4.3 (#1, Apr 14 2011, 20:41:59) [GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2

The header file in my program is:

#!/usr/bin/python2.5

So I think I may be using version 2.5

Upvotes: 1

Views: 1238

Answers (2)

John Machin
John Machin

Reputation: 82924

The code is unnecessarily complicated and won't run on Python 2.4, as you have found out. Change it to read:

val = sum(1 for x in metricC[key] if x >= 0.5)

Benefits: (1) will run on Python 2.4 (2) don't have to explain about adding booleans (3) more efficient (don't waste time adding zeroes) (4) no dopey ; at the end.

Upvotes: 2

Brendan Long
Brendan Long

Reputation: 54242

You're using a conditional expression, which was added in Python 2.5.

You're not running /usr/bin/python2.5, you're using /usr/bin/python (which is 2.4). To run it using the interpreter specified in the file, make it executable and then run it directly:

chmod +x run-print.py
./run-print.py

It's unlikely that you have Python 2.5 installed though unless your distro has a special backported package for it.

Upvotes: 8

Related Questions