python學習筆記5

2022-07-22 21:21:31 字數 4473 閱讀 7630

python可以寫入py檔案,還可以直接執行檔案

%%writefile ex1.py

pi = 3.1416

def sum(lst):

tot = lst[0]

for value in lst[1:]:

tot = tot + value

return tot

w = [0, 1, 2, 3]

print sum(w), pi

%run ex1.py
當然我還可以直接import這個檔案

import ex1

print ex1.pi

reload(ex1)

# 重新載入ex1,這樣可以重新

import os

os.remove('ex1.py')

# 刪除這個檔案

有時候我們想將乙個.py檔案既當作指令碼,又能當作模組用,這個時候可以使用__name__這個屬性。

只有當檔案被當作指令碼執行的時候,__name__的值才會是'__main__',所以我們可以:

if __name__ == '__main__':
假設我們有這樣的乙個資料夾:

foo/

匯入包要求:

似乎python3裡面是不需要寫東西的

python2需要寫import bar, baz

介紹下異常

下面這個函式如果是負數,那麼會有bug

import math

while true:

text = raw_input('> ')

if text[0] == 'q':

break

x = float(text)

y = math.log10(x)

print "log10() = ".format(x, y)

我們可以用try

import math

while true:

try:

text = raw_input('> ')

if text[0] == 'q':

break

x = float(text)

y = math.log10(x)

print "log10() = ".format(x, y)

except valueerror:

print "the value must be greater than 0"

import math

while true:

try:

text = raw_input('> ')

if text[0] == 'q':

break

x = float(text)

y = 1 / math.log10(x)

print "1 / log10() = ".format(x, y)

except exception:

print "invalid value"

import math

while true:

try:

text = raw_input('> ')

if text[0] == 'q':

break

x = float(text)

y = 1 / math.log10(x)

print "1 / log10() = ".format(x, y)

except (valueerror, zerodivisionerror):

print "invalid value"

import math

while true:

try:

text = raw_input('> ')

if text[0] == 'q':

break

x = float(text)

y = 1 / math.log10(x)

print "1 / log10() = ".format(x, y)

except valueerror:

print "the value must be greater than 0"

except zerodivisionerror:

print "the value must not be 1"

# 這樣就可以像if elif一樣

import math

while true:

try:

text = raw_input('> ')

if text[0] == 'q':

break

x = float(text)

y = 1 / math.log10(x)

print "1 / log10() = ".format(x, y)

except valueerror as exc:

if exc.message == "math domain error":

print "the value must be greater than 0"

else:

print "could not convert '%s' to float" % text

except zerodivisionerror:

print "the value must not be 1"

except exception as exc:

print "unexpected error:", exc.message

當我們使用except exception時,會捕獲所有的exception和它派生出來的子類,但不是所有的異常都是從exception類派生出來的,可能會出現一些不能捕獲的情況,因此,更加一般的做法是使用這樣的形式:

try:

pass

except:

pass

這樣不指定異常的型別會捕獲所有的異常,但是這樣的形式並不推薦。

我們還可以使用finally,就是不管怎麼樣,都會執行

try:

print 1 / 0

except zerodivisionerror:

print 'divide by 0.'

finally:

print 'finally was called.'

有些情況下,我想讓程式繼續執行,然後我又需要使用者知道以下事情

import warnings

def month_warning(m):

if not 1<= m <= 12:

msg = "month (%d) is not between 1 and 12" % m

warnings.warn(msg, runtimewarning)

month_warning(13)

warnings.filterwarnings(action = 'ignore', category = runtimewarning)

month_warning(13)

下面介紹下io操作

寫入測試檔案:

%%writefile test.txt

this is a test file.

hello world!

python is good!

today is a good day.

讀檔案

f = open('test.txt')

f = file('test.txt')

text = f.read()

print text

f = open('test.txt')

lines = f.readlines()

print lines

# readlines 方法返回乙個列表,每個元素代表檔案中每一行的內容:

f.close()

寫檔案

f = open('myfile.txt', 'w')

f.write('hello world!')

f.close()

print open('myfile.txt').read()

f = open('myfile.txt', 'w+')

f.write('hello world!')

f.seek(6)

print f.read()

f.close()

# seek就是移動到第4個字元

Python 學習筆記 5

今天從25章開始 p652 學習 python 的 oop 用 看起來更直觀 class class a def init self,value 建構函式 self.data value def add self,other 運算子過載 return class a self.data other ...

Python學習筆記5

列表與元組的區別 sort sort reverse true 對元素進行排序,預設是公升序,小值在前面,後面那種形式是降序,小值在後面 reverse 反轉列表的順序 count value 返回value的出現次數 index value 返回value第一次出現的位置編號 insert i,v...

Python學習筆記 5

模組 用來從邏輯上組織python 包括變數,函式,類,邏輯等,來實現乙個功能。本質就是乙個python檔案。包 從邏輯上組織模組。必須帶有乙個init.py檔案 匯入方式 import module import module1,module2 from module import 不建議用 fr...