條件表達式: if 1>2:print(111) elif 2>3:print(222) else:print(333) for循環: for i in range(3,10): print(i) 輸出結果:for循環,步長為2 for i in range(1,10,2): print(i)
輸出結果:
想打印到一行的話,print加一個end參數,如:print(i,end="")即可
打印引用內容: name = "王路飛" s = f"我是海賊{name}" print(s)
結果:
反轉字符串:
s = "123456" print(s[::-1])
結果:
去除字符串前後空格:
username = " admin " realrm= username.strip(); print(realrm) print(len(username)) print(len(realrm))
結果:
修改變量:
"""
global:局部修改全局變量
nonlabal:在局部引入外層的局部變量
"""
a = 10
def func():
global a #修改全局變量需要global
a = 20
func()
print(a)
def func1():
a = 10
def func2():
nonlocal a #向上一層找有沒有該變量,沒有繼續向上一層找,直到最外層(不到全局)
a = 20
func2()
print(a)
func1()
結果:20
20
數組添加移除元素:
list = []
list.append("aaa")
list.append("bbb")
list.insert(1,"111") #指定位置插入指定的字符串
print(list)
result = list.pop(1) #移除下標為1的字符串
print(list) #打印移除後的list
print(result) #打印移除的字符
結果:
數組循環:
list=["1a","2b","3c"]
for i in range(len(list)):#循環0-list長度的的下標
print(i,end="")
print()
for item in list:#循環list中的元素
print(item,end="")
結果:
字典取值遍歷:
dict = {"key":1,"key2":"11"}
print(dict.get("key"))
print(dict["key2"])
#遍歷字典
for key in dict :#遍歷key,根據key拿vaules
print(key,dict.get(key))
print(list(dict.keys()))#拿到所有的key
for key,values in dict.items():
print(key,values)
結果:
元素互換位置:
a = 10
b = 20
a,b = b,a
print(a)
print(b)
結果: 20
10
判斷元素出現次數:
lst = ["a","b","c","a","a"]
print(lst.count("a"))
結果:3
計算從0-100的和:
print(sum(range(0,101)))
結果:5050
打印99乘法表:
def write99():
for i in range(1, 10):
for j in range(1, i+1):
print(f"{i}*{j}={i*j}",end=" ")
print()
write99()
結果:
從小到大排序:
def bigToSimal(arr):
for i in range(1,len(arr)):
for j in range(0,len(arr)-i):
if arr[j] < arr[j+1]:
temp = arr[j+1]
arr[j+1] = arr[j]
arr[j] = temp
return arr
arra = [2, 5, 8, 1, 3]
print(bigToSimal(arra))
結果:[8, 5, 3, 2, 1]
裝飾器:
def guanjia(game):
def inner():
print("打開科技")
game()
print("關閉科技")
return inner
@guanjia
def play_hali():
print('hello,hali')
@guanjia
def play_ys():
print("向著星辰與深淵")
play_ys()
結果:打開科技
向著星辰與深淵
關閉科技
# 通用裝飾器寫法
def wrapper(fn): #fn:目標函數
def inner(*args,**kwargs):
ret = fn(*args,**kwargs)
return ret
return inner