3-1 姓名:将一些朋友的名字存储到一个列表中,命名为names,再依次打印出来
names = ['Mary', 'Mike', 'Tom', 'Jerry']
for name in names:
print(name)
可以看到,运行代码后出现了如下文字:
Mary
Mike
Tom
Jerry
3-2 问候语:列表与3-1相同,但是不只打印姓名,而是为每人打印一条问候语
names = ['Mary', 'Mike', 'Tom', 'Jerry']
for name in names:
print(name + ", How are you?")
可以看到,运行代码后出现了如下文字:
Mary, How are you?
Mike, How are you?
Tom, How are you?
Jerry, How are you?
3-4 嘉宾名单:
list = ['Hitler', 'Stalin', 'Tom']
for name in list:
print(name + ", I'd like to invate you for a dinner.")
可以看到,运行代码后出现了如下文字:
Hitler, I'd like to invate you for a dinner.
Stalin, I'd like to invate you for a dinner.
Tom, I'd like to invate you for a dinner.
3-5 修改嘉宾名单:
list = ['Hitler', 'Stalin', 'Tom']
for name in list:
print(name + ", I'd like to invate you for a dinner.")
absence = 'Tom'
print(absence + " could not come.")
list.remove(absence)
list.append("Jerry")
for name in list:
print(name + ", I'd like to invate you for a dinner.")
可以看到,运行代码后出现了如下文字:
Hitler, I'd like to invate you for a dinner.
Stalin, I'd like to invate you for a dinner.
Tom, I'd like to invate you for a dinner.
Tom could not come.
Hitler, I'd like to invate you for a dinner.
Stalin, I'd like to invate you for a dinner.
Jerry, I'd like to invate you for a dinner.
3-6 添加嘉宾:
list = ['Hitler', 'Stalin', 'Tom']
for name in list:
print(name + ", I'd like to invate you for a dinner.")
print("I find a bigger table")
list.insert(0, "Jerry")
list.insert(2, "John")
list.append("Mary")
for name in list:
print(name + ", I'd like to invate you for a dinner.")
可以看到,运行代码后出现了如下文字:
Hitler, I'd like to invate you for a dinner.
Stalin, I'd like to invate you for a dinner.
Tom, I'd like to invate you for a dinner.
I find a bigger table
Jerry, I'd like to invate you for a dinner.
Hitler, I'd like to invate you for a dinner.
John, I'd like to invate you for a dinner.
Stalin, I'd like to invate you for a dinner.
Tom, I'd like to invate you for a dinner.
Mary, I'd like to invate you for a dinner.
4-3 数到20
for x in range(1, 21):
print(x)
可以看到,程序运行后打印了1到20的整数
4-4 一百万
for x in range(1, 1000001):
print(x)
可以看到,程序运行后打印了1到一百万的整数
4-5 计算一到一百万的总和
sum = 0
for x in range(1, 1000001):
sum += x
print(sum)
计算结果
500000500000
4-6 奇数
list = [x for x in range(1, 21, 2)]
for x in list:
print(x)
可以看到,运行代码后出现了如下文字:
1
3
5
7
9
11
13
15
17
19
4-8 立方
list = [x**3 for x in range(1, 11)]
for x in list:
print(x)
可以看到,运行代码后出现了如下文字:
1
8
27
64
125
216
343
512
729
1000