python计算器基础知识_Python基础(一):将Python当做计算器、编程的第一步
我們來嘗試一些簡單的 Python 命令。啟動解釋器然后等待主提示符 >>> 出現(xiàn)(不需要很久)。1.1. 數(shù)字
解釋器表現(xiàn)得就像一個簡單的計算器:可以向其錄入一些表達式,它會給出返回值。表達式語法很直白:運算符 +,-,* 和 / 與其它語言一樣(例如:Pascal 或 C);括號 (()) 用于分組。例如:>>>2 + 24>>>50 - 5*620>>>(50 - 5*6) / 45.0>>>8 / 5??# division always returns a floating point number1.6
整數(shù)(例如,2, 4, 20 )的類型是 int,帶有小數(shù)部分的數(shù)字(例如,5.0, 1.6)的類型是float。在本教程的后面我們會看到更多關(guān)于數(shù)字類型的內(nèi)容。
除法(/)永遠返回一個浮點數(shù)。如要使用 floor 除法 并且得到整數(shù)結(jié)果(丟掉任何小數(shù)部分),你可以使用 // 運算符;要計算余數(shù)你可以使用 %>>>17 / 3??# classic division returns a float5.666666666666667>>>>>>17 // 3??# floor division discards the fractional part5>>>17 % 3??# the % operator returns the remainder of the division2>>>5 * 3 + 2??# result * divisor + remainder17
通過 Python,還可以使用 ** 運算符計算冪乘方 [1]:>>>5 ** 2??# 5 squared25>>>2 ** 7??# 2 to the power of 7128
等號( '=' )用于給變量賦值。賦值之后,在下一個提示符之前不會有任何結(jié)果顯示:>>>width = 20>>>height = 5*9>>>width * height900
變量在使用前必須 “定義”(賦值),否則會出錯:>>># try to access an undefined variable...nTraceback (most recent call last):??File "", line 1, in NameError: name 'n' is not defined
浮點數(shù)有完整的支持;整數(shù)和浮點數(shù)的混合計算中,整數(shù)會被轉(zhuǎn)換為浮點數(shù):>>>3 * 3.75 / 1.57.5>>>7.0 / 23.5
交互模式中,最近一個表達式的值賦給變量 _。這樣我們就可以把它當(dāng)作一個桌面計算器,很方便的用于連續(xù)計算,例如:>>>tax = 12.5 / 100>>>price = 100.50>>>price * tax12.5625>>>price + _113.0625>>>round(_, 2)113.06
此變量對于用戶是只讀的。不要嘗試給它賦值 —— 你只會創(chuàng)建一個獨立的同名局部變量,它屏蔽了系統(tǒng)內(nèi)置變量的魔術(shù)效果。
除了 int 和 float,Python 還支持其它數(shù)字類型,例如 Decimal 和 Fraction。Python 還內(nèi)建支持 復(fù)數(shù),使用后綴 j 或 J 表示虛數(shù)部分(例如,3+5j)。
1.2. 字符串
相比數(shù)值,Python 也提供了可以通過幾種不同方式表示的字符串。它們可以用單引號 ('...') 或雙引號 ("...") 標識 [2]。\ 可以用來轉(zhuǎn)義引號:>>>'spam eggs'??# single quotes'spam eggs'>>>'doesn\'t'??# use \' to escape the single quote..."doesn't">>>"doesn't"??# ...or use double quotes instead"doesn't">>>'"Yes," he said.''"Yes," he said.'>>>"\"Yes,\"he said."'"Yes," he said.'>>>'"Isn\'t," she said.''"Isn\'t," she said.'
在交互式解釋器中,輸出的字符串會用引號引起來,特殊字符會用反斜杠轉(zhuǎn)義。雖然可能和輸入看上去不太一樣,但是兩個字符串是相等的。如果字符串中只有單引號而沒有雙引號,就用雙引號引用,否則用單引號引用。print() 函數(shù)生成可讀性更好的輸出, 它會省去引號并且打印出轉(zhuǎn)義后的特殊字符:>>>'"Isn\'t," she said.''"Isn\'t," she said.'>>>print('"Isn\'t," she said.')"Isn't," she said.>>>s = 'First line.\nSecond line.'??# \n means newline>>>s??# without print(), \n is included in the output'First line.\nSecond line.'>>>print(s)??# with print(), \n produces a new lineFirst line.Second line.
如果你前面帶有 \ 的字符被當(dāng)作特殊字符,你可以使用 原始字符串,方法是在第一個引號前面加上一個 r:>>>print('C:\some\name')??# here \n means newline!C:\someame>>>print(r'C:\some\name')??# note the r before the quoteC:\some\name
字符串文本能夠分成多行。一種方法是使用三引號:"""...""" 或者 '''...'''。行尾換行符會被自動包含到字符串中,但是可以在行尾加上 \ 來避免這個行為。下面的示例: 可以使用反斜杠為行結(jié)尾的連續(xù)字符串,它表示下一行在邏輯上是本行的后續(xù)內(nèi)容: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
字符串可以由 + 操作符連接(粘到一起),可以由 * 表示重復(fù):>>># 3 times 'un', followed by 'ium'>>>3 * 'un' + 'ium''unununium'
相鄰的兩個字符串文本自動連接在一起。:>>>'Py' 'thon''Python'
它只用于兩個字符串文本,不能用于字符串表達式:>>>prefix = 'Py'>>>prefix 'thon'??# can't concatenate a variable and a string literal...SyntaxError: invalid syntax>>>('un' * 3) 'ium'...SyntaxError: invalid syntax
如果你想連接多個變量或者連接一個變量和一個字符串文本,使用 +:>>>prefix + 'thon''Python'
這個功能在你想切分很長的字符串的時候特別有用:>>>text = ('Put several strings within parentheses ''to have them joined together.')>>>text'Put several strings within parentheses to have them joined together.'
字符串也可以被截取(檢索)。類似于 C ,字符串的第一個字符索引為 0 。Python沒有單獨的字符類型;一個字符就是一個簡單的長度為1的字符串。:>>>word = 'Python'>>>word[0]??# character in position 0'P'>>>word[5]??# character in position 5'n'
索引也可以是負數(shù),這將導(dǎo)致從右邊開始計算。例如:>>>word[-1]??# last character'n'>>>word[-2]??# second-last character'o'>>>word[-6]'P'
請注意 -0 實際上就是 0,所以它不會導(dǎo)致從右邊開始計算。
除了索引,還支持 切片。索引用于獲得單個字符,切片 讓你獲得一個子字符串:>>>word[0:2]??# characters from position 0 (included) to 2 (excluded)'Py'>>>word[2:5]??# characters from position 2 (included) to 5 (excluded)'tho'
注意,包含起始的字符,不包含末尾的字符。這使得 s[:i] + s[i:] 永遠等于 s:>>>word[:2] + word[2:]'Python'>>>word[:4] + word[4:]'Python'
切片的索引有非常有用的默認值;省略的第一個索引默認為零,省略的第二個索引默認為切片的字符串的大小。:>>>word[:2]??# character from the beginning to position 2 (excluded)'Py'>>>word[4:]??# characters from position 4 (included) to the end'on'>>>word[-2:] # characters from the second-last (included) to the end'on'
有個辦法可以很容易地記住切片的工作方式:切片時的索引是在兩個字符 之間 。左邊第一個字符的索引為 0,而長度為 n 的字符串其最后一個字符的右界索引為 n。例如: +---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0? ?1? ?2? ?3? ?4? ?5? ?6-6??-5??-4??-3??-2??-1
文本中的第一行數(shù)字給出字符串中的索引點 0...6。第二行給出相應(yīng)的負索引。切片是從 i 到 j 兩個數(shù)值標示的邊界之間的所有字符。
對于非負索引,如果上下都在邊界內(nèi),切片長度就是兩個索引之差。例如,word[1:3] 是 2 。
試圖使用太大的索引會導(dǎo)致錯誤:>>>word[42]??# the word only has 6 charactersTraceback (most recent call last):??File "", line 1, in IndexError: string index out of range
Python 能夠優(yōu)雅地處理那些沒有意義的切片索引:一個過大的索引值(即下標值大于字符串實際長度)將被字符串實際長度所代替,當(dāng)上邊界比下邊界大時(即切片左值大于右值)就返回空字符串:>>>word[4:42]'on'>>>word[42:]''
Python字符串不可以被更改 — 它們是 不可變的 。因此,賦值給字符串索引的位置會導(dǎo)致錯誤:>>>word[0] = 'J'...TypeError: 'str' object does not support item assignment>>>word[2:] = 'py'...TypeError: 'str' object does not support item assignment
如果你需要一個不同的字符串,你應(yīng)該創(chuàng)建一個新的:>>>'J' + word[1:]'Jython'>>>word[:2] + 'py''Pypy'
內(nèi)置函數(shù) len() 返回字符串長度:>>>s = 'supercalifragilisticexpialidocious'>>>len(s)34
See alsoText Sequence Type — str字符串是 序列類型 的例子,它們支持這種類型共同的操作。String Methods字符串和Unicode字符串都支持大量的方法用于基本的轉(zhuǎn)換和查找。String Formatting這里描述了使用 str.format() 進行字符串格式化的信息。String Formatting Operations這里描述了舊式的字符串格式化操作,它們在字符串和Unicode字符串是 % 操作符的左操作數(shù)時調(diào)用。
1.3. 列表
Python 有幾個 復(fù)合 數(shù)據(jù)類型,用于表示其它的值。最通用的是 list (列表) ,它可以寫作中括號之間的一列逗號分隔的值。列表的元素不必是同一類型:>>>squares = [1, 4, 9, 16, 25]>>>squares[1, 4, 9, 16, 25]
就像字符串(以及其它所有內(nèi)建的 序列 類型)一樣,列表可以被索引和切片:>>>squares[0]??# indexing returns the item1>>>squares[-1]25>>>squares[-3:]??# slicing returns a new list[9, 16, 25]
所有的切片操作都會返回一個包含請求的元素的新列表。這意味著下面的切片操作返回列表一個新的(淺)拷貝副本:>>>squares[:][1, 4, 9, 16, 25]
列表也支持連接這樣的操作:>>>squares + [36, 49, 64, 81, 100][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
不像 不可變的 字符串,列表是 可變的,它允許修改元素:>>>cubes = [1, 8, 27, 65, 125]??# something's wrong here>>>4 ** 3??# the cube of 4 is 64, not 65!64>>>cubes[3] = 64??# replace the wrong value>>>cubes[1, 8, 27, 64, 125]
你還可以使用 append() 方法 (后面我們會看到更多關(guān)于列表的方法的內(nèi)容)在列表的末尾添加新的元素:>>>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]
也可以對切片賦值,此操作可以改變列表的尺寸,或清空它:>>>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']>>>letters['a', 'b', 'c', 'd', 'e', 'f', 'g']>>># replace some values>>>letters[2:5] = ['C', 'D', 'E']>>>letters['a', 'b', 'C', 'D', 'E', 'f', 'g']>>># now remove them>>>letters[2:5] = []>>>letters['a', 'b', 'f', 'g']>>># clear the list by replacing all the elements with an empty list>>>letters[:] = []>>>letters[]
內(nèi)置函數(shù) len() 同樣適用于列表:>>>letters = ['a', 'b', 'c', 'd']>>>len(letters)4
允許嵌套列表(創(chuàng)建一個包含其它列表的列表),例如:>>>a = ['a', 'b', 'c']>>>n = [1, 2, 3]>>>x = [a, n]>>>x[['a', 'b', 'c'], [1, 2, 3]]>>>x[0]['a', 'b', 'c']>>>x[0][1]'b'
總結(jié)
以上是生活随笔為你收集整理的python计算器基础知识_Python基础(一):将Python当做计算器、编程的第一步的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python模拟键盘输入_python模
- 下一篇: python算法编程_Python算法编