文章目录


1. 打印文件名

for i in range(0, 3):
m = f'name{i}'
print(m)

输出:

name0
name1
name2

2. 打印数字

for i in range(5,0,-1):
print(i)

输出:

5
4
3
2
1

while方法

i=5 
while(i > 0):
print(i)
i=i-1 #Decrementing

3. 创建动态变量,并给动态变量赋值

实例1

j = [10, 20, 30]
for i in range(0, 3):
m = f'name{i}'
exec(m + '= %s' % (j[i]))

print(name0)
print(name1)
print(name2)

输出结果:

10
20
30

实例2

value = [10, 20]
var = 'my_var'
expr = var + "= %s" % (value[1])
exec(expr)
print(my_var)

输出结果:

20

✈推荐阅读:

python range()函数_赋值