BeginnerCode776
BeginnerCode776

Reputation: 27

Counter variable isnt being incremented inside the for loop correctly

I am trying to increment symbol by 2 in the first if statement instead of by 1, which is the default for this for loop. However, even after the if statement is true and symbol is incremented by 2, the following iteration runs as if the symbol has just been incremented by 1. So my dilemma is that even though symbol is being increased by 2, it goes back to being increased by one which makes doing symbol+=2 useless.

Is there any way of increasing symbol by 2 in the first if statement?

def solution(roman):
    
    value = 0

    for symbol in range(len(roman)):
            
        if roman[symbol:symbol+2] == 'IV':
            value+=4
            symbol+=2
        
        elif roman[symbol] == 'I':
            value+=1
            
        elif roman[symbol] == 'V':
            value+=5
            
    return value

Upvotes: 0

Views: 554

Answers (1)

S4NR-3000
S4NR-3000

Reputation: 57

I fear you can't do it with the for loop:

The for-loop makes assignments to the variables in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop. The for Statement. doc.python.org

for is a little different in Python as it "is [only] used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object".

Give the while loop try.

Upvotes: 1

Related Questions