自從本課程開始以來,我們還沒有感受到 computer 姑娘的智能。最簡(jiǎn)單的智能應(yīng)該體現(xiàn)在哪里呢?想想小孩子剛剛回說話的時(shí)候情景吧。
小孩學(xué)說話,是一個(gè)模仿的過程,孩子周圍的人怎么說,她(他)往往就是重復(fù)??垂倏梢酝涀约寒?dāng)初是怎么學(xué)說話了吧?就找個(gè)小孩子觀察一下吧。最好是自己的孩子。如果沒有,就要抓緊了。
通過 Python 能不能實(shí)現(xiàn)這個(gè)簡(jiǎn)單的功能呢?當(dāng)然能,要不然 Python 如何橫行天下呀。
不過在寫這個(gè)功能前,要了解兩個(gè)函數(shù):raw_input 和 print
這兩個(gè)都是 Python 的內(nèi)建函數(shù)(built-in function)。關(guān)于 Python 的內(nèi)建函數(shù),下面這個(gè)表格都列出來了。所謂內(nèi)建函數(shù),就是能夠在 Python 中直接調(diào)用,不需要做其它的操作。
Built-in Functions
| abs() | divmod() | input() | open() | staticmethod() |
|---|---|---|---|---|
| all() | enumerate() | int() | ord() | str() |
| any() | eval() | isinstance() | pow() | sum() |
| basestring() | execfile() | issubclass() | print() | super() |
| bin() | file() | iter() | property() | tuple() |
| bool() | filter() | len() | range() | type() |
| bytearray() | float() | list() | raw_input() | unichr() |
| callable() | format() | locals() | reduce() | unicode() |
| chr() | frozenset() | long() | reload() | vars() |
| classmethod() | getattr() | map() | repr() | xrange() |
| cmp() | globals() | max() | reversed() | zip() |
| compile() | hasattr() | memoryview() | round() | import() |
| complex() | hash() | min() | set() | apply() |
| delattr() | help() | next() | setattr() | buffer() |
| dict() | hex() | object() | slice() | coerce() |
| dir() | id() | oct() | sorted() | intern() |
這些內(nèi)建函數(shù),怎么才能知道哪個(gè)函數(shù)怎么用,是干什么用的呢?
不知道你是否還記得我在前面使用過的方法,這里再進(jìn)行演示,這種方法是學(xué)習(xí) Python 的法寶。
>>> help(raw_input)
然后就出現(xiàn):
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.
從中是不是已經(jīng)清晰地看到了 raw_input()的使用方法了。
還有第二種方法,那就是到 Python 的官方網(wǎng)站,查看內(nèi)建函數(shù)的說明。https://docs.Python.org/2/library/functions.html
其實(shí),我上面那個(gè)表格,就是在這個(gè)網(wǎng)頁(yè)中抄過來的。
例如,對(duì) print()說明如下:
print(*objects, sep=' ', end='\n', file=sys.stdout)
Print objects to the stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Output buffering is determined by file. Use file.flush() to ensure, for instance, immediate appearance on a screen.
分別在交互模式下,將這個(gè)兩個(gè)函數(shù)操練一下。
>>> raw_input("input your name:")
input your name:python
'python'
輸入名字之后,就返回了輸入的內(nèi)容。用一個(gè)變量可以獲得這個(gè)返回值。
>>> name = raw_input("input your name:")
input your name:python
>>> name
'python'
>>> type(name)
<type 'str'>
而且,返回的結(jié)果是 str 類型。如果輸入的是數(shù)字呢?
>>> age = raw_input("How old are you?")
How old are you?10
>>> age
'10'
>>> type(age)
<type 'str'>
返回的結(jié)果,仍然是 str 類型。
再試試 print(),看前面對(duì)它的說明,是比較復(fù)雜的。沒關(guān)系,我們從簡(jiǎn)單的開始。在交互模式下操作:
>>> print("hello, world")
hello, world
>>> a = "python"
>>> b = "good"
>>> print a
python
>>> print a,b
python good
比較簡(jiǎn)單吧。當(dāng)然,這是沒有搞太復(fù)雜了。
特別要提醒的是,print()默認(rèn)是以 \n 結(jié)尾的,所以,會(huì)看到每個(gè)輸出語(yǔ)句之后,輸出內(nèi)容后面自動(dòng)帶上了 \n,于是就換行了。
有了以上兩個(gè)準(zhǔn)備,接下來就可以寫一個(gè)能夠“對(duì)話”的小程序了。
#!/usr/bin/env python
# coding=utf-8
name = raw_input("What is your name?")
age = raw_input("How old are you?")
print "Your name is:", name
print "You are " + age + " years old."
after_ten = int(age) + 10
print "You will be " + str(after_ten) + " years old after ten years."
對(duì)這段小程序中,有幾點(diǎn)說明
前面演示了 print()的使用,除了打印一個(gè)字符串之外,還可以打印字符串拼接結(jié)果。
print "You are " + age + " years old."
注意,那個(gè)變量 age 必須是字符串,如最后的那個(gè)語(yǔ)句中:
print "You will be " + str(after_ten) + " years old after ten years."
這句話里面,有一個(gè)類型轉(zhuǎn)化,將原本是整數(shù)型 after_ten 轉(zhuǎn)化為了 str 類型。否則,就包括,不信,你可以試試。
同樣注意,在 after_ten = int(age) + 10 中,因?yàn)橥ㄟ^ raw_input 得到的是 str 類型,當(dāng) age 和 10 求和的時(shí)候,需要先用 int()函數(shù)進(jìn)行類型轉(zhuǎn)化,才能和后面的整數(shù) 10 相加。
這個(gè)小程序,是有點(diǎn)綜合的,基本上把已經(jīng)學(xué)到的東西綜合運(yùn)用了一次。請(qǐng)看官調(diào)試一下,如果沒有通過,仔細(xì)看報(bào)錯(cuò)信息,你能夠從中獲得修改方向的信息。
所謂原始字符串,就是指字符串里面的每個(gè)字符都是原始含義,比如反斜杠,不會(huì)被看做轉(zhuǎn)義符。如果在一般字符串中,比如
>>> print "I like \npython"
I like
python
這里的反斜杠就不是“反斜杠”的原始符號(hào)含義,而是和后面的 n 一起表示換行(轉(zhuǎn)義了)。當(dāng)然,這似乎沒有什么太大影響,但有的時(shí)候,可能會(huì)出現(xiàn)問題,比如打印 DOS 路徑(DOS,有沒有搞錯(cuò),現(xiàn)在還有人用嗎?)
>>> dos = "c:\news"
>>> dos
'c:\news' # 這里貌似沒有什么問題
>>> print dos # 當(dāng)用 print 來打印這個(gè)字符串的時(shí)候,就出問題了。
c:
ews
如何避免?用前面講過的轉(zhuǎn)義符可以解決:
>>> dos = "c:\\news"
>>> print dos
c:\news
此外,還有一種方法,如:
>>> dos = r"c:\news"
>>> print dos
c:\news
>>> print r"c:\news\python"
c:\news\python
狀如 r"c:\news",由 r 開頭引起的字符串,就是原始字符串,在里面放任何字符都表示該字符的原始含義。
這種方法在做網(wǎng)站設(shè)置網(wǎng)站目錄結(jié)構(gòu)的時(shí)候非常有用。使用了原始字符串,就不需要轉(zhuǎn)義了。
總目錄 | 上節(jié):字符串(1) | 下節(jié):字符串(3)
如果你認(rèn)為有必要打賞我,請(qǐng)通過支付寶:qiwsir@126.com,不勝感激。