自從本課程開始以來,我們還沒有感受到 computer 姑娘的智能。最簡單的智能應(yīng)該體現(xiàn)在哪里呢?想想小孩子剛剛回說話的時候情景吧。
小孩學(xué)說話,是一個模仿的過程,孩子周圍的人怎么說,她(他)往往就是重復(fù)??垂倏梢酝涀约寒敵跏窃趺磳W(xué)說話了吧?就找個小孩子觀察一下吧。最好是自己的孩子。如果沒有,就要抓緊了。
通過 Python 能不能實現(xiàn)這個簡單的功能呢?當然能,要不然 Python 如何橫行天下呀。
不過在寫這個功能前,要了解兩個函數(shù):raw_input 和 print
這兩個都是 Python 的內(nèi)建函數(shù)(built-in function)。關(guān)于 Python 的內(nèi)建函數(shù),下面這個表格都列出來了。所謂內(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ù),怎么才能知道哪個函數(shù)怎么用,是干什么用的呢?
不知道你是否還記得我在前面使用過的方法,這里再進行演示,這種方法是學(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
其實,我上面那個表格,就是在這個網(wǎng)頁中抄過來的。
例如,對 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.
分別在交互模式下,將這個兩個函數(shù)操練一下。
>>> raw_input("input your name:")
input your name:python
'python'
輸入名字之后,就返回了輸入的內(nèi)容。用一個變量可以獲得這個返回值。
>>> 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()
,看前面對它的說明,是比較復(fù)雜的。沒關(guān)系,我們從簡單的開始。在交互模式下操作:
>>> print("hello, world")
hello, world
>>> a = "python"
>>> b = "good"
>>> print a
python
>>> print a,b
python good
比較簡單吧。當然,這是沒有搞太復(fù)雜了。
特別要提醒的是,print()
默認是以 \n
結(jié)尾的,所以,會看到每個輸出語句之后,輸出內(nèi)容后面自動帶上了 \n
,于是就換行了。
有了以上兩個準備,接下來就可以寫一個能夠“對話”的小程序了。
#!/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."
對這段小程序中,有幾點說明
前面演示了 print()
的使用,除了打印一個字符串之外,還可以打印字符串拼接結(jié)果。
print "You are " + age + " years old."
注意,那個變量 age
必須是字符串,如最后的那個語句中:
print "You will be " + str(after_ten) + " years old after ten years."
這句話里面,有一個類型轉(zhuǎn)化,將原本是整數(shù)型 after_ten
轉(zhuǎn)化為了 str 類型。否則,就包括,不信,你可以試試。
同樣注意,在 after_ten = int(age) + 10
中,因為通過 raw_input
得到的是 str 類型,當 age 和 10 求和的時候,需要先用 int()
函數(shù)進行類型轉(zhuǎn)化,才能和后面的整數(shù) 10 相加。
這個小程序,是有點綜合的,基本上把已經(jīng)學(xué)到的東西綜合運用了一次。請看官調(diào)試一下,如果沒有通過,仔細看報錯信息,你能夠從中獲得修改方向的信息。
所謂原始字符串,就是指字符串里面的每個字符都是原始含義,比如反斜杠,不會被看做轉(zhuǎn)義符。如果在一般字符串中,比如
>>> print "I like \npython"
I like
python
這里的反斜杠就不是“反斜杠”的原始符號含義,而是和后面的 n 一起表示換行(轉(zhuǎn)義了)。當然,這似乎沒有什么太大影響,但有的時候,可能會出現(xiàn)問題,比如打印 DOS 路徑(DOS,有沒有搞錯,現(xiàn)在還有人用嗎?)
>>> dos = "c:\news"
>>> dos
'c:\news' # 這里貌似沒有什么問題
>>> print dos # 當用 print 來打印這個字符串的時候,就出問題了。
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)的時候非常有用。使用了原始字符串,就不需要轉(zhuǎn)義了。
總目錄 | 上節(jié):字符串(1) | 下節(jié):字符串(3)
如果你認為有必要打賞我,請通過支付寶:qiwsir@126.com,不勝感激。