简体   繁体   English

我们如何 go 回到 Python 中的前一行代码,就像我们在 Fortran 中所做的那样

[英]How can we go back a previous line of code in Python like we could do in Fortran

I try to convert Fortran code into Python language since it's easy to find some python tutorials online rather than with Fortran.我尝试将 Fortran 代码转换为 Python 语言,因为它很容易在线找到一些 python 教程,而不是 Z884826ZB96666。 However, the Fortran code I work with has a goto function to go back to the previous line, to make an iteration (a loop).但是,我使用的 Fortran 代码有一个 goto function 到 go 回到上一行,以进行迭代(循环)。 I used the while loop Python instead of the goto in but the result value is not the same.我使用了 while 循环 Python 而不是 goto in 但结果值不一样。 For easy understanding, my code can be simply explained by a simple math problem, which is to calculate the square root of 2. In Fortran, it wrote:为了便于理解,我的代码可以用一个简单的数学问题来简单解释,就是计算2的平方根。在Fortran中,它写道:

    a = 2
    x = 1
    iter0 = 0
100 continue
    iter0 = iter0 + 1
    x1 = a / x
    err = abs(x1 - x) / abs(x)
    x = x + 0.7 * (x1 - x)
    if(err.gt.1.0e-6) goto 100

    print*, x

In Python, I wrote在 Python 中,我写道

a = 2
x = 1
x1 = a / x
err = abs(x1 - x) / abs(x)
iter0 = 0
while err > 1.0e-6:
    iter0 = iter0+1
    x = x + 0.7 * (x1 - x)
    x1 = a / x
    err = abs(x1 - x) / abs(x)
print(x)

So for you, is the structure of the Python code would work the same way the Fortran one did, isn't it?所以对你来说,Python 代码的结构是否与 Fortran 代码的工作方式相同,不是吗? I found the result is not the same我发现结果不一样

Your result isn't the same because you're doing things in a different order to what you were doing in your original code.你的结果不一样,因为你做事的顺序与你在原始代码中做的事情不同。

There are no GOTOs in python, you've done the right thing of using a while loop python 中没有 GOTO,您使用 while 循环是正确的

you want你要

a = 2
x = 1
iter0 = 0
err = 1 #do this so we enter the while loop
while err > 1.0e-6:
    iter0 = iter0+1
    x1 = a / x
    err = abs(x1 - x) / abs(x)
    x = x + 0.7 * (x1 - x)
    
print(x)

This gives 1.4142133304064006这给出了 1.4142133304064006

Unfortunately you can't do that in python, but instead you could put all your code in a function and call the function.不幸的是,您不能在 python 中执行此操作,但您可以将所有代码放入 function 并调用 function。 Or if you want to repeat something, you could of course use loops.或者,如果您想重复某些内容,当然可以使用循环。 So basically go around the "issue".所以基本上 go 围绕“问题”。

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

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