简体   繁体   中英

Python decrement the variable inside for loop

i converted my java code into a python code and how to decrement the variable inside of the for loop in the python? I try to decrease the index by 1 if it is inside the if statement, but apparently I can't do that. Is there any other way that I can decrease i in a for loop?

Java Code:

for(int i = 1; i <= 3; i++)
        {
            System.out.print("Enter Movie " + i + " of " + 3 + " : ");
            String inputMovie = sc.nextLine();
            if (inputMovie.equals("")) 
            {
                System.out.println("Please input a movie name.");
                System.out.println("");
                i--;
            }

            else
                movies.offer("'"+inputMovie+"'");
        }

Python Code:

for i in range(1,4):
    inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
    if inputMovie=="":
        print("Please input a movie name")
        print("")
        i-=1
        pass
    else:
        movies.append(inputMovie)
    pass

Output: well if we look at the output it is still incrementing not decrementing the i

Enter Movie 1 of 3 :
Please input a movie name

Enter Movie 2 of 3 :
Please input a movie name

Enter Movie 3 of 3 :
Please input a movie name

Python doesn't let you alter the iterator in a for loop. As soon as the next iteration of the loop comes by, the iterator will be the next value of the iterable.

This is also because range doesn't behave like an actual Java-like for loop. Instead, it keeps generating numbers within the range (you can see this by typing list(range(10)) in a Python interpreter, it will make a list of numbers from 0 to 9.

If you want to modify the iterator, you should go old-school with a while loop instead:

i = 1
while i <= 3:
    inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
    if inputMovie=="":
        print("Please input a movie name")
        print("")
        i-=1
    else:
        movies.append(inputMovie)
    i = i + 1

This should do the same as your Java code, as I'm just moving the three instructions from the Java for loop to their places. Notice pass is not required as it is a statement with no effect.

For the sake of optimization, let me say you don't really need to decrement the iterator, just avoid incrementing it instead. I keep this solution separate from the original answer since it is a significant deviation from your original design:

i = 1
while i <= 3:
    inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
    if inputMovie=="":
        print("Please input a movie name")
        print("")
    else:
        movies.append(inputMovie)
        i = i + 1

All I've done is remove the decrement and push the increment to the else block so it is only run if a movie name has been input.

you should use a while statement

"Unfortunately" the for loop will keep "memory" and reassign to the next value at each iteration

i = 1
while i < 4:
    inputMovie = input("Enter Movie " + str(i) + " of " + str(3) + " : ")
    if inputMovie == "":
        print("Please input a movie name")
        print("")
        i-=1
    else:
        movies.append(inputMovie)
        i+=1

the pass instruction is irrelevant, you can omit that

pass statement

range(low,high) generates a sequence consisting of elements starting from low and ending at high-1 . That's why your i-=1 doesn't work, since I is iterating in that list.
The easiest alternative here would be to use a while loop.

while i<target:
    if something:
        #do something
        i += 1

The for loop in Python is more like for-each. So the loop value(i) will get updated to the next value regardless of the changes/updates in the loop.

A better way to do this would be to use a while loop.

i = 1
while i <= 3:
    inputMovie = input("Enter Movie " + str(i) + " of " + str(3) + " : ")
    if inputMovie=="":
        print("Please input a movie name")
        print("")
        i-=1
        pass
    else:
        movies.append(inputMovie)
        i+=1
    pass

You have to set your range() function correctly. In order to decrement the loop you can use while loop or you can change your algorithm and set the for loop but now what you can do is if you can select the range functions step value to -1. Please try it to check the code coz i also have the same question in mind like you.

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