python——用循环遍历列表

如果想要把列表中的值依次拿出来使用,或者依次输入,可以用for循环遍历列表。

1.写一段程序,让用户把整数输入到列表中,再把列表内的整数全部相乘。
numbers=[]  #定义一个空列表
total=int(input("输入列表内要有多少个整数:"))
for i in range(total):
	numbers.append(int(input("enter a number:")))
print(numbers)

运行程序,自己输入一些数据,对照输出是否正确。
在这里插入图片描述
然后,继续编写程序,把整个列表中的数相乘。

numbers=[]
result=1
total=int(input("输入列表元素的个数:"))

for i in range(total):
    numbers.append(int(input("输入一个数:")))
# i 为每个元素的下标
for i in range(total):
    result*=numbers[i]
print(result)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_46009608/article/details/115189399
今日推荐