是否有任何方法可以使python语句的执行无序

例如,我们可以执行以下脚本吗
A=4
B=3
K=4*c
C=a+b
打印k
不会出现名称错误(因为c是在第4行中定义的,但在第3行中被调用),即,首先应该执行第4行,然后执行第三行。

# 回答1


在Python中没有"GOTO"语句。因此,程序无法知道您希望它采用什么其他执行路径。
# 回答2


真正的问题是,你为什么想让它这样做?也许还有其他办法。但简短的回答是"不"。
# 回答3


如果你这样做是可能的:

选择 | 换行 | 行号
  1. >>> a=4
  2. >>> b=3
  3. >>> k='4*c'
  4. >>> c=a+b
  5. >>> print eval(k)
  6. 28
# 回答4


啊,@bvdet,我喜欢。通过将所有行设置为字符串并使用exec命令,您可以进一步执行此操作。如果可能,您可以在Try Expect结构中执行此操作,以便使顺序正确。
就像这样:

选择 | 换行 | 行号
  1. commands=['a=4','b=3','k=4*c','c=a+b']
  2.  
  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

这提供了:

选择 | 换行 | 行号
  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. >>> 

标签: python

添加新评论