Python 循环内减少变量。

huangapple go评论76阅读模式
英文:

Python decrement the variable inside for loop

问题

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("")
        continue
    else:
        movies.append(inputMovie)

输出:嗯,如果我们看输出,它仍然在递增而不是递减 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
英文:

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

答案1

得分: 2

Python不允许在for循环中更改迭代器。一旦循环的下一次迭代到来,迭代器将是可迭代对象的下一个值。

这也是因为range不像真正的类似Java的for循环那样运作。相反,它在范围内生成数字(您可以通过在Python解释器中键入list(range(10))来查看,它会生成一个从0到9的数字列表)。

如果要修改迭代器,应该使用旧式的while循环:

i = 1
while i <= 3:
    inputMovie = input("输入第" + str(i) + "部电影(共3部):")
    if inputMovie == "":
        print("请输入电影名称")
        print("")
        i -= 1
    else:
        movies.append(inputMovie)
    i = i + 1

这与您的Java代码执行的操作相同,只是我将Java for 循环中的三个指令移到了相应的位置。请注意,由于pass没有任何效果,所以不需要它。

出于优化的考虑,我想说您实际上不需要递减迭代器,而是应该避免递增迭代器。我将此解决方案与原回答分开,因为它与您的原始设计有显著偏差:

i = 1
while i <= 3:
    inputMovie = input("输入第" + str(i) + "部电影(共3部):")
    if inputMovie == "":
        print("请输入电影名称")
        print("")
    else:
        movies.append(inputMovie)
        i = i + 1

我所做的只是去除了递减操作,并将递增操作移到了else块中,这样只有在输入了电影名称时才会执行递增。

英文:

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 &lt;= 3:
    inputMovie=input(&quot;Enter Movie &quot; + str(i) + &quot; of &quot; + str(3) + &quot; : &quot;)
    if inputMovie==&quot;&quot;:
        print(&quot;Please input a movie name&quot;)
        print(&quot;&quot;)
        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 &lt;= 3:
    inputMovie=input(&quot;Enter Movie &quot; + str(i) + &quot; of &quot; + str(3) + &quot; : &quot;)
    if inputMovie==&quot;&quot;:
        print(&quot;Please input a movie name&quot;)
        print(&quot;&quot;)
    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.

答案2

得分: 1

你应该使用 while 语句。

“不幸的是”,for 循环会保留“内存”,并在每次迭代时重新分配给下一个值。

i = 1
while i < 4:
    inputMovie = input("输入第 " + str(i) + " 部电影(共 " + str(3) + " 部):")
    if inputMovie == "":
        print("请输入电影名称")
        print("")
        i -= 1
    else:
        movies.append(inputMovie)
        i += 1

pass 指令是不相关的,可以省略。

pass 语句

英文:

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 &lt; 4:
    inputMovie = input(&quot;Enter Movie &quot; + str(i) + &quot; of &quot; + str(3) + &quot; : &quot;)
    if inputMovie == &quot;&quot;:
        print(&quot;Please input a movie name&quot;)
        print(&quot;&quot;)
        i-=1
    else:
        movies.append(inputMovie)
        i+=1

the pass instruction is irrelevant, you can omit that

pass statement

答案3

得分: 1

range(low,high) 生成一个序列,其中的元素从 low 开始,到 high-1 结束。这就是为什么你的 i-=1 不起作用,因为 i 在该序列中进行迭代。
在这种情况下,最简单的替代方法是使用 while 循环。

while i&lt;target:
    if something:
        #做点什么
        i += 1
英文:

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&lt;target:
    if something:
        #do something
        i += 1

答案4

得分: 1

以下是翻译好的部分:

在Python中,for循环更像是for-each。因此,循环的值(i)将会被更新为下一个值,而不管循环中的变化/更新如何。

一个更好的方法是使用while循环。

i = 1
while i <= 3:
    inputMovie = input("输入第 " + str(i) + " 部电影(共 3 部): ")
    if inputMovie == "":
        print("请输入电影名称")
        print("")
        i -= 1
        pass
    else:
        movies.append(inputMovie)
        i += 1
    pass

请注意,我已经移除了HTML编码(例如&lt;&quot;)并进行了适当的翻译。

英文:

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 &lt;= 3:
    inputMovie = input(&quot;Enter Movie &quot; + str(i) + &quot; of &quot; + str(3) + &quot; : &quot;)
    if inputMovie==&quot;&quot;:
        print(&quot;Please input a movie name&quot;)
        print(&quot;&quot;)
        i-=1
        pass
    else:
        movies.append(inputMovie)
        i+=1
    pass

答案5

得分: 1

你必须正确设置你的 range() 函数。为了递减循环,你可以使用 while 循环,或者你可以修改你的算法并设置 for 循环,但现在你可以尝试的是,如果你将 range() 函数的步长值设为 -1。请尝试一下,检查一下代码,因为我也有与你类似的问题。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月21日 14:27:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64457797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定