python怎么使用goto跳转执行到指定代码行?

猿友 2021-08-05 16:25:45 浏览数 (11662)
反馈

在开发过程中我们可能会需要让代码跳转到指定代码行,在汇编和C语言中都可以使用goto关键字进行跳转,那么python跳转到指定代码行要如何实现呢?今天我们就来聊聊python goto跳转。

1. 缘起

在实际开发中遇到这样一个问题:

以下是伪代码

if embedding.model is not exist:
 calculate embedding   ## moudel_1
 save embedding.model
else :
 embedding = load embedding.model

try:
 use embedding
except KeyError:
 calculate embedding    ##这里与moudel_1一致。

发现except 中需要粘贴之前写过的calculate embedding

简单概括就是:

somecode_1
try:
 somecode_2
except:
 somecode_3   
 somecode_1   ## 重新执行

2. 使用goto

(1)安装goto

pip install goto-statement

(2)使用goto完成一个小例子

官方文档见:https://pypi.org/project/goto-statement/

定义函数

from goto import with_goto

@with_goto     #必须有
def test(list_): 
    tmp_list = list_
    label.begin  #标识跳转并开始执行的地方
    result = []
    try:
        for i, j in enumerate(list_):
            tmp = 1 / j
            result.append(tmp)
            last_right_i = i
    except ZeroDivisionError:
        del tmp_list[last_right_i + 1]
        goto.begin      #在有跳转标识的地方开始执行
    return result

运行

a = test([1, 3, 4, 0, 6])
print(a)

结果

[1.0, 0.3333333333333333, 0.25, 0.16666666666666666]

注意:如果你在ide山运行label 和 goto 下有红色波浪线提示错误。不用理会直接执行即可

补充:Pycharm跳转回之前所在的代码行

用Pycharm写Python代码有一段时间了,有一个问题一直困扰着我:浏览代码的时候时常需要从一个函数跳转到另一个函数,有时候两个函数相聚比较远,我一直不知道怎么直接回到上一个函数。

于是我采取的办法是按ctr+F然后输入上一个函数的函数名来定位并且回到上一个函数。不忍直视~~~

下面是找到跳转按钮的过程:

1.找到View下面的Toolbar并勾选上

启动跳转控制台


2.按钮出现

按钮出现

一款对浏览代码功能支持良好的IDE一般Toolbar上都有按钮或者会有快捷键可以在历史浏览页面之间跳转。而我的Pycharm的默认设置一直是将Toolbar隐藏起来的。

以上就是python跳转到指定代码行的全部内容,值得一提的是,goto跳转这种方式虽然在实现上没有问题,也不会对代码的效率造成太多影响,但是这种方式对代码的结构有比较大的破坏,很影响代码的阅读,小编的编程老师让我们尽量少使用这种方式的代码,希望小伙伴在使用goto的时候有所考量,也希望大家多多支持W3Cschool


0 人点赞