Python第31課到42課

2022-07-18 22:06:40 字數 2815 閱讀 2337

【python第31課到42課】

讀檔案f=file('data.txt')

data=f.read()

print data

f.close

其他用法

data.txt中存的內容是

hi my name is mike

helloworld!

當執行f=file('data.txt')

data=f.readlines() #把內容按行讀取至乙個list中 ,所有內容都讀出來了。

print data

f.close

結果['hi my name is mike\n', 'helloworld!']

當執行f=file('data.txt')

data=f.readline() #把內容讀取一行出來

print data

f.close

結果hi my name is mike

寫檔案開啟檔案有file()和open()兩種方法

用法一致

write示例

data='i will be in a file .\n so cool'

out = open ('output.txt','w')

out.write(data)

out.close()

data='\n add new data'

out = open ('output.txt','a')

out.write(data)

out.close()

處理檔案中的資料

統計總分

kk 23 34 23

jj 40 40 40 23

zz 99 99 11 11

gg 100

程式:f=file('data.txt')

lines=f.readlines()

#print lines

f.close()

results=

for line in lines:

#print line

data=line.split()

#print data

sum=0

for score in data[1:]:

sum+=int(score)

result='%s \t :%d\n' %(data[0],sum)

#print result

#print results

output=file('result.txt','w')

output.writelines(results)

output.close()

結果:kk :80

jj :143

zz :220

gg :100

break

例子1:

while true:

a=raw_input()

if a=='eof':

break

continue

類上異常處理

try...except

例子1:

try:

f=file('none-exist.txt')

print 'file opened'

f.close()

except:

print 'file not exist'

print 'done'

字典字典dictionary,基本格式(key健,value值)

注意1.健必須唯一

例子1:

score =

print score['kk']

輸出結果:

99用for...in遍歷

score =

for name in score:

print score[name]

結果:99

59100

注意,這裡的輸出結果的順序和score定義的順序不一樣了。

2.改score['kk']=18

3.增score['aa']=88

4.刪del score['kk']

5.空字典

score={}

模組from 模組名 import 方法名

例子1:

from random import randint

num = randint(1,10)

print num

例子2:

import random

num=random.randint(1,10)

print num

例子3:

檢視random有哪些函式和變數

dir(random)

例子4:

from math import pi

print pi

例子5:

給引入的方法換個名字

from math import pi as math_pi

print math_pi

【39-41】用檔案儲存遊戲

函式的預設引數

程式1:

def hello (name ='world'):

print 'hello'+name

hello()

hello('python')

結果:helloworld

hellopython

程式2:

def addfun(a,b=5):#def addfun(a=5,b=3)是錯誤的用法。預設引數必須在參數列的末尾

return a+b

c=addfun(3)

print c

結果:8

《笨辦法學Python》 第42課手記

本節課具體講類 class 涉及到定義以及定義後類內部函式的使用。前半部分原 如下 class thething object 類的宣告,object不能省略 def init self 這裡是in it的意思,即設定內部變數 self.number 0 defsome function self ...

《笨辦法學Python》 第42課手記

本節課具體講類 class 涉及到定義以及定義後類內部函式的使用。前半部分原 如下 class thething object 類的宣告,object不能省略 def init self 這裡是in it的意思,即設定內部變數 self.number 0 defsome function self ...

《笨辦法學Python》 第31課手記

本節課是一小段類似 龍與地下城 的遊戲的 是if語句巢狀的深入,即巢狀的if語句中又出現巢狀的if語句。理論上可以巢狀許多層,至於上限是多少,暫不清楚。原 如下 print you enter a dark room with two doors.do you go through door 1 o...