(一)將 Python 當做計算器
①除法 (/
)永遠返回一個浮點數。 floor 除法可以使用 //
運算符得到整數結果(丟掉任何小數部分);要計算餘數你可以使用 %
PS:Python的命令行交互工具IDLE可以將文本打印,快捷鍵:CTRL+P贊
- >>> 7/3
- 2.3333333333333335
- >>> 7//3
- 2
- >>> 7%3
- 1
- >>> 7%%3
- SyntaxError: invalid syntax
- >>>
②乘法通過 Python,還可以使用 **
運算符計算冪乘方
- >>>
- 5**2
- 25
③賦值=和C一樣還是賦值操作。變量在使用前必須 “定義”(賦值),否則會出錯,浮點數有完整的支持;整數和浮點數的混合計算中,整數會被轉換爲浮點數:
>>> 7.0 / 23.5
④數據類型:除了 int 和 float,Python 還支持其它數字類型,例如 Decimal 和 Fraction。Python 還內建支持 複數,使用後綴 j
或 J
表示虛數部分(例如,3+5j
)。
⑤字符串Python 也提供了可以通過幾種不同方式表示的字符串,單引號'...'和雙引號"...",\可以用來轉義。
- >>> '我是通哥'
- '我是通哥'
- >>> "我是通哥"
- '我是通哥'
- >>> print('我是通哥')
- 我是通哥
- >>> print("我是通哥")
- 我是通哥
- >>>
示例2
- >>> s='"通哥最帥,妹子都喜歡他",這是他自己說的'
- >>> print(s)
- "通哥最帥,妹子都喜歡他",這是他自己說的
- >>>
示例3
- >>> print('通哥的好東西(嘿嘿嘿)都放在C:\some\name')
- 通哥的好東西(嘿嘿嘿)都放在C:\some
- ame
- >>> print(r'通哥的好東西(嘿嘿嘿)都放在C:\some\name')
- 通哥的好東西(嘿嘿嘿)都放在C:\some\name
- >>>
示例4 打印一段字符串可以使用 三引號 ① """..."""②'''...'''
print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
輸出:
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
示例5 字符串拼接 +
>>> 3 * 'un' + 'ium' 'unununium'相鄰的兩個字符串文本自動連接在一起。:
>>> 'Py' 'thon' 'Python'
- >>> a='Py'
- >>> b='thon'
- >>> print(a+b)
- Python
- >>> print(3*a+b)
- PyPyPython
這個功能在你想切分很長的字符串的時候特別有用:
>>> text = ('Put several strings within parentheses '
'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
⑥字符串與數組
>>> word = 'Python' >>> word[0] # character in position 0 'P' >>> word[5] # character in position 5 'n'
索引也可以是負數,這將導致從右邊開始計算。例如:
>>> word[-1] # last character 'n' >>> word[-2] # second-last character 'o' >>> word[-6] 'P'除了索引,還支持 切片,不包含末尾的字符。
>>> word[0:2] # characters from position 0 (included) to 2 (excluded) 'Py' >>> word[2:5] # characters from position 2 (included) to 5 (excluded) 'tho'
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
切片的索引有非常有用的默認值;省略的第一個索引默認爲零,省略的第二個索引默認爲切片的字符串的大小。
⑦ 內置函數 len() 返回字符串長度:
>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34
⑧ 列表
Python 有幾個 複合 數據類型,用於表示其它的值。最通用的是 list (列表) ,它可以寫作中括號之間的一列逗 號分隔的值。列表的元素不必是同一類型:
>>> list=[1,25,23.6,12,45,56]>>> list[2]
23.6
>>> list[1:]
[25, 23.6, 12, 45, 56]
>>>
不像 不可變的 字符串,列表是 可變的,它允許修改元素: append方法
cubes = [1, 8, 27, 65, 125]
>>> cubes.append(216) # add the cube of 6 >>> cubes.append(7 ** 3) # and the cube of 7 >>> cubes [1, 8, 27, 64, 125, 216, 343]