Skip to main content
 首页 » 编程设计

python之在 Python 中跳转

2025年05月04日14落叶无声

我想在 Python 代码中跳转(比如 goto ...)。 我知道 Goto 的编程很糟糕,但我现在太“深奥”了,无法重新创建我的结构。

此外,使用函数也不是一个好主意,因为我不希望程序继续运行函数调用之后的代码。

我正在考虑引发异常。我不确定这是否可行。

问题(简​​化):

假设我在自由奔跑。

如果我按“左”键,我的角色应该开始向左跑,当他撞到墙上时,他应该开始向右跑。 (类似于按“右”)

换句话说:当我的角色撞到墙上时,我希望代码块停止运行并启动另一个代码块。

异常(exception)会在这里起作用吗? 因为我不确定即使未遇到异常本身,异常引发下的代码是否会运行。

提前致谢

编辑: 我的代码:http://pastebin.com/QBy5x3g8 (死了)

请您参考如下方法:

If I press 'Left' My character should start running left, and when he hits a wall, he should start running right. (analogous for pressing 'Right') In other words: when my character hits a wall I want the codeblock to STOP running and to start another codeblock.

可以这样实现

# main loop 
while True: 
 
  # check for input and respond appropriately 
  if left_key_pressed: 
    # keep running left until you hit a wall 
    while not hit_wall: 
      run_left()  
 
    # hit a wall, do something after 
 
  elif right_key_pressed: 
    while not hit_wall: 
      run_right() 
 
    # hit a wall, do something after 

无需执行任何类型的显式 Goto

Besides, using functions wouldn't be a good idea because I don't want the program to continue running code that's after the function call.

如果您不希望程序在函数调用后继续运行,您始终可以显式终止程序或抛出异常使其崩溃,但我怀疑这就是您想要做的。至少,作为用户,我可能不希望程序因为我撞墙而终止。