How to jump back to a specific line of code (Python)
我刚刚提取了一些旧代码,但我很想知道如何跳回到特定的代码行。 我的意思是,如果有一个
码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | def main(): abc = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz' message = input("What's the message to encrypt/decrypt?") def keyRead(): try: return int(input("What number would you like for your key value?")) except ValueError: print("You must enter a number!") main() key = keyRead() choice = input("Choose: encrypt or decrypt.") if choice =="encrypt": encrypt(abc, message, key) elif choice =="decrypt": encrypt(abc, message, key * (-1)) else: print("You must chose either 'encrypt' or 'decrypt!'") main() def encrypt(abc, message, key): cipherText ="" for letter in message: if letter in abc: newPosition = (abc.find(letter) + key * 2) % 52 cipherText += abc[newPosition] else: cipherText += letter print(cipherText) return cipherText main() |
所以我真正想要的是,如果用户没有输入
虽然循环最适合你的情况,但你真的可以跳回到一个特定的行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import sys def jump(lineno): frame = sys._getframe().f_back called_from = frame def hook(frame, event, arg): if event == 'line' and frame == called_from: try: frame.f_lineno = lineno except ValueError as e: print"jump failed:", e while frame: frame.f_trace = None frame = frame.f_back return None return hook while frame: frame.f_trace = hook frame = frame.f_back sys.settrace(hook) |
使用此功能跳回
此外,还有野外的goto实现。