简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM