例如,我们可以执行以下脚本吗
A=4
B=3
K=4*c
C=a+b
打印k
不会出现名称错误(因为c是在第4行中定义的,但在第3行中被调用),即,首先应该执行第4行,然后执行第三行。
# 回答1
在Python中没有"GOTO"语句。因此,程序无法知道您希望它采用什么其他执行路径。
# 回答2
真正的问题是,你为什么想让它这样做?也许还有其他办法。但简短的回答是"不"。
# 回答3
如果你这样做是可能的:
- >>> a=4
- >>> b=3
- >>> k='4*c'
- >>> c=a+b
- >>> print eval(k)
- 28
# 回答4
啊,@bvdet,我喜欢。通过将所有行设置为字符串并使用exec命令,您可以进一步执行此操作。如果可能,您可以在Try Expect结构中执行此操作,以便使顺序正确。
就像这样:
- 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
这提供了:
- 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
- >>>