[Lab] Python 語法亂筆記2


<檔案處理>
設一個變數 file 來接

file = open('test.txt') #開檔

file.close()  # 關檔

<目錄管理>
要操作檔案目錄的話要將os library import進來
import os
os.getcwd()  #取得目前工作目錄位子

os.chdir(' ') # change director 到 ' 指定路徑 ' 中

<情境:開檔後用readline()讀取檔案一行的內容>
data = open('test.txt')  # 設一個變數接開檔
print(data.readline(), end = '')  #  讀取檔案中的一整行後印出,結尾不自動換行
data.seek(0) # 檔案讀寫pointer回到檔案的開頭!

<and, or, not>
python 的比較運算裡面,可以很直觀的使用and or not關鍵字來做布林運算,
這三的運算子同時放在一起的時候,會有運算先後順序之分
順序如下
1. not
2. and
3. or
例如
True or not False and False
這樣會還傳 True 
加上括弧來解釋如下
True or ((not False) and False)
因為 not 是第一順位所以先做 not false 成 true
然後是第二順位運算 and
true and false 得到結果是 false
最後是or運算
true or flase 結果是 true
所以最後結果為 true !!!

<function>
python 的 fuction 這樣寫:
def funciton_name:
      直接用縮排來取代block,放置function內容
例子
寫一個計算次方的function

 37^4 = 1874161

<if else>
python 的 else if 要這樣寫 elif
if... elif... else

<isalpha()>
這個function會判斷是否是文字
例如
k = "12345"
k.isalpha() --> 會 False!


<字串處理 substring>
Python的字串要直接做substring非常的直觀
例如
s = "abcdefg"
要拿第一個位置字母 a 就直接這樣寫: s[0]
如果是
s[1:4] 就會得到 "bcd" (從 s[1] 開始到  s[4] 之前 不包含s[4]的substring )

<sqrt()開平方根與import大小事>
要記得import math
這種import 稱之為 generic import
把整個math library都import進來
如果是這種:
from math import sqrt
稱之為function import 
會直接把sqrt加進來,可以直接呼叫不需加上math.sqrt()
但如果原本code裡面已經有寫了一種sqrt就會被覆蓋掉

若是這種:from math import * 稱之為 universal import
會把math library裡面的所有function import近來可直接用

下列的code會印出math裡面所有的function


留言

這個網誌中的熱門文章

[筆記] CRLF跟LF之區別 --- 隱形的 bug

[ML筆記] Batch Normalization

[筆記] 統計實習(1) SAS 基礎用法 (匯入資料並另存SAS新檔,SUBSTR,計算總和與平均,BMI)

[ML筆記] Ensemble - Bagging, Boosting & Stacking