## raw_input和print
自從本課程開始以來,我們還沒有感受到computer姑娘的智能。最簡單的智能應該體現在哪里呢?想想小孩子剛剛回說話的時候情景吧。
> 小孩學說話,是一個模仿的過程,孩子周圍的人怎么說,她(他)往往就是重復。看官可以忘記自己當初是怎么學說話了吧?就找個小孩子觀察一下吧。最好是自己的孩子。如果沒有,就要抓緊了。
通過python能不能實現這個簡單的功能呢?當然能,要不然python如何橫行天下呀。
不過在寫這個功能前,要了解兩個函數:raw_input和print
> 這兩個都是python的內建函數(built-in function)。關于python的內建函數,下面這個表格都列出來了。所謂內建函數,就是能夠在python中直接調用,不需要做其它的操作。
Built-in Functions
* * *
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#abs-----divmod---input----open-----staticmethod)|abs() | divmod() | input()| open()| staticmethod()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#all-----enumerate----int--ord--str)|all() | enumerate() | int() | ord() | str()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#any-----eval-----isinstance---pow--sum)|any() | eval() | isinstance()| pow()| sum()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#basestring--execfile-----issubclass---print----super)|basestring() | execfile() | issubclass() | print() | super()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#bin-----file-----iter-----property-----tuple)|bin() | file() | iter()| property()| tuple()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#bool----filter---len--range----type)|bool() | filter() | len() | range() | type()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#bytearray---float----list-----raw_input----unichr)|bytearray() | float()| list() | raw_input()| unichr()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#callable----format---locals---reduce---unicode)|callable() | format() | locals() | reduce() | unicode()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#chr-----frozenset----long-----reload---vars)|chr() | frozenset() | long() | reload() | vars()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#classmethod-----getattr--map--repr-----xrange)|classmethod()| getattr()| map() | repr() | xrange()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#cmp-----globals--max--reversed-----zip)|cmp() | globals()| max()| reversed()| zip()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#compile--hasattr-----memoryview---round----import)|compile() |hasattr() | memoryview()| round() |?**import**()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#complex--hash----min--set--apply)|complex() |hash() | min()| set() | apply()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#delattr--help----next-----setattr--buffer)|delattr() |help()| next()| setattr()| buffer()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#dict----hex---object---slice---coerce)|dict() | hex() |object() |slice() | coerce()|
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#dir-----id----oct--sorted---intern)|dir() | id() |oct() |sorted() |intern()|
這些內建函數,怎么才能知道哪個函數怎么用,是干什么用的呢?
不知道你是否還記得我在前面使用過的方法,這里再進行演示,這種方法是學習python的法寶。
~~~
>>> 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.
~~~
從中是不是已經清晰地看到了`raw_input()`的使用方法了。
還有第二種方法,那就是到python的官方網站,查看內建函數的說明。[https://docs.python.org/2/library/functions.html](https://docs.python.org/2/library/functions.html)
其實,我上面那個表格,就是在這個網頁中抄過來的。
例如,對`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.
~~~
分別在交互模式下,將這個兩個函數操練一下。
~~~
>>> raw_input("input your name:")
input your name:python
'python'
~~~
輸入名字之后,就返回了輸入的內容。用一個變量可以獲得這個返回值。
~~~
>>> name = raw_input("input your name:")
input your name:python
>>> name
'python'
>>> type(name)
<type 'str'>
~~~
而且,返回的結果是str類型。如果輸入的是數字呢?
~~~
>>> age = raw_input("How old are you?")
How old are you?10
>>> age
'10'
>>> type(age)
<type 'str'>
~~~
返回的結果,仍然是str類型。
再試試`print()`,看前面對它的說明,是比較復雜的。沒關系,我們從簡單的開始。在交互模式下操作:
~~~
>>> print("hello, world")
hello, world
>>> a = "python"
>>> b = "good"
>>> print a
python
>>> print a,b
python good
~~~
比較簡單吧。當然,這是沒有搞太復雜了。
特別要提醒的是,`print()`默認是以`\n`結尾的,所以,會看到每個輸出語句之后,輸出內容后面自動帶上了`\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()`的使用,除了打印一個字符串之外,還可以打印字符串拼接結果。
~~~
print "You are " + age + " years old."
~~~
注意,那個變量`age`必須是字符串,如最后的那個語句中:
~~~
print "You will be " + str(after_ten) + " years old after ten years."
~~~
這句話里面,有一個類型轉化,將原本是整數型`after_ten`轉化為了str類型。否則,就包括,不信,你可以試試。
同樣注意,在`after_ten = int(age) + 10`中,因為通過`raw_input`得到的是str類型,當age和10求和的時候,需要先用`int()`函數進行類型轉化,才能和后面的整數10相加。
這個小程序,是有點綜合的,基本上把已經學到的東西綜合運用了一次。請看官調試一下,如果沒有通過,仔細看報錯信息,你能夠從中獲得修改方向的信息。
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/107.md#原始字符串)原始字符串
所謂原始字符串,就是指字符串里面的每個字符都是原始含義,比如反斜杠,不會被看做轉義符。如果在一般字符串中,比如
~~~
>>> print "I like \npython"
I like
python
~~~
這里的反斜杠就不是“反斜杠”的原始符號含義,而是和后面的n一起表示換行(轉義了)。當然,這似乎沒有什么太大影響,但有的時候,可能會出現問題,比如打印DOS路徑(DOS,有沒有搞錯,現在還有人用嗎?)
~~~
>>> dos = "c:\news"
>>> dos
'c:\news' #這里貌似沒有什么問題
>>> print dos #當用print來打印這個字符串的時候,就出問題了。
c:
ews
~~~
如何避免?用前面講過的轉義符可以解決:
~~~
>>> 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開頭引起的字符串,就是原始字符串,在里面放任何字符都表示該字符的原始含義。
這種方法在做網站設置網站目錄結構的時候非常有用。使用了原始字符串,就不需要轉義了。
- 第零章 預備
- 關于Python的故事
- 從小工到專家
- Python安裝
- 集成開發環境
- 第壹章 基本數據類型
- 數和四則運算
- 除法
- 常用數學函數和運算優先級
- 寫一個簡單的程序
- 字符串(1)
- 字符串(2)
- 字符串(3)
- 字符串(4)
- 字符編碼
- 列表(1)
- 列表(2)
- 列表(3)
- 回顧list和str
- 元組
- 字典(1)
- 字典(2)
- 集合(1)
- 集合(2)
- 第貳章 語句和文件
- 運算符
- 語句(1)
- 語句(2)
- 語句(3)
- 語句(4)
- 語句(5)
- 文件(1)
- 文件(2)
- 迭代
- 練習
- 自省
- 第叁章 函數
- 函數(1)
- 函數(2)
- 函數(3)
- 函數(4)
- 函數練習
- 第肆章 類
- 類(1)
- 類(2)
- 類(3)
- 類(4)
- 類(5)
- 多態和封裝
- 特殊方法(1)
- 特殊方法(2)
- 迭代器
- 生成器
- 上下文管理器
- 第伍章 錯誤和異常
- 錯誤和異常(1)
- 錯誤和異常(2)
- 錯誤和異常(3)
- 第陸章 模塊
- 編寫模塊
- 標準庫(1)
- 標準庫(2)
- 標準庫(3)
- 標準庫(4)
- 標準庫(5)
- 標準庫(6)
- 標準庫(7)
- 標準庫(8)
- 第三方庫
- 第柒章 保存數據
- 將數據存入文件
- mysql數據庫(1)
- MySQL數據庫(2)
- mongodb數據庫(1)
- SQLite數據庫
- 電子表格
- 第捌章 用Tornado做網站
- 為做網站而準備
- 分析Hello
- 用tornado做網站(1)
- 用tornado做網站(2)
- 用tornado做網站(3)
- 用tornado做網站(4)
- 用tornado做網站(5)
- 用tornado做網站(6)
- 用tornado做網站(7)
- 第玖章 科學計算
- 為計算做準備
- Pandas使用(1)
- Pandas使用(2)
- 處理股票數據
- 附:網絡文摘
- 如何成為Python高手
- ASCII、Unicode、GBK和UTF-8字符編碼的區別聯系