Python基礎方法使用例子&集合、列表、元組、字典的區別
print(“Hello World”)
型別轉換
#a = int(10)
#print(type(a))
輸入框+if判斷
# age = input("請輸入年齡:")
# age = int(age)
# if age>=18:
# print("python歡迎你")
# else:
# print("回家吃奶吧")
#有如下值集合[11,22,33,44,55,66,77,88,99,90], 將所有大於66的值儲存至字典的第一個key中,將小於66值儲存至第二個key的值
# li = [11,22,33,44,55,66,77,88,99,90]
# c = {">66":[],"<66":[]}
#
# for i in li:
# if i>66:
# c['>66'].append(i)
# else:
# c['<66'].append(i)
#
# print(c)
輸出商品列表,使用者輸入序號,顯示使用者選中的商品。
商品 li = [“手機”, “電腦”, “滑鼠墊”, “遊艇” ]
a. 允許使用者新增商品
b. 使用者輸入序號顯示內容
#li = ["手機", "電腦", "滑鼠墊", "遊艇" ]
shop = input("請輸入您想加入的商品:")
li.append(shop)
#print("商品現有",li)
# num = int(input("請輸入序號:"))
# print(li[num])
if巢狀
# k = input("是否攜帶違禁物品(0,沒有;1,攜帶)") # if int(k) == 1: # print("銬起來帶走") # else: # print("放行") # name = input("請出示您的身份證") # if name == 'monkey': # print('welcome to plane') # else: # print('stop')
and 和 |的使用
# a = input('1:餓了 , 2:不餓')
# b = input('輸入支付餘額')
# if a == '1' and int(b) >=10:
# print("給您準備飯菜")
# else:
# print("沒錢可吃不了飯呢,親!")
# a = input("請輸入數字a:")
# a = int(a)
# if a > 3 | a<10:
# #輸出大於3小於10的數字
# print(a)
# else:
# #否則輸出null
# print('null')
not的使用
# a = input("請輸入數字a:")
# #轉換數字型別
# a = int(a)
# if not a>3:
# #輸出的是小於3的數字
# print(a)
# else:
# #沒有則輸出Null
# print('Null')
下標索引展示
#s = 'world'
#print(s[0])
輸出為w
替換練習,將空格替換為,
# s = 'I can use python'
# #通過重新賦值改變s的值
# s = s.replace(' ',',')
# print(s)
分割練習
# s = 'I can use python'
# l = s.split()
# print(l)
列表便利迴圈+type顯示
# l = ['1',20,'hello world']
# for i in l:
# print(i,type(i))
#列表修改元素
#append 在列表末尾新增元素a
#insert(1,a) 將元素插入到下標為1的位置
#extend(a) 將元素a中的每個成員依次新增到列表中
# l = []
# #按照順序新增元素
# l.extend('python')
# print(l)
# l.extend('isok')
# print(l)
# #在列表末尾新增元素
# l.append('justsoso')
# print(l)
# #將哈哈新增至下表索引為3的位置
# l.insert(3,'哈哈')
# print(l)
#刪除
#pop()預設刪除列表最後一個元素
#pop(i) 刪除下標索引為i的元素
#remove(a) 刪除值為a的元素,不存在報錯
#del a 將變數a刪除
# l = [1,'哈哈哈',123,'嘻嘻嘻']
#刪除最後一個元素
# l.pop()
# print(l)
#刪除指定下表索引元素
# l.pop(0)
# print(l)
#刪除值為a的元素
# l.remove('哈哈哈')
# print(l)
#將變數a刪除
# del l[1]
# print(l)
#返回下標索引
#index:存在,返回下標,不存在報錯
#in 存在 true 不存在 false
#not in 不存在 true 存在 false
#count 統計出現的次數
#l = [1,'哈哈哈',123,'嘻嘻嘻','哈哈哈','哈哈哈']
# print(l.index('哈哈哈'))
# print(l.count('哈哈哈'))
#常用函式
#求元素個數:len()
#求最大值:max()
#求最小值:min()
#求列表中所有數字和:sum()
#排序(預設從小到大):
#sore()從小到大
#sort(reverse=true) 從大到小
#反轉不排序 reverse()
#l = [1,'哈哈哈',123,'嘻嘻嘻']
#l.reverse()
#print(l)
# l = [1,2,3,10,5,6,7]
#True首字母必須大寫
# l.sort(reverse=True)
# print(l)
# print(sum(l))
# print(max(l))
# print(min(l))
# print(len(l))
#元組tuple
#元組不能增刪改其中資料,但是可以直接刪除整個元組
index 按照值去查詢,存在返回下標,不存在則報錯
count 存在時返回存在的數量,不存在,返回()
in 判斷是否在其中,在為true 不在為false
#not in 判斷是否不在其中,不在為true 在為false
# a = (1,2,3,4,4)
# print(a.index(2))
# print(a.count(4))
#字典
#{鍵:值},兩者合稱為鍵值對,多個鍵值對之間’,'隔開,鍵不能重複
z = {'name': '賈雨村', 'age': '48', 'sex': '男',
'name1': '賈寶玉', 'age2': '22', 'sex3': '男', }
# for i, j in z.items():
# print(i, j)
print(z)
z['name']='寂寞'
print(z)
z['age']= 0
print(z)
z['sex'] = '女'
print(z)
del z['name']
print(z)
del z
集合、列表、元組、字典的區別: