Home > Mobile >  Is there any alternative to goto in Python?
Is there any alternative to goto in Python?

Time:07-10

Version: Python 3.7

for obj in group_obj.objects:
            bpy.ops.ed.undo_push()
        --> move_rotate(obj, T, T_0)
        |
        |   if check_if_cross_wall(obj):
        |       bpy.ops.ed.undo()
        ________from there


            count  = 1
            accessableArea(obj)
        

Here is my code. My target is to check if the condition is satisfied, and if it is True, it will reverse the operation and goto the first line directly. I think goto is the most suitable way to do this, but I just know goto in C or C , and Python does not have this.

Is there any other way to do this?

My code logic is:
Move & rotate the object, then check if it crosses the wall. If True, reverse the operation, then move & rotate again and check if it crosses the wall. If False, it will save the current state and go to the next object.

CodePudding user response:

No, there is no "goto" in Python. To accomplish the sort of jump you describe, you can use a while loop with a continue statement to move back to the start of the loop and break to exit the loop, like this:

for obj in group_obj.objects:
    bpy.ops.ed.undo_push()
    
    while True:
        move_rotate(obj, T, T_0)
        
        # as long as this is true, it will keep
        # moving back to the start of the loop
        if check_if_cross_wall(obj):
            bpy.ops.ed.undo()
            continue
            
        # Exit the loop when the condition
        # above wasn't true
        break

    count  = 1
    accessableArea(obj)

Alternately, you could structure it like this, where it breaks when the condition is false and otherwise just does "undo" and starts over (no continue needed):

for obj in group_obj.objects:
    bpy.ops.ed.undo_push()
    
    while True:
        move_rotate(obj, T, T_0)
        
        # exit the loop when the condition is false
        if not check_if_cross_wall(obj):
            break

        # otherwise undo and run the loop again
        bpy.ops.ed.undo()

    count  = 1
    accessableArea(obj)

CodePudding user response:

No. If you want to jump in your code, you will have to use functions:

def func0(n):
    return n - 5

def func1():
    print(1)

def func2():
    print(2)

if func0(5) > 0:
    func1()
else:
    func2()
  • Related