2

I'm trying to create a long calculation calculator ( does long division, addition etc.) while in the long division section I'm trying to get the number to divide with but I can't (as in numdiv)

Ex: In 240 / 12, the number I'm trying to find is 24, then I'll have another loop that will add 12 to find 2 (as in 24/12 is 2).

Here is my code:

##############
#number is bigger (or equal) to number 2

number = 19000
operation = '/'
number2 = 12

##############

import math

longer = len(str(number))
shorter = len(str(number2))
if operation == '/':
    print str(number2) + '/' + str(number)
for i in range(longer - 1):
    if int(str(number)[0, i]) >= number2:
        numdiv = int(str(number)[0, i])
for i in range(1, math.trunc(numdiv / number2)):
    if number2 * (i + 1) >= numdiv:
        print (shorter + 1) * ' ' + number * i

The error is 5 lines from the end where I did

if int(str(number)[0, i]) >= number2:

It said

TypeError: string indices must be numbers, not object

NEW

I tried doing

if str(number)[:i] >= number2:
        numdiv = str(number)[:i]
for i in range(1, math.trunc(numdiv / number2)):
    if number2 * (i + 1) >= numdiv:
        print (shorter + 1) * ' ' + number * i

numdiv in this case is trying to be an integer and doing this causes the problem:

ValueError: invalid literal for int() with base 10: ''

How do I fix this?

4
  • 1
    The first thing I notice is you should be using [0:i] to represent a range of indices, not [0, i]. Still, when I replicated it I got that it "not tuple" instead of "not object"... Commented Feb 13, 2016 at 1:04
  • You're not indexing into the string properly. I'm not sure exactly what you're trying to do, but indexing formatting is [start:stop:step], right now it thinks you're trying to index with a list, hence the error. Commented Feb 13, 2016 at 1:05
  • This tutorial should give you a good idea of how to slice strings and what can be done with slices. Commented Feb 13, 2016 at 1:17
  • ok, kinda forgot that. Thanks. Commented Feb 13, 2016 at 1:31

1 Answer 1

0

With somestring[0, i] you are trying to index into a string using a tuple.

Proof:

>>> class mystr(str):
...     def __getitem__(self, x):
...         print(x, type(x))
... 
>>> f = mystr('foo')
>>> f[0, 1]
((0, 1), <type 'tuple'>)

Trying to index into a string using anything but integers will give you a TypeError.

If you want a slice from your string up to position i, use

str(number)[0:i]

or just

str(number)[:i]

which does the same.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.