如何仅打印for循环中的最后一个值? [英] How do I print only the last value in a for loop?
本文介绍了如何仅打印for循环中的最后一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于下面的代码,我只想打印平方根函数的最后一个近似值,而不是打印出所有近似值.
For the below code, I only want to print the last approximation for the squareroot function, instead of printing out every approximation.
def square(x):
guess = int(x/2)
for i in range(1,10):
nextguess = (guess + x/guess)/2
guess=nextguess
print(nextguess)
推荐答案
只需取消您的print()
标识即可:
Just de-denting your print()
will work:
def square(x):
guess = int(x/2)
for i in range(1,10):
nextguess = (guess + x/guess)/2
guess=nextguess
print(nextguess)
循环后,nextguess
仍然具有最后一个循环的值.
在Python中,循环不会创建新的作用域.因此,您在循环中创建或更改的所有内容在循环之后仍然可用.
After the loop, nextguess
still has the value form the last cycle.
In Python, a loop does not create a new scope. So, everything you create or change in the loop is still available after the loop.
这篇关于如何仅打印for循环中的最后一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文