python進階(一)變數與資料型別、python之禪

Mrwhite86發表於2021-04-14

一、變數:

1、變數組成

必須由資料、字母與下劃線組合

不能以數字開頭

python關鍵字與函式名不能作為變數名

2、含引號的字串變數

當字串變數中包含引號時,可使用單引號與雙引號進行區分,或轉義

print("python is 'ok'")
print('my name is "Mr.white"')
print("java is \"ok\"")

檢視結果

python is 'ok'
my name is "Mr.white"
java is "ok"

3、製表符與換行符

print('python')
print('\tjava\n\tgolang')

檢視結果

python
    java
    golang

4、大小寫

 

myTest='abcdEFG'
print(myTest.upper())
print(myTest.lower())
print(myTest.title())

 

檢視結果

ABCDEFG
abcdefg
Abcdefg

 

 

5、f表示式:

作用:字串中使用變數,任意位置拼接

firstName='ada'
lastName='lovepeace'
fullname=f'{firstName} {lastName}'
print(fullname)

檢視結果

ada lovepeace

6、刪除空白

text="   this is a stripTest  "
print(f"'{text.lstrip()}'")
print(f"'{text.rstrip()}'")
print(f"'{text.strip()}'")

檢視結果

'this is a stripTest  '
'   this is a stripTest'
'this is a stripTest'

 

二、資料型別

1.整形與浮點型的計算

print(4/2)
print(4//2)
print(1+2)
print(1+2.0)
print(1200_000_00)

檢視執行結果

2.0
2
3
3.0
120000000

 

三、常量

全大小形式:

MAX_OK="HELLO WOLRD"

 

四、註釋

#this is and helpNote

 

五、python之禪

import this

檢視結果:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

翻譯如下:

Python之禪 by Tim Peters
 
優美勝於醜陋(Python 以編寫優美的程式碼為目標)
明瞭勝於晦澀(優美的程式碼應當是明瞭的,命名規範,風格相似)
簡潔勝於複雜(優美的程式碼應當是簡潔的,不要有複雜的內部實現)
複雜勝於凌亂(如果複雜不可避免,那程式碼間也不能有難懂的關係,要保持介面簡潔)
扁平勝於巢狀(優美的程式碼應當是扁平的,不能有太多的巢狀)
間隔勝於緊湊(優美的程式碼有適當的間隔,不要奢望一行程式碼解決問題)
可讀性很重要(優美的程式碼是可讀的)
即便假借特例的實用性之名,也不可違背這些規則(這些規則至高無上)
 
不要包容所有錯誤,除非你確定需要這樣做(精準地捕獲異常,不寫 except:pass 風格的程式碼)
 
當存在多種可能,不要嘗試去猜測
而是儘量找一種,最好是唯一一種明顯的解決方案(如果不確定,就用窮舉法)
雖然這並不容易,因為你不是 Python 之父(這裡的 Dutch 是指 Guido )
 
做也許好過不做,但不假思索就動手還不如不做(動手之前要細思量)
 
如果你無法向人描述你的方案,那肯定不是一個好方案;反之亦然(方案測評標準)
 
名稱空間是一種絕妙的理念,我們應當多加利用(倡導與號召)

 

相關文章