Goto (Posting On Python-List Prohibited)

Chris Angelico rosuav at gmail.com
Sun Dec 31 14:37:02 EST 2017


On Mon, Jan 1, 2018 at 6:29 AM, bartc <bc at freeuk.com> wrote:
> You'll need to give an example I think. Suppose I start with this:
>
> def fn(a):
>     if a==1:
>         print ("One")
>         print ("Two")
>         print ("Three")
>     elif a==2:
>         print ("Four")
>     else:
>         print ("Other")
>         print ("One")
>         print ("Two")
>         print ("Three")
>
> I want to share the lines that print One Two Three, so I create an inline
> function, defined as close as possible to the original code:
>
> def fn2(a):
>     if a==1:
>         def F123():
>             print ("One")
>             print ("Two")
>             print ("Three")
>         F123()
>     elif a==2:
>         print ("Four")
>     else:
>         print ("Other")
>         F123()
>
> However, if I call this with fn2(3), it says that variable F123 has not been
> assigned.

Right, so you'd move it one line up (or move the 'if' down to below
the function definition), thus the larger block of code stays where it
is.

> Note also that a goto, and a function call, don't do the same thing. The
> function will return, the goto won't.

Not sure what you mean by "return", because what you effectively do is
create a name for a block of code, and then use (call) that block of
code more than once. That makes it easy to comprehend. With the goto,
you have to go look at the body below to figure out what happens.

ChrisA



More information about the Python-list mailing list