Is there any way in which the execution of python statements can be made out of order

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mohd Khan

    Is there any way in which the execution of python statements can be made out of order

    For example, can we execute the following script

    a = 4
    b = 3
    k = 4 * c
    c = a + b
    print k

    without getting a name error(since c is defined in the 4th line but called for in the 3rd line) i.e. first the 4th line should get executed then the third.
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    first the 4th line should get executed then the third.
    There are no "goto" statements in Python. So there is no way for the program to know what other execution path you wish it to take.

    Comment

    • Glenton
      Recognized Expert Contributor
      • Nov 2008
      • 391

      #3
      The real question is why do you want it to do this? Maybe there's another way. But the short answer is "no"

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        It's possible if you do it like this:
        Code:
        >>> a=4
        >>> b=3
        >>> k='4*c'
        >>> c=a+b
        >>> print eval(k)
        28

        Comment

        • Glenton
          Recognized Expert Contributor
          • Nov 2008
          • 391

          #5
          Ah, @bvdet, I like it. You could take this further, by making all the lines strings and using the exec command. You could do it inside a try except structure, so that the order is made correct, if possible.

          Like this:
          Code:
          commands=['a=4','b=3','k=4*c','c=a+b']
          
          j=0
          while True:
              i=len(commands)
              if i==0:
                  print "All commands executed"
                  break
              if j>1000:
                  print "Unable to resolve commands"
                  break
              try:
                  exec(commands[j%i])
                  print commands[j%i], 'was executed successfully'
                  commands=commands[:(j%i)]+commands[(j%i)+1:]  #remove executed command
              except:
                  print commands[j%i], 'not yet executed'
                  j+=1
          which gives:
          Code:
          a=4 was executed successfully
          b=3 was executed successfully
          k=4*c not yet executed
          c=a+b was executed successfully
          k=4*c was executed successfully
          All commands executed
          >>>

          Comment

          Working...