Maks
Maks

Reputation: 257

Equivalent to GOTO in conditions, Python

Since there is no goto operator in Python, what technique can be used instead?

Condition If it is true, go to thread 1, if is false, go to thread 2 In thread we do something small and after that we go to thread 2 where all other actions take place.

Upvotes: 5

Views: 39030

Answers (5)

Jatin Falak
Jatin Falak

Reputation: 1

def thread1():
    #write your thread 1 code here

    print("entered no is 1")

def thread2():
    #write your thread 2 code here
    print("Number is greater or less then one.")

def main():
   a=input()
   if a==1:
   thread1()
   elif a<=1 or a>=1:
   thread2()
    #you can use recursion here in case if you want to use agin and again
    #if you want to print serveral time you can use looping.
    for i in range(4):
        main()
    #if you want to run goto forever and ever and ever then remove loop in 
    #this code.

#this code will enable you the equivalent of goto statement.

This is what I use every time in Python 3.x.

Upvotes: 0

st0le
st0le

Reputation: 33545

To the best of my knowledge it's not present (thankfully), but you should check this link

The "goto" module was an April Fool's joke, published on 1st April 2004. Yes, it works, but it's a joke nevertheless. Please don't use it in real code!

Upvotes: 5

detly
detly

Reputation: 30342

Since there is no goto operator in Python, what technique can be used instead?

Constructing your code logically and semantically.

if condition:
    perform_some_action()

perform_other_actions()

Upvotes: 14

Optimal Cynic
Optimal Cynic

Reputation: 807

def thread_1():
  # Do thread_1 type stuff here.

def thread_2():
  # Do thread_2 type stuff here.

if condition:
    thread_1()

# If condition was false, just run thread_2(). 
# If it was true then thread_1() will return to this point.
thread_2()

edit: I'm assuming that by "thread" you mean a piece of code (otherwise known as a subroutine or a function). If you're talking about threads as in parallel execution then you'll need more detail in the question.

Upvotes: 6

Martin Kosek
Martin Kosek

Reputation: 398

Python is designed to support good coding practices and GOTO is not one of them. It may lead to unreadable program logic, if not used properly.

I suggest to learn code your program in a Python way, do not stick with (sometimes bad) habits from other programming languages. See Python documentation, real mature Python programs and learn.

Upvotes: 2

Related Questions