By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,100 Members | 2,892 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,100 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.
Oct 20 '10 #1
Share this Question
Share on Google+
4 Replies

Expert 100+
P: 624
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.
Oct 21 '10 #2

Expert 100+
P: 391
The real question is why do you want it to do this? Maybe there's another way. But the short answer is "no"
Oct 25 '10 #3

Expert Mod 2.5K+
P: 2,851
It's possible if you do it like this:
Expand|Select|Wrap|Line Numbers
  1. >>> a=4
  2. >>> b=3
  3. >>> k='4*c'
  4. >>> c=a+b
  5. >>> print eval(k)
  6. 28
Oct 25 '10 #4

Expert 100+
P: 391
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:
Expand|Select|Wrap|Line Numbers
  1. commands=['a=4','b=3','k=4*c','c=a+b']
  3. j=0
  4. while True:
  5.     i=len(commands)
  6.     if i==0:
  7.         print "All commands executed"
  8.         break
  9.     if j>1000:
  10.         print "Unable to resolve commands"
  11.         break
  12.     try:
  13.         exec(commands[j%i])
  14.         print commands[j%i], 'was executed successfully'
  15.         commands=commands[:(j%i)]+commands[(j%i)+1:]  #remove executed command
  16.     except:
  17.         print commands[j%i], 'not yet executed'
  18.         j+=1
which gives:
Expand|Select|Wrap|Line Numbers
  1. a=4 was executed successfully
  2. b=3 was executed successfully
  3. k=4*c not yet executed
  4. c=a+b was executed successfully
  5. k=4*c was executed successfully
  6. All commands executed
  7. >>> 
Oct 26 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.