Python递减for循环中的变量

劳雷欧

我将Java代码转换为python代码,以及如何在python的for循环内减少变量?如果索引位于if语句中,我会尝试将其减少1,但是显然我不能这样做。还有其他方法可以减少for循环中的i吗?

Java代码:

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代码:

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

输出:好吧,如果我们看一下输出,它仍然在增加而不减少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不允许您for循环更改迭代器一旦循环的下一次迭代出现,迭代器将成为可迭代对象的下一个值。

这也是因为range它的行为不像实际的类似Java的for循环。取而代之的是,它会一直在该范围内生成数字(您可以通过list(range(10))在Python解释器中键入内容来查看,它将列出从0到9的数字。

如果要修改迭代器,则应该while改用循环来代替:

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

这应该与您的Java代码相同,因为我只是将这三个指令从Javafor循环移至它们的位置。声明pass不是必需的,因为它是无效的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章