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
+ 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
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 >>> a=4 >>> b=3 >>> k='4*c' >>> c=a+b >>> print eval(k) 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 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: Expand|Select|Wrap|Line Numbers 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 >>>  Oct 26 '10 #5

### Post your reply

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