在Python中是否有goto或任何等价的东西能够跳转到特定的代码行?


当前回答

我有自己的做法。 我使用单独的python脚本。

如果我想要循环:

file1.py

print("test test")
execfile("file2.py")
a = a + 1

file2.py

print(a)
if a == 10:
   execfile("file3.py")
else:
   execfile("file1.py")

file3.py

print(a + " equals 10")

(注意:此技术仅适用于Python 2。x版本)

其他回答

不,有另一种方法来实现goto语句

class id:
     def data1(self):
        name=[]
        age=[]   
        n=1
        while n>0:
            print("1. for enter data")
            print("2. update list")
            print("3. show data")
            print("choose what you want to do ?")
            ch=int(input("enter your choice"))
            if ch==1:    
                n=int(input("how many elemet you want to enter="))
                for i in range(n):
                    name.append(input("NAME "))
                    age.append(int(input("age "))) 
            elif ch==2:
                name.append(input("NAME "))
                age.append(int(input("age ")))
            elif ch==3:
                try:
                    if name==None:
                        print("empty list")
                    else:
                        print("name \t age")
                        for i in range(n):
                            print(name[i]," \t ",age[i])
                        break
                except:
                    print("list is empty")
            print("do want to continue y or n")
            ch1=input()
            if ch1=="y":
                n=n+1
            else:
                print("name \t age")
                for i in range(n):
                    print(name[i]," \t ",age[i])
                n=-1
p1=id()
p1.data1()  

虽然在Python中没有任何等同于goto/label的代码,但您仍然可以使用循环来获得goto/label的这种功能。

让我们以下面所示的代码示例为例,其中goto/label可以在python以外的任意语言中使用。

String str1 = 'BACK'

label1:
    print('Hello, this program contains goto code\n')
    print('Now type BACK if you want the program to go back to the above line of code. Or press the ENTER key if you want the program to continue with further lines of code')
    str1 = input()

if str1 == 'BACK'
    {
        GoTo label1
    }
print('Program will continue\nBla bla bla...\nBla bla bla...\nBla bla bla...')

现在,通过使用下面所示的while循环,可以在python中实现上述代码示例的相同功能。

str1 = 'BACK'

while str1 == 'BACK':
        print('Hello, this is a python program containing python equivalent code for goto code\n')
        print('Now type BACK if you want the program to go back to the above line of code. Or press the ENTER key if you want the program to continue with further lines of code')
        str1 = input()
print('Program will continue\nBla bla bla...\nBla bla bla...\nBla bla bla...')

我在官方的python设计和历史FAQ中找到了这个。

为什么没有goto? 您可以使用异常来提供一个甚至可以工作的“结构化goto” 跨函数调用。许多人认为异常可以方便地实现 模拟C语言中“go”或“goto”结构的所有合理使用, Fortran和其他语言。例如:

class label(Exception): pass  # declare a label

try:
    ...
    if condition: raise label()  # goto label
    ...
except label:  # where to goto
    pass
... 

这并不允许你跳到循环的中间,但那是 通常被认为是对goto的滥用。很少使用。

在官方常见问题解答中甚至提到了这一点,并且提供了一个很好的解决方案示例,这非常好。我真的很喜欢python,因为它的社区甚至是这样对待goto的;)

我认为while循环是“goto_Statement”的替代。因为3.6之后,goto循环不再工作了。我还写了一个while循环的例子。

str1 = "stop"
while str1 == "back":
    var1 = int(input(" Enter Ist Number: "))
    var2 = int(input(" Enter 2nd Number: "))
    var3 = print("""  What is your next operation
                      For Addition   Press And Enter : 'A'
                      For Muliplt    Press And Enter : 'M'
                      For Division   Press And Enter : 'D'
                      For Subtaction Press And Enter : 'S' """)

    var4 = str(input("For operation press any number : "))
    if(var1 == 45) and (var2 == 3):
        print("555")
    elif(var1 == 56) and (var2 == 9):
        print("77")
    elif(var1 == 56) and (var2 == 6):
        print("4")
    else:
        if(var4 == "A" or "a"):
            print(var1 + var2)
        if(var4 == "M" or "m"):
            print(var1 * var2)
        if(var4 == "D" or "d"):
            print(var1 / var2)
        if(var4 == "S" or "s"):
            print(var1 - var2)

    print("if you want to continue then type  'stop'")

    str1 = input()
print("Strt again")    

我用函数解决了这个问题。我唯一做的就是改变函数的标签。下面是一个非常基本的代码:

def goto_holiday(): #label: holiday
        print("I went to holiday :)")
    
def goto_work(): #label: work
    print("I went to work")
salary=5000
if salary>6000:
    goto_holiday()
else:
    goto_work()