为什么Python没有goto语句?
是的,Python中没有goto语句。让我们先了解一下什么是C语言中的goto语句。但是,在C语言中,goto语句的使用也是被反对的。
C程序中的goto语句提供了无条件跳转到同一函数中标记语句的功能。以下是语法−
goto label;
..
.
label: statement;
阅读更多:Python 教程
示例
现在让我们看一个goto的C程序−
#include <stdio.h>
int main () {
int a = 10;
LOOP:do {
if( a == 15) {
/* 跳过本次迭代 */
a = a + 1;
goto LOOP;
}
printf("a = %d\n", a);
a++;
}while( a < 20 );
return 0;
}
输出
a = 10
a = 11
a = 12
a = 13
a = 14
a = 16
a = 17
a = 18
a = 19
注意 − 在C语言中,强烈反对使用goto语句。
Python中没有GoTo
在Python中,不需要goto,因为我们可以使用if语句,或,and,和if-else表达式以及while和for语句的loop,包括continue和break来完成相同的工作。
自定义异常
使用自定义异常作为另一种替代方案 −
class goto1(Exception):
pass
class goto2(Exception):
pass
class goto3(Exception):
pass
def loop():
print('start')
num = input()
try:
if num<=0:
raise goto1
elif num<=2:
raiseelif num<=4:
raise goto3
elif num<=6:
raise goto1
else:
print('end')
return 0
except goto1 as e:
print('goto1')
loop()
except goto2 as e:
print('goto2')
loop()
except goto3 as e:
print('goto3')
loop()
嵌套方法
示例
另一个替代方案是使用嵌套方法−
def demo():
print("在demo()函数中")
def inline():
print("在")
inline()
demo()
输出
在
在demo()函数中
goto-statement模块
这是一个在Python中使用goto的函数装饰器。在Python 2.6到3.6和PyPy上测试过。使用pip进行安装 −
注意:仅适用于Python 3.6
pip install goto-statement
让我们看一个例子 −
# Python 3.6
from goto import with_goto
@with_goto
def range(start, stop):
i = start
result = []
label .begin
if i == stop:
goto .end
result.append(i)
i += 1
goto .begin
label .end
return result
极客教程