f



Python interpreter error: unsupported operand type(s) for -: 'tuple' and 'int'

In my Python code fragment, I want to write a code fragment such that
the minimum element of a tuple is subtracted from all the elements of a
given
tuple.

When I execute the following python script I get the following
interpreter
error.


C:\>python test.py
200 ddf DNEWS Version  5.7b1,, S0, posting OK
Reading messages from newsgroup comp.lang.c ...
Newsgroup responded 211 3377 67734 71134 comp.lang.c selected
Read 3377 messages from the newsgroup
Converting date to seconds since epoch ..
Traceback (most recent call last):
  File "test.py", line 111, in ?
    main()
  File "test.py", line 101, in main
    processNewsgroup(s, 'comp.lang.c');
  File "test.py", line 80, in processNewsgroup
    relativetime = thissecond - minsec
TypeError: unsupported operand type(s) for -: 'tuple' and 'int'

How would I fix this type error ?

<--->
from nntplib import NNTP

import sys
import time
import string

senders = ' ';
dates   = ' ';
seconds = ' ';
rangetime = ' ';

## --------------------------------------------
## Parse a given date to be converted to
## milliseconds from epoch time.
## Input -  datestr - String in date format
##   Jan 13 2004, 13:23:34 +0800
## Output :- number of milliseconds since epoch
##
## --------------------------------------------
def parseDate(datestr):
    timezone = '';
    index = string.find(datestr, '+');
    if (index != -1):  #  Date not found
        timezone = datestr[index:];
    if ( len(timezone)  == 0):
        negindex = string.find(datestr, '-');
        if (negindex != -1):
            timezone = datestr[negindex:];
    if ( len(timezone) == 0):
        timezone = ' %Z';

    datefound = 0;
    try:
        mydate = time.strptime(datestr, '%a, %d %b %Y %H:%M:%S ' +
timezone)
    except:
        try:
            mydate = time.strptime(datestr, '%d %b %Y %H:%M:%S ' +
timezone)
        except:
            print "Unexpected error:", sys.exc_info()[0]

    # Get number of milliseconds since epoch
    return int( time.mktime(mydate) );


## ------------------------------------------- ----
# Function to deal with a given newsgroups
# newsgroup - comp.lang.c etc.
# s  -  NNTP Host instance ( an instance from NNTP )
## ----------------------------------------------------
def processNewsgroup(s, newsgroup):
    global senders;
    global dates;
    global seconds;
    global rangetime;

    print 'Reading messages from newsgroup %s ...' % (newsgroup)

    # Newsgroup - comp.lang.c for now
    resp, count, first, last, name = s.group(newsgroup);

    print 'Newsgroup responded %s' % resp;

    # XHDR command as per the NNTP RFC specification
    resp, senders = s.xhdr('from', first + '-' + last)

    # XHDR command as per the NNTP RFC specification
    resp, dates = s.xhdr('date', first + '-' + last)

    print 'Read %s messages from the newsgroup ' % (count)
    print 'Converting date to seconds since epoch ..'

    # Convert the date format to the seconds since epoch
    for i in xrange( len(dates) ):
        thissecond = parseDate(dates[i][1]);
        seconds = (seconds, thissecond );

    minsec = int( min(seconds) );
    for thissecond in seconds:
        # in xrange( len(seconds) ):
        relativetime = thissecond - minsec
        #TODO: INTERPRETER ERRORS ABOVE.

        rangetime = (rangetime, relativetime );

    rangetime
    print 'Converted date to seconds since epoch ..'





## -----------------------------------------------
# Entry Point to the whole program
## -----------------------------------------------
def main():
    # Read the message from the given news server.
    s = NNTP('news.mynewserver');

    # Print the welcome message
    # More of a test than anything else
    print s.getwelcome()

    processNewsgroup(s, 'comp.lang.c');

    # Quit from the NNTPLib after using the same
    s.quit()



## --------------------------------
# Entry-point to the whole program
## --------------------------------
main()
<--->

0
3/30/2005 1:40:59 AM
comp.lang.python 77058 articles. 6 followers. Post Follow

3 Replies
1004 Views

Similar Articles

[PageSpeed] 39

To quote a much smaller trimmed-down example, here is how it looks
like:

<-->
import sys

## --------------------------------------------
## --------------------------------------------
def GenerateList():
    array = ' '
    for i in xrange(10):
        array = (array, i)
    return array


## -----------------------------------------------
# Entry Point to the whole program
## -----------------------------------------------
def main():
    mylist = GenerateList()
    minnumber = min(mylist)
    for num in mylist:
        print num - minnumber
        ## TODO: Interpreter errors above.

## --------------------------------
# Entry-point to the whole program
## --------------------------------
main()

<-- >

0
3/30/2005 1:48:15 AM
Rakesh wrote:

 > To quote a much smaller trimmed-down example, here is how it looks
 > like:
 > ## -----------------------------------------------
 > # Entry Point to the whole program
 > ## -----------------------------------------------
 > def main():
 >     mylist = GenerateList()
 >     minnumber = min(mylist)
 >     for num in mylist:
 >         print num - minnumber
 >         ## TODO: Interpreter errors above.


Try printing mylist. Then you'll know why - operand doesn't work.
You're creating a nested tuple.

I'd recommend changing the original script to something like::

   seconds = []
   [snip]

       # Convert the date format to the seconds since epoch
       for i in xrange( len(dates) ):
           thissecond = parseDate(dates[i][1])
           seconds.append(thissecond)

or if you want to stick with tuple::

   seconds = ()
   [snip]

       # Convert the date format to the seconds since epoch
       for i in xrange( len(dates) ):
           thissecond = parseDate(dates[i][1])
           seconds += (thissecond, )

-- george
0
ml1351 (37)
3/30/2005 4:09:58 AM
George Yoshida wrote:
> Rakesh wrote:
>
>  > To quote a much smaller trimmed-down example, here is how it looks
>  > like:
>  > ## -----------------------------------------------
>  > # Entry Point to the whole program
>  > ## -----------------------------------------------
>  > def main():
>  >     mylist = GenerateList()
>  >     minnumber = min(mylist)
>  >     for num in mylist:
>  >         print num - minnumber
>  >         ## TODO: Interpreter errors above.
>
>
> Try printing mylist. Then you'll know why - operand doesn't work.
> You're creating a nested tuple.
>
> I'd recommend changing the original script to something like::
>
>    seconds = []
>    [snip]
>
>        # Convert the date format to the seconds since epoch
>        for i in xrange( len(dates) ):
>            thissecond = parseDate(dates[i][1])
>            seconds.append(thissecond)
>
> or if you want to stick with tuple::
>
>    seconds = ()
>    [snip]
>
>        # Convert the date format to the seconds since epoch
>        for i in xrange( len(dates) ):
>            thissecond = parseDate(dates[i][1])
>            seconds += (thissecond, )
>
> -- george

   Thanks. That fixed the problem.

## --------------------------------------------
## Generate a list
## --------------------------------------------
def GenerateList():
    array = []
    for i in xrange(10):
        array.append(i)
    return array


## -----------------------------------------------
# Entry Point to the whole program
## -----------------------------------------------
def main():
    mylist = GenerateList()
    minnumber = min(mylist)
    for num in mylist:
        print num - minnumber

## --------------------------------
# Entry-point to the whole program
## --------------------------------
main()

This is how my revised code looks like

0
3/30/2005 2:36:12 PM
Reply:

Similar Artilces:

Python interpreter error: unsupported operand type(s) for |:
hey folks i get this error: Python interpreter error: unsupported operand type(s) for |: when i run this line of code: for incident in bs('tr', {'bgcolor' : '#eeeeee'} | {'bgcolor' : 'white'} ): any idea what i'm doing wrong here? thanks yaffa you cannot use | with two dict (dict has no .__or__ method) what are you trying to do? Szabolcs Nagy a �crit : > you cannot use | with two dict (dict has no .__or__ method) > > what are you trying to do? > read the post: "need help with python syntax"... (posted one hour ...

unsupported operand type(s) python v2.7
>>> def n(): 34 * 2 >>> def g(): 4 + 2 >>> def ng(): return n() + g() >>> ng() Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> ng() File "<pyshell#13>", line 2, in ng return n() + g() TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType' On 20.10.2015 10:44, ngangsia akumbo wrote: >>>> def n(): > 34 * 2 > > >>>> def g(): > 4 + 2 > Your n and g functions do not have an ...

python is a python
python is a python ...

python and s-lang
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I was just wondering if anyone has looked into using Python instead of, or in additon to, s-lang modules. Does slrn support the use of other interpreted languages ? (I hate the term scripted languages; very innacurate of modern interpreted languages). Given the fact that Python is as flexible and powerful as it is, and given the fact that it was designed to interface with such languages as C, it seemed natural that someone must have done this if it is possible. I would like to hear from those individuals, or anyone with programming experience (a...

Boost + Python C/API: Mixing python return types with boost return types
Hello, I'm new to Boost & Python and I'm diving straight in by trying to write an extension module to a third party library. Foolishness probably, but I don't have much choice! My question is how can I write a C++ method that will either return a boost wrapped C++ class or a Python object type depending on some internal value? So I want to do something like: PyObject* Variant::getValue() { switch (type) { case INT: return Py_BuildValue("i", union.int); break; case SOMECLASS: ?????? } } But I can...

return tuple from C to python (extending python)
Hi all, I want to make python call some C functions, process them and return them. Ok, I got all the wrapper functions and everything setup right. Here is my problem. What I need to do is to return a tuple from C to python. To go about doing this, I first create a tuple object in C doing the following: PyObject* toRet; toRet = PyTuple_New(num_addr); then, in a for loop, i assign values to the tuple as follows: for ( i = 0; i < num_addr; i++ ) { printf("%d\n", dat[i]); PyTuple_SET_ITEM(toRet, i, (PyObject*)dat[i] ); } (dat is declared as follows: unsigned int* dat; ) then, i say return toRet at the end of my C function. when I try to print the tuple in python, it says the memory address 0x.... could not be written, and I can see a part of the tuple printout, which is as follows: ( <nil>, then i get my error. can someone please help me with this? thanks a lot! -- Kiran Kiran wrote: > Hi all, I want to make python call some C functions, process them and > return them. > > Ok, I got all the wrapper functions and everything setup right. Here > is my problem. What I need to do is to return a tuple from C to > python. > > To go about doing this, I first create a tuple object in C doing the > following: > > PyObject* toRet; > toRet = PyTuple_New(num_addr); > > then, in a for loop, i assign values to the tuple as follows: > > for ( i = 0; i < num_addr; i++ ) > { > ...

Python mascot? How about a Pythoneer?
I've been thinking that a good Python mascot might help in raising public awareness of Python. The problem with a snake as a mascot is that it is not anthropomorphic enough. An effective mascot has to have something approximating two arms, two legs, and a head, so that he can be put into various interesting situations and adventures. (At the very least, he has to be able to work a keyboard and a mouse!) Good examples can be found in some of the imaginative things that have been done with Linux's Tux. So a snake is out. So are Terry Gilliam's wonderful cartoons for the Flyin...

Python to Python communication
Hello, I have a group of Python programms which I want to teach to "talk to each other". All run on Windows, on the same computer or in the same intranet. Security of communication is not an issue (encryption on lower level protocols / intra computer communication). Partially these programs are using wxPython. It is important that the communcation is "only an added feature", I am not willing to spend big memory / computing ressources on it. So I googled and came up with at least the following opportunities: XMLRPC - quite "simple" to implement within python, contained in my favourite web framework Quixote / medusa SOAP - around the same amount of work as XMLRPC ----> these two are fully buzzword compatible to enterprise communication needs. But are they really lightwight and needed? Banana - within the twisted framework. Is described as high performance with very litte ressources. From my scanning of twisted it is meanwhile possible to integrate it within wxPython and you only need to sell the soul of your firstborn for it; but I got the impression twisted rather needs a total commitment than a "I just need some banana, man" pyro - Python Remote Objects. Irmen de Jong has a "get Firefox" icon on it's page and he plays with the name "pyro", which makes a good impression. It looks rather "ripe", but: he is talking about "pyro 4.0" which will be incompatible with pyro ...

Invoking Python from Python
Hi all, I have a need to create a Python script on the fly from another Python program and then execute the script so created. Do I need to invoke Python through os.spawnl or is there a better way? Thanks, -- John Am Tue, 08 Nov 2005 08:10:25 -0800 schrieb John Henry: > Hi all, > > I have a need to create a Python script on the fly from another Python > program and then execute the script so created. Do I need to invoke > Python through os.spawnl or is there a better way? Hi, creating source code with a script, is no good solution. Once I had to maintain lisp code which stored its data in lisp code, too (incl. conditions and loops). It was a nightmare. Please explain what you want to do, and we will find a better solution. HTH, Thomas -- Thomas G�ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann@thomas-guettler.de In article <pan.2005.11.08.16.21.11.472836@thomas-guettler.de>, Thomas Guettler <niemand.leermann@thomas-guettler.de> wrote: . . . >creating source code with a script, is no good solution. > >Once I had to maintain lisp code which stored its data in lisp code, too >(incl. conditions and loops). It was a nightmare. > >Please explain what you want to do, and we will find a better solution. . . . Yes and no. There are times when it's justified. I ENTIRELY agree, though, that many people who *think* that's what they...

Embedding Python in Python
Hi, I've been programming in Python for a couple of weeks now and am quite impressed with the language - it was very easy to learn (it actually reminds me a lot of programming in BASIC many many years ago - it's very fast to hack together a couple lines of code in interactive mode). I'm throwing together a simple little game (sort of a MUD-type thing) as my first 'big' project, and I thought it would be cool to be able to script the game in Python. Basically, I want to be able to type scripts in from within the game and attach them to objects, monsters, rooms, whatever. N...

python ScriptControl error in Excel while running fine in python
I am trying to use ScriptControl under Excel (Windows XP) with the code: Global sc As New MSScriptControl.ScriptControl Public Function os_getcwd() sc.Language = "python" sc.ExecuteStatement ("import os") os_getcwd = sc.Eval("os.getcwd()") End Function When setting the language to python I have the error "A script engine for the specified language..." On the other side, under python, the translated code: import win32com.client sc=win32com.client.Dispatch("ScriptControl") sc.Language = "python" sc.ExecuteStatement (&q...

Python interpreter in Basic or a Python-2-Basic translator.
I'm looking for a Python interpreter written in BASIC, preferably Visual Basic, and one written in VBA would be best of all. An alternative would be a Python-2-Basic compiler. Unfortunately I have to develop some special purpose code in an organization where my only development environment is Microsoft Office Visual Basic for Applications. The security 'droids have decided that since the MS Office Suite is a "standard" application then software written in MS Office VBA must be "safe." Any other development environments (such as Java, Perl, Cygwin) are "unsa...

Fatal Python error with Py_InitModule (Python 2.3)
I'm using Python embedded in my app, and I've run into problems creating my own modules. I'm using Python version 2.3 compiled with MSVC .NET (not 2003). When I call Py_InitModule I get the message: "Fatal Python error: Interpreter not initialized (version mismatch?)" However, Python does seem to be initialized. Py_IsInitialized() returns 1, and I can PyImport_Import() and I can run scripts successfully from my program. I'm not sure what I could be doing wrong, all the information I've found online indicates that the above message comes from incompatible v...

Python/C API, Numeric Python, Type Conversion
Hi, I am posting here to seek for help on type conversion between Python (Numeric Python) and C. Attachment A is a math function written in C, which is called by a Python program. I had studied SWIG and Python/C API a bit. I was able to pass numeric array (Numeric Python) into the C function and access/change these arrays. Problem I am having is that I couldn't quite get the array converted back to some PyObject or something that Python Interpreter can understand. So, alternatively I passed an empty numeric array as well as other arguments, and had return value(result) stored in t...

..\..\Python-2.5.2\Include\pyport.h(117) : fatal error C1189: #error : "Python needs a typedef for Py_ssize_t in pyport.h."
When I try and compile using VS2003 for Release. Compiles fine for Debug. In a hurry (should be gardening). Any solution? TIA Bill ...

static program including python interpreter + dynamic python extensions
Dear Newsgroup, I have a problem that is somewhat related to Alexandre Gillet's ones: "build a static python executable". I would like to make a C[++] program scriptable. Therefor, I have included a python interpreter into the program. Additionally I have wraped all the program's interfaces that I need, using SWIG. Finally, I have created a shared library, which includes this interface and all functions that are to be available from within python scripts. And it works: one can write a script, which can access the program's routines and data, the main program correctly l...

What platforms have Python Virtual Machines and what version(s) of Python do they support?
What platforms have Python Virtual Machines and what version(s) of Python do they support? In particular: Palm OS PocketPC What version of Python does Jython support? Does any machine running a JVM support Jython? Does it depend on the JVM version and if it's J2ME? Thank you for your time! -- Regards, Casey "Casey Hawthorne" <caseyhHAMMER_TIME@istar.ca> wrote in message news:361ab1trhpgra9hig255r7arv68gfpe7lj@4ax.com... > What platforms have Python Virtual Machines and what version(s) of > Python do they support? > In particular: > Palm OS > PocketPC T...

RE: Bigloo vs. Python, features (was Re: Typed Python?
Peter Maas wrote: > Jacek Generowicz schrieb: > > Python provides no built-in support for pattern matching, therefore > > your average happy Pythoneer will not be familiar with pattern > > matching, the point of pattern matching, the benefits of pattern > > matching, or the situations in which pattern matching is a big win. >=20 > If I understand correctly you mean that it makes a difference > whether it reads >=20 > s ~ /a.*b/ >=20 > or >=20 > re.match('/a.*b/', s) >=20 > ? >=20 > For me this is only a lexical issue...

Fatal Python error using ctypes & python exceptions
Hi Everyone, I've created a 'C' dll that is accessed via ctypes library containing a bunch of functions. I've successfully been able to use the functions. However, I would like to throw python exceptions from some of them. I throw them using: ::PyErr_SetString(::PyExc_RuntimeError, theErrorString); I crash the console when this function is invoked in the 'C' domain. I get an error stating: Fatal Python error: PyThreadState_Get: no current thread when the calling code in python is: try: cdll.MyDll.ThrowingFunction() except: print "An error has occurred&...

Type error when using SQLAlchemy and Python
HI, I posted this to sqlalchemy but didnt get a response, so I was wondering if anyone on python-list could help me. I m currently trying to build an api for a database and I really like the way that Djangos manager ( Class_name.objects ) is set up. This seems very intuitive for me. After reading through the some of the django source and getting slightly confused I ve implemented a basic version for one of my tables. The problem is I get an exception, when I m not expecting one. registry.py --> contains table definitions etc. Manager.py from Registry import * class Manager(object): ...

Error in PyDev but not in the standard python interpreter
Hi, this is probably not the best place for this topic but I know this forum is widely read. I take this opportunity and apology at the same time. If I run this in my python3 interpreter everything works fine: mowglie@flappi ~ $ python3 Python 3.3.2+ (default, Feb 28 2014, 00:52:16) [GCC 4.8.1] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from netCDF4 import num2date >>> from datetime import datetime >>> d1 = num2date(0, 'days since 1000-01-01', 'standard...

Pausing for Python Interpreter error messages...
I've written a few classes that I have been testing in IDLE. However, every time I make a change to the classes based on the testing I have to walk through all he steps of preparing the classes for testing again. So I wrote a script that does all the set-up work for me. The only problem is when I run this script using the Python interpreter I can't get the command prompt to stay up long enough for me to read the message. How do I get the command prompt to stay up? Is there a way to run my script and view the error message in IDLE? Thanks for the help. Scott Huey P.S. - I'm usi...

%%(%s)s mean in python
def fetchRecord(db, form): try: key = form['key'].value record = db[key] fields = record.__dict__ fields['key'] = key except: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing or invalid key!' return fields def updateRecord(db, form): if not 'key' in form: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing key input!' else: key = form['key'].value if key in db: record = db[key] else: from person import Person rec...

C++ to python with boost.python: Exposing virtual bool operator()(int )=0
Hello pythonians! ;-D , I have a little problem when I expose (assisted by boost.python) classes with virtual functions, specially with operator(). In the C++ code below I test two different implementations of a member function of A that takes as an argument the abstract class Base (see Option 1 / Option 2): - Both compile without problems - Only the second works in python (see python program below). It seems like if the problem is in the way I expose operator()... but I do not understand it very well Any clue about why this is happening?I would appreciate any comment on this. Tha...

Py++, boost and python type mismatch error
I have a simple C++ library (from a dll) I am attempting to make accessible through bindings to python. I used Py++ to generate some boost code for the library that I compiled into a pyd. I can import the pyd no problem into python, but I can't seem to call the functions. struct MM_Api { void* pData; }; int declspec(dllimport) MM_Initialize( MM_Api* pApi ); I made a PyMM.pyd that has this in it. import PyMM api = PyMM.MM_Api ret = PyMM.MM_Initialize(api) Traceback (most recent call last): File "<stdin>", line 1, in <module> Boost.Py...

Web resources about - Python interpreter error: unsupported operand type(s) for -: 'tuple' and 'int' - comp.lang.python

Resources last updated: 3/5/2016 5:26:06 PM