python基础---元组、字典、函数、文件、异常
文章目錄
- python基礎---元組、字典、函數、文件、異常
- Tuple(元組)
- 常用操作
- dict(字典)
- 函數
- 文件
- 異常
python基礎—元組、字典、函數、文件、異常
Tuple(元組)
tuple的元素不能修改
tuple寫在小括號里 ,
只有一個元素的tuple也要加上 “,”
tup1=(1)
tup2=(2,)
print(type(tup1))
print(type(tup2))#只有一個元素后必須加 , 才能被認為是元組
#<class 'int'> tup1類型
#<class 'tuple'> tup2類型
tup3=(1,2,3,4,5,6,7,8,9)
print(tup3[1:5])#2.3.4.5#增
tup=tup3+tup2
print(tup)#創造了一個新元組,
常用操作
訪問元組中的元素 下標直接訪問 print(tup1[2])
遍歷元組 for for i in tup1:print(i)
元組的切片 使用[::] tup1[2:5:2]
加法操作
元組成員關系 in 2 in list1
得到重復元素數量 count tup1.count(1)
獲取元組長度 len()
獲取元組元素最大值 max()
獲取元組元素最小值 min()
其他類型對象轉換成元組 tuple()
dict(字典)
字典是無序對象的集合,使用鍵-值(key-value)存儲,具有極快的查找速度。
鍵(key)必須使用不可變類型
同一個字典中,鍵(key)必須是唯一的
#字典的定義
info={"name":"lj","age":18}#字典的訪問
print(info["name"])
print(info["age"])#訪問了不存在的鍵
#print(info["grade"])
#直接訪問報錯
print(info.get("grade","nam"))#使用get方法沒有找到對應的鍵則返回默認值“nam”
print(info.get("name",19))#結果為18,而不是19,在字典中有“name”
增
info["id"]="newId"
print(info["id"])
刪
print("刪除前:%s"%info["name"])
del info ["name"]
# del info#輸出為空白,但不會報錯
# print(info)
info.clear()#輸出含{}
# clean (info)#輸出會報錯,
print(info)
改
info2={"name":"lj","age":18}
info2["age"]=20
print(info2["age"])#結果:20
查(遍歷)
info2={"name":"lj","age":18}
print(info2.keys())#dict_keys(['name', 'age'])#得到所有的鍵(列表)print(info2.values())#dict_values(['lj', 18])#得到所有的值(列表)print(info2.items())#dict_items([('name', 'lj'), ('age', 18)])#每一個鍵值是一個元組#遍歷所有的鍵值對
for key,value in info2.items():print("key=%s,value=%s"%(key,value))#key=name,value=lj#key=age,value=18
函數
函數的定義
def printinfo():print("---------------")print("人生苦短,我用python")
printinfo()
帶參數的函數
def add2Num(a,b):c=a+bprint(c)add2Num(10,20)
帶返回值的函數
def add2Num1(a,b):return a+b
print(add2Num1(10,20))
返回多個值的函數
def divid(a,b):shang=a//byushu=a%breturn shang,yushu
print(divid(10,3))
def hengxian():x=(int(input("請輸入:")))a=random.randint(1,x)print(a)for i in range(1,a+1):print(i,"*"*i)hengxian()結果:
請輸入:15
5
1 *
2 **
3 ***
4 ****
5 *****
文件
f=open("test.txt","w")#打開文件,w模式(寫模式),文件不存在就新建
f.write("hello world,I'm here!")#將字符串寫入文件中```python
f=open("test.txt","r")#要再次確定文件打開方式,將上面的w模式改成r模式
f=open("test.txt","r")#要再次確定文件打開方式,將上面的w模式改成r模式content1 = f.read(5) #表示讀取單個字符print(content1)#hello
content1 = f.read(5)
print(content1)# worl 包括空格也當成一個字符讀取
# 會延續上面已讀的往下讀,而不會再次從頭開始讀
content1=f.readlines()#表示讀取整個一行文件
#readline與readlines不一樣,前者輸出還是一行
i=1
for temp in content1:print("%d:%s"%(i,temp))i+=1
# 包括空行也能輸出content2=f.readline()#在上面for循環中輸出為單個字符輸出,下面直接輸出則是只輸出一行
print(content2)
#同樣為延續輸出
f.close()#關閉文件
結果:
helloworl
1:d,I'm here!#只有一行,而且延續上面已讀
文件其他相關操作
1:文件重命名
import os
os.rename(”原名“,”現名“)
2:刪除文件:
import os
os.remove(”文件名“)
3:創建文件夾:
import os
os.mkdir(”文件名“)
4:獲取當前目錄:
import os
os.getcwd()
5:改變默認目錄:
import os
os.chdir("…/")
6:獲取目錄列表
import os
os.listdir("…/")
7:刪除文件:
import os
os.rmdir(“文件名”)
異常
import timetry:print("---1-------------------")f=open("123.txt","r")print("---2-------------------")except IOError:print("error")
#結果:---1-------------------
# error#try里面的第二句沒有執行
Exception可以捕獲所有異常
try:print(num)
except (IOError,NameError):#在括號中可以有多種可能出現的異常#異常想要被捕獲,需要與異常情況一致print("出現錯誤")
except Exception as result:#Exception可以捕獲所有異常print("產生錯誤")print(result)#name 'num' is not defined#輸出產生異常的原因
try…finally和嵌套
try:f = open("test.txt", "r")try:while True:content=f.readline()if len(content)==0:breaktime.sleep(2)print(content)finally:#如果可以執行到此代碼的第二個try,則finally一定會被執行f.close()print("關閉文件")
except Exception as result:print("發生異常")
#結果:
hello world,I'm here!hello world,I'm here!hello world,I'm here!hello world,I'm here!hello world,I'm here!hello world,I'm here!
關閉文件#finally被執行
總結
以上是生活随笔為你收集整理的python基础---元组、字典、函数、文件、异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python基础学习笔记--字符串、列表
- 下一篇: python基础--urllib