473,386 Members | 1,736 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

"list indices must be integers, not str"

I'm writing a calculator that takes simple input. This is the code so far.

Expand|Select|Wrap|Line Numbers
  1. def getlist(rawstring):
  2.   stringclip = rawstring.replace(" ", "")
  3.   oplist = {'+':' + ','-':' - ','*':' * ','/':' / ','(':' ( ',')':' ) ','^':' ^ '}
  4.   ''' This replacement implementation came from http://gomputor.wordpress.com/ '''
  5.   for i, j in oplist.iteritems():
  6.     stringclip = stringclip.replace(i, j)
  7.   return stringclip.split()
  8.  
  9. def domath(blist, op):
  10.   for i in blist:
  11.     if blist[i] == op:
  12.       x = blist.pop(i - 1)
  13.       y = blist.pop(i + 1)
  14.       x = float(x)
  15.       y = float(y)
  16.       if op == '^':
  17.         del blist[i]
  18.         blist.inser(i, x**y)
  19.       elif op == '*':
  20.         del blist[i]
  21.         blist.insert(i, x*y)
  22.       elif op == '/':
  23.         del blist[i]
  24.         blist.insert(i, x/y)
  25.       elif op == '+':
  26.         del blist[i]
  27.         blist.insert(i, x+y)
  28.       else:
  29.         del blist[i]
  30.         blist.insert(i, x-y)
  31.   return blist
  32.  
  33. fullstring = raw_input("What would you like to calculate?: ")
  34.  
  35. operlist = ['^','*','/','+','-']
  36.  
  37. for i in operlist:
  38.   domath(getlist(fullstring), operlist[i])
  39.  
When I run this code I get the error:

Expand|Select|Wrap|Line Numbers
  1. What would you like to calculate?: 8 / 4 + 2
  2. Traceback (most recent call last):
  3.   File "/Users/Tramp/Desktop/calc2.py", line 46, in <module>
  4.     domath(getlist(fullstring), operlist)
  5.   File "/Users/Tramp/Desktop/calc2.py", line 17, in domath
  6.     if blist[i] == op:
  7. TypeError: list indices must be integers, not str
  8.  
So two questions

1) What am I doing wrong here? I thought that what I was doing was passing i, an integer, into a list which would get me the value stored at that place -- which according to my code should be a string which I should be able to then compare with another string. What am I misunderstanding?

2) Once this is solved, is there an easy way to catch errors and, instead of crashing the script, print something like "Input error"? I'm thinking of a situation in which someone feeds my script the input "4 + 5 - 6#$#@% - 1". The nonsense in the middle will cause my script to store #$#@% as a value in the list, but when it comes time to do a mathematical operation on it I will receive an error. The same thing would happen if someone wrote "5 ++ 6" into my code. Any help on this front is greatly appreciated. I'm being a bit preemptive.

I realize that I'm a newb, and I don;t want to waste anybody's time. If anyone has links that answer or partially answer my question, feel free to just drop them here. I don't want anyone to have to write out a long explanation. I'm sure what I'm doing is very elementary.

Thanks for the help.
May 26 '10 #1
3 14155
dwblas
626 Expert 512MB
A simple print statement should help.
Expand|Select|Wrap|Line Numbers
  1. def domath(blist, op):
  2.     for el in blist:
  3.         print el, type(el) 
You should not use "i", "l", or "o" as variable names as they can look like numbers.
May 26 '10 #2
EDIT because I figured out a bit more.

So I was misunderstanding what the "for i in blaba" was actually returning. I get that now, it's already returning the value inside of the list. I can change my code to partially accomodate for that, but what I really wanted to do -- the spirit of what I was trying to do -- was to run the function passing in a different value each time by changing the index of the list by one until the list is done (I hope that makes sense).

I can rewrite my code to something like this, but it won't work. This is because I want to actually work with the position that a value is at in the list, and not just the value itself. I will now get an error when I try to use "i" as the integer position within the list (because it's not, it's the value at a given position IN the list). Is there a way to use my original code but write the "for" loop in such a way that what us being passed in is just the integer being changed by 1 until the max value in the list is reached?

Expand|Select|Wrap|Line Numbers
  1. def getlist(rawstring):
  2.   stringclip = rawstring.replace(" ", "")
  3.   oplist = {'+':' + ','-':' - ','*':' * ','/':' / ','(':' ( ',')':' ) ','^':' ^ '}
  4.   ''' This replacement idea from http://gomputor.wordpress.com/ '''
  5.   for i, j in oplist.iteritems():
  6.     stringclip = stringclip.replace(i, j)
  7.   return stringclip.split()
  8.  
  9. def doparemath(alist):
  10.   for i in alist:
  11.     if alist[i] == '(':
  12.       print "temporary"
  13. # will need to check at the end to see if it needs to run again (if there are other parentheses)
  14.  
  15. def domath(blist, op):
  16.   for i in blist:
  17.     if i == op:
  18.       x = blist.pop(i - 1)
  19.       y = blist.pop(i + 1)
  20.       x = float(x)
  21.       y = float(y)
  22.       if op == '^':
  23.         del blist[i]
  24.         blist.inser(i, x**y)
  25.       elif op == '*':
  26.         del blist[i]
  27.         blist.insert(i, x*y)
  28.       elif op == '/':
  29.         del blist[i]
  30.         blist.insert(i, x/y)
  31.       elif op == '+':
  32.         del blist[i]
  33.         blist.insert(i, x+y)
  34.       else:
  35.         del blist[i]
  36.         blist.insert(i, x-y)
  37.   return blist
  38.  
  39. fullstring = raw_input("What would you like to calculate?: ")
  40.  
  41. operlist = ['^','*','/','+','-']
  42.  
  43. for i in operlist:
  44.   domath(getlist(fullstring), i)
  45.  
May 26 '10 #3
dwblas
626 Expert 512MB
You can use enumerate:
Expand|Select|Wrap|Line Numbers
  1. def domath(blist, op):
  2.     for ctr, el in enumerate(blist):
  3.         print ctr, el, type(ctr), type(el) 
  4. #
  5. #  or range
  6. def domath(blist, op):
  7.     for ctr in range(len(blist)):
  8.         print ctr, blist[ctr], type(ctr) 
May 27 '10 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: Nicolas Girard | last post by:
Hi, Forgive me if the answer is trivial, but could you tell me how to achieve the following: {k1:,k2:v3,...} --> ,,,...] The subtle point (at least to me) is to "flatten" values that are...
14
by: MLH | last post by:
I have the following code to list query names in Access 2.0's Immediate Window. Currently, it lists names of all saved queries. Can you suggest a modification that will result in it listing only...
59
by: Pierre Quentel | last post by:
Hi all, In some program I was testing if a variable was a boolean, with this test : if v in My script didn't work in some cases and I eventually found that for v = 0 the test returned True ...
7
by: Girish Sahani | last post by:
Hi, Please check out the following loop,here indexList1 and indexList2 are a list of numbers. for index1 in indexList1: for index2 in indexList2: if ti1 == ti2 and not index1 !=...
3
by: janzon | last post by:
Hi! Sorry for the bad subject line... Here's what I mean. Suppose we deal with C++ standard integers lists (the type is indifferent). We have a function f, declared as list<intf(int); Now...
8
by: John Nagle | last post by:
The Python documentation for "str" says "str() : Return a string containing a nicely printable representation of an object." However, there's no mention of the fact that "str" of a Unicode...
4
by: =?utf-8?B?Qm9yaXMgRHXFoWVr?= | last post by:
Hello, what is the use-case of parameter "start" in string's "endswith" method? Consider the following minimal example: a = "testing" suffix="ing" a.endswith(suffix, 2) Significance of...
1
by: bcwhite | last post by:
I'm writing a program and want to create a class that is derived from the "str" base type. When I do so, however, I have problems with the __init__ method. When I run the code below, it will call...
3
by: Ge Chunyuan | last post by:
hi Group: Once use ActivePython latest version for Python 2.5.1. I happened to find function "str" is not callable, but it is available for Python 2.5. Can anybody give some comments about it?...
2
by: stef mientki | last post by:
hello, The next piece of code bothers me: ptx, pty, rectWidth, rectHeight = self._point2ClientCoord (p1, p2 ) dc.SetClippingRegion ( ptx, pty, rectWidth, rectHeight ) Because I want to...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.