為什麼 Python 中沒有 goto 語句?
是的,Python 中沒有 goto 語句。讓我們首先了解 C 語言中的 goto 是什麼。但是,在 C 中也不鼓勵使用 goto。
C 程式語言中的 goto 語句提供了一個從 'goto' 到同一函式中帶標籤語句的無條件跳轉。以下是語法:
goto label; .. . label: statement;
示例
現在讓我們看看一個用於 goto 的 C 程式:
#include <stdio.h> int main () { int a = 10; LOOP:do { if( a == 15) { /* skip the iteration */ 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 語句以及或、與、if-else 表示式和 while 和 for 迴圈(包含 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: raise goto2 elif 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("In the demo() function") def inline(): print("In") inline() demo()
輸出
In In the demo() function
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP