0

If I write i+=2, 'i' in "for" doesn't change. I know how to parse, but I don't know how to increase "i". Maybe it is very stupid question but in c++ I can do it

d = {
    'zero': 0,
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4,
    'five': 5,
    'six': 6,
    'seven': 7,
    'eight': 8,
    'nine': 9,
    'ten': 10,
    'eleven': 11,
    'twelve': 12,
    'thirteen': 13,
    'fourteen': 14,
    'fifteen': 15,
    'sixteen': 16,
    'seventeen': 17,
    'eighteen': 18,
    'nineteen': 19,
    'twenty': 20,
    'thirty': 30,
    'forty': 40,
    'fifty': 50,
    'sixty': 60,
    'seventy': 70,
    'eighty': 80,
    'ninety': 90,
    'hundred': 100,
    'thousand': 1000,
    'million': 1000000 } def simple_num(num:str):
    num_s = num.split("-")
    k = d[num_s[0]] + d[num_s[1]]
    return k

def parse_int(string:str):
    string = string.split()
    if "and" in string:
        string.remove('and')
    s = 0
    for i in range(0,len(string)):
        if i+1<len(string) and (string[i+1] in ['million','thousand','hundred']):
            if i+1<len(string) and string[i+1] == 'hundred':
                s += d[string[i]] * d[string[i + 1]]

            else:
                s+=simple_num(string[i])
                s*=d[string[i+1]]

            i+=2
            continue
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • There is nothing you can do to `i` inside the loop, since at the next iteration it is overwritten by the next value from `range()`. What reason do you have that requires `i+=2`? – quamrana Jan 28 '21 at 16:29
  • You *do*i increase it, but then at the beginning of each iteration, `i` is assigned the next object in the iterator, so it gets overwritten, because `i` is the loop target, you did `for i in ...` – juanpa.arrivillaga Jan 28 '21 at 16:34

1 Answers1

1

You could use a while loop :

count = len(string)
i = 0
while(i < count):
    # do something
    i += 2
dspr
  • 2,383
  • 2
  • 15
  • 19
  • yes, you are right. But I want to understand , why i couldn't increase 'i' in 'for'. i think that problem in range() – DarthVader8848 Jan 28 '21 at 16:36
  • @muradocaqverdiyev no, it has *nothign* to do with `range`. You need to understand that Python for-loops are *iterator based* for loops. In the statement, `for in : ...` an *iterator* is made on the result of the expression in ``, in this case, you used `range(0, len(string))` which creates a `range` object (i.e. `range` is a constructor). An iterator is created from that iterable, and on each iteration, the result of `next(iterator)` is assigned to ``. So at the beginning of each iteration, `i` is reassigned, until the iterator is empty, and the loop exits – juanpa.arrivillaga Jan 28 '21 at 16:41
  • thank you! I think I need to study this issue – DarthVader8848 Jan 28 '21 at 16:43