第三次日报
循环
if循环
a = 1
if a == 1:
print("True")
elif a == 2:
pass # 占位
else:
print("False")
i = 0
print("True") if i == 0 else print ("False")
运行结果:
True
True
for循环
test_list = [1, 2, 3, 4, 5, 6, 7]
for l in test_list: # l:迭代器 用来遍历 in 后面的列表、元组、字符串、字典等里面的元素
print(l)
for l in range(7):
print(test_list[l])
# 列表推导式
test = [l for l in test_list]
print(test)
print([l for l in test_list])
运行结果:
1
2
3
4
5
6
7
1
2
3
4
5
6
7
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
while循环
i = 0
test_list = [1, 2, 3, 4, 5, 6, 7]
while i < len(test_list):
print(test_list[i])
i += 1
# 死循环
'''
while 1:
print(1)
'''
运行结果:
1
2
3
4
5
6
7
replace函数
replace()方法语法:
str.replace(old, new[, max])
old – 将被替换的子字符串。
new – 新字符串,用于替换old子字符串。
max – 可选字符串, 替换不超过 max 次
返回值:返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。
str1 = "hello python"
print("替换前:", str1)
print("替换后:", str1.replace("python", "world"))
运行结果:
替换前: hello python
替换后: hello world
count函数实现
count()方法语法:
str.count(sub, start= 0,end=len(string))
sub – 搜索的子字符串 start – 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
end --字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
返回值:该方法返回子字符串在字符串中出现的次数。
str1 = "hello world"
print(str1.count("l", 1, 5))
print(str1.count("l"))
运行结果:
2
3
打印杨辉三角
杨辉三角定义:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
代码:
def triangles():
L = [1] #定义L为一个只包含一个元素的列表
while True:
yield L #定义为生成器函数
L =[1] + [L[n] + L[n-1] for n in range(1,len(L))] + [1]
n = 0
for t in triangles():
print(t)
n = n + 1
if n == 10:
break
运行结果:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]