如何跳回特定的代码行(Python)

时间:2017-09-17 18:17:11

标签: python python-3.x

我刚刚提取了一些旧代码,但我很想知道如何跳回到特定的代码行。我的意思是,如果有一个if语句,除非另有说明,它会做一些事情,无论如何,我想要做的是if语句结束时,或者当我到达{{1}时我希望代码不要重新开始,而是从代码中的某一行开始。我将在下面解释更多:

CODE:

else

所以我真正想要的是,如果用户没有输入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() encrypt,它会向他们显示消息:decrypt但在此行下我希望它返回到You must enter either 'encrypt' or 'decrypt'!部分,而不是一直回到choice部分。如果有办法做到这一点,我真的很感谢你帮助我!

1 个答案:

答案 0 :(得分:0)

虽然循环最适合你的情况,但你真的可以跳回到一个特定的行:

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)

使用此功能跳回key = keyRead()行。 此外,还有goto implementation in the wild