2021-04-13

第三次日报

循环

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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值