There are two types of loop, for and while.
1、for value in iterable: #可迭代的
# code you want to execute
range经常和for连用,range表示一个范围,syntax:range(start,end,step)
例子:
1、阶乘
numbers = [4, 17, 9, 5, 7, 1, 6, 9, 3, 3, 13]
i=1
for number in numbers:
i=number*i
print(i)
2、遍历
X = "HUOBAOKEKE"
for i in range(len(X)):
print(X[i])
输出的结果是这个字符串每个字母都挨个输出。
2、while condition:
# code that executes while condition is true
例子:写一个程序,需要不停读取使用者需要购买的东西,并把这些信息加入一个list中,当使用者输入空白时输出list。
fruit = input("What do you need to buy?\n")
list_f = []
while fruit != "":
list_f.append(fruit)
fruit = input()
print(list_f)