简体   繁体   English

如何仅打印 for 循环中的最后一个值?

[英]How do I print only the last value in a for loop?

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)

Just de-denting your print() will work:只需去除您的print()凹痕即可:

def square(x):
    guess = int(x/2)
    for i in range(1,10):
        nextguess = (guess + x/guess)/2
        guess=nextguess
    print(nextguess)

After the loop, nextguess still has the value form the last cycle.在循环之后, nextguess仍然具有上一个循环的值。 In Python, a loop does not create a new scope.在 Python 中,循环不会创建新的作用域。 So, everything you create or change in the loop is still available after the loop.因此,您在循环中创建或更改的所有内容在循环后仍然可用。

If you are using a list, for example, List1 is the List name:例如,如果您使用的是列表,则List1是列表名称:

List1 = ["praneeth","Veeru","Avinash","Harsha","Avinash"] . List1 = ["praneeth","Veeru","Avinash","Harsha","Avinash"]

If you would like to print Avinash which is the last element of the list, you can use List1[-1] which returns the last element of the list.如果您想打印列表的最后一个元素Avinash ,您可以使用List1[-1]返回列表的最后一个元素。

You can try doing it with a while loop你可以尝试用一个while循环来做

def square(x):
    guess = int(x/2)
    i = 1
    while (i < 10):
        nextguess = (guess + x/guess)/2
        guess=nextguess
        i = i + 1
    print(nextguess)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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