简体   繁体   中英

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. However, the Fortran code I work with has a goto function to go back to the previous line, to make an iteration (a loop). I used the while loop Python instead of the goto in but the result value is not the same. 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:

    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

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? 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

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

Unfortunately you can't do that in python, but instead you could put all your code in a function and call the function. Or if you want to repeat something, you could of course use loops. So basically go around the "issue".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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