在Python程序前加上 from __future__ import division 或者在解釋器里面直接執(zhí)行它,或者通過(guò)命令行運(yùn)行Python時(shí)使用命令開(kāi)關(guān)-Qnew,會(huì)使單斜線不再整除,如
>>> 1/2
0.5
而雙斜線實(shí)現(xiàn)整除,如
>>> 1//2
0
>>> x = input('x:')
用import導(dǎo)入模塊,然后按照“模塊.函數(shù)”的格式使用這個(gè)模塊的函數(shù),如
>>> import math
>>> math.floor(23.96)
23.0
在使用了“form模塊import函數(shù)”這種形式的import命令之后,就可以直接使用函數(shù),而不需要模塊名作為前綴了,如
>>> from math import sqrt
>>> sqrt(9)
3.0
CMath模塊可以實(shí)現(xiàn)處理復(fù)數(shù),如
>>> cmath.sqrt(-9)
3j
在IDLE中,file->new file會(huì)彈出一個(gè)編輯窗口,在里面編輯如下
name = raw_input("what is your name")PRint 'hello,' + name + '!'
然后file-save 保存為hell.py,然后F5運(yùn)行,則在解釋器中出現(xiàn)結(jié)果,如
>>> ================================ RESTART ================================
>>>
what is your name55
hello,55!
或者雙擊hell.py,則命令行窗口一閃而逝。
在代碼中,#右邊的一切都會(huì)被忽略,那部分即為注釋。
反引號(hào)、str和repr是將值轉(zhuǎn)換為字符串的三種方式,其中str會(huì)把值轉(zhuǎn)換為合理形式的字符串,以便用戶理解,而repr會(huì)創(chuàng)建一個(gè)字符串,以合法的平Python表達(dá)式的形式來(lái)表示值,如
tmp = 1000print 'hello ' + `tmp`print 'hello ' + str(tmp)print 'hello ' + repr(tmp)
結(jié)果如下
hello 1000
hello 1000
hello 1000
input會(huì)假設(shè)用戶輸入的是合法的Python表達(dá)式(或多或少有些與repr函數(shù)相反的意思),raw_input會(huì)把所有的輸入當(dāng)做原始數(shù)據(jù),然后將其放到字符串中,如
print 'hello ' + raw_input('your name:')print 'hello ' + input('your name:')
結(jié)果如下
your name:55
hello 55
your name:55
Traceback (most recent call last):
File "E:/work/Code/python/hell.py", line 2, in <module>
print 'hello ' + input('your name:')
TypeError: cannot concatenate 'str' and 'int' objects
如果要書(shū)寫(xiě)一個(gè)跨多行的長(zhǎng)字符串,可以使用三個(gè)引號(hào)代替普通引號(hào),如
print '''This is a long string.it continues here.and it's not over yet."hello world!".still here.'''
結(jié)果如下
This is a long string.
it continues here.
and it's not over yet.
"hello world!".
普通字符串也可以跨行,如果一行之中最后一個(gè)字符是反斜線,那么,換行本身就“轉(zhuǎn)義”了,也就是被忽略了(同時(shí)適用于表達(dá)式),如
print 'This is a long string./it stop here.'
結(jié)果
This is a long string.it stop here.
原始字符串不會(huì)吧反斜線當(dāng)做特殊字符,在元是字符串中輸入的每個(gè)字符都會(huì)與書(shū)寫(xiě)的方式保持一致,如
print r'E:/work/Code/python' '//'
結(jié)果如下
E:/work/Code/python/
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注