- 1.1 程序輸出,print語句
- 把一個字符串賦值給變量,僅使用變量名時,輸出的字符串是用單引號括起來的,其目的是爲了讓非字符串對象也能以字符串的方式輸出——即它顯示的是該對象的字符串表示,而不僅僅是字符串本身。
- >>> myString = 'Hello World!'
- >>> print myString
- Hello World!
- >>> myString
- 'Hello World!'
- 下劃線(_)在解釋器中有特別的含義,表示最後一個表達式的值。
- >>> _
- 'Hello World!'
- Python的print語句,與字符串格式操作符(%)結合使用。可實現字符串替換功能。
- >>> print "%s is number %d!"%("Python",1)
- Python is number 1!
- %s表示由一個字符串替換,%d表示由一個整型替換,另外%f表示由一個浮點型替換。
- Print語句也支持將輸出重定向到文件。符號>>用來重定向輸出。
- >>> print >> sys.stderr,"Fital error:invalid input!"
- Fital error:invalid input!
- 1.2 程序輸入,raw_input()
- 從用戶那裏得到數據輸入的最容易的方法是使用raw_input()內建函數(類似於SHELLl裏的read)。他讀取標準輸入,並將讀取到的數據賦值給指定的變量。可以使用int()內建函數將用戶的字符串轉換成整型。
- >>> user = raw_input('Enter login name:')
- Enter login name:root
- >>> print 'Your login name:',user
- Your login name: root
- >>> num = raw_input('Now enter a number: ')
- Now enter a number: 1024
- >>> print 'Doubleing your number: %d'%(int(num)*2)
- Doubleing your number: 2048
- 在學習Python的過程中,如果需要得到一個生疏函數的幫助,只需對它調用內建函數help()。通過用函數名作爲help()的參數就能得到相應的幫助信息。
- >>> help(raw_input)
- Help on built-in function raw_input in module __builtin__:
- raw_input(...)
- raw_input([prompt]) -> string
- Read a string from standard input. The trailing newline is stripped.
- If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
- On Unix, GNU readline is used if enabled. The prompt string, if given,
- is printed without a trailing newline before reading.
- (END)
- 1.3 註釋
- 同大部分腳本語言;一樣,Python也是用#標示注視,從#開始,知道一行結束的內容都是注視。
- >>> #one monment
- ... print 'Hello World!'
- Hello World!
- 1.4 操作符
- + - * / // % **
- 加、減、乘、除(取比商小的最大整數)、浮點除(對結果四捨五入,是真正的除法)、取餘、乘方
- >>> print -2*4+3**2
- 1
- +和-優先級最低,*、/、//、%優先級較高,單目操作符+和-優先級更高,乘方的優先級最高。
- < <= > >= == != <> 標準比較操作符,根據表達式的值的真假返回布爾值。
- >>> 2 < 43
- True
- >>> 2 <> 43
- True
- >>> 2 != 43
- True
- !=和<>,均爲“不等於”比較操作符,後者慢慢被淘汰,故推薦使用前者。
- Python也提供邏輯操作符。
- and or not
- >>> 2 < 43 and 2 > 34
- False
- >>> 2 < 43 or 2 > 34
- True
- >>> not 2 > 34
- True
- >>> 3<4<5
- True
- 最後一個例子在其他語言中通常是不合法的,不過Python支持這樣的表達式,級簡潔又優美。它實際上是下面表達式的縮寫:
- >>> 3 < 4 and 4 < 5
- True
- 1.5 變量和賦值