python笔记(备用)

for循环 99乘法表

for i in range (1,10):
    for j in range (1,i+1):
        print('%d X %d = %d\t'%(j,i,i*j),end='')
    print()

while循环会一直循环,if True 循环一次。

while True:
    print("一直打印")

a = 0         #先设置变量为了让while循环可以跳出循环执行。
while a<10:
    print(a)
    a +=1
i = 1
while i < 5:
    print("我是will")
    i +=1
else:
    print("条件满足时跳出")
n = int(input("请输入数字:"))
j = 1
while j <= n:
   i = 1
   while i <= j:
       print("*",end='')
       i +=1
   print()
   j +=1

个人理解while 外层控制 j<=n时候已经控制个高度,在内部使用变量和while循环打印内容

请输入数字:4
*
**
***
****

Process finished with exit code 0

pass:用于占位代码,

break:会终止带代码执行,

continue:终止控制的语句,执行后面操作

例如 continue为例:

i = "william"
for i in i:
    if i =='l':
       continue
    print(i,end='')

wiiam
Process finished with exit code 0

列表推倒式

#语法:[变量 for 变量 in 可迭代对象]
#未使用推倒式:
result2 = []
for i in range(10):
    result2.append(i)
print(result2)

#使用列表推倒式
result3 = [i for i in range(11)]
print(result3)

L = [[1,2,3],[4,5,6],[7,8,9]]
result=[i[0]for i in L]
print(result)
result1=[L[i][i] for i in range(len(L))]
print(result1)

copy

import copy
a = [1,2,3,4,[6,7,8],9]
b = a
print('a的id:%s,b的id%s'%(id(a),id(b)))
c = copy.copy(a)
d = copy.deepcopy(a)
a.append(10)
a[4].append(11)
print(b)
print(c)
print(d)

a的id:2193633568264,b的id2193633568264
[1, 2, 3, 4, [6, 7, 8, 11], 9, 10]
[1, 2, 3, 4, [6, 7, 8, 11], 9]
[1, 2, 3, 4, [6, 7, 8], 9]

Process finished with exit code 0

函数:是一个被重复调用的入口和出口固定程序段

减少冗余代码

代码结构清晰

保证代码一致性

猜你喜欢

转载自blog.csdn.net/zsw208703/article/details/89067740
今日推荐