python是吉多·範羅蘇姆發明的一種面向對象的腳本語言,可能有些人不知道面向對象和腳本具體是什麼意思,可是對於一個初學者來講,如今並不須要明白。你們都知道,當下全棧工程師的概念很火,而Python是一種全棧的開發語言,因此你若是能學好Python,那麼前端,後端,測試,大數據分析,爬蟲等這些工做你都能勝任。前端
關於語言的選擇,有各類各樣的討論,在這裏我很少說,就引用Python裏面的一個彩蛋來講明爲何要選擇Python,在Python解釋器裏輸入import this 就能夠看到。java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
>>>
import
this
The Zen of Python, by Tim Peters
Beautiful
is
better than ugly.
Explicit
is
better than implicit.
Simple
is
better than
complex
.
Complex
is
better than complicated.
Flat
is
better than nested.
Sparse
is
better than dense.
Readability counts.
Special cases aren't special enough to
break
the rules.
Although practicality beats purity.
Errors should never
pass
silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one
-
-
and
preferably only one
-
-
obvious way to do it.
Although that way may
not
be obvious at first unless you're Dutch.
Now
is
better than never.
Although never
is
often better than
*
right
*
now.
If the implementation
is
hard to explain, it's a bad idea.
If the implementation
is
easy to explain, it may be a good idea.
Namespaces are one honking great idea
-
-
let's do more of those!
|
上面的話簡單的總結來講就是「優雅」、「明確」、「簡單」,或許你仍是有些不明白,舉個簡單的例子,若果一樣的功能你用C/C++寫可能要寫100行代碼,而若是用Python寫你可能只要20行代碼就搞定,一樣的若是一個問題有好幾種解決方案,可是Python會用一種最簡單的方法來實現。因此Python是用最簡單最優雅最明確的方法來解決問題。node
1.print在python2.x是語句,在python3.x是print()函數python
1
2
3
4
5
6
7
8
9
10
|
Old:
print
"The answer is"
,
2
*
2
New:
print
(
"The answer is"
,
2
*
2
)
Old:
print
x,
# Trailing comma suppresses newline
New:
print
(x, end
=
" "
)
# Appends a space instead of a newline
Old:
print
# Prints a newline
New:
print
()
# You must call the function!
Old:
print
>>sys.stderr,
"fatal error"
New:
print
(
"fatal error"
,
file
=
sys.stderr)
Old:
print
(x, y)
# prints repr((x, y))
New:
print
((x, y))
# Not the same as print(x, y)!
|
2.python3.x所有字符集都是unicode,而在python2.x中是ascii編碼,須要設置#-*- coding:utf-8 -*-,中文才不會亂碼linux
3.python2.x一些庫名在python3.x的更改shell
python2.x | _winreg | ConfigParser | copy_reg | Queue | SocketServer | markupbase | repr | test.test_support |
python3.x | winreg | configparser | copyreg | queue | socketserver | _markupbase | reprlib | test.support |
4.python3.x有一些第三方模塊支持不了,固然還有其餘的模塊,後續慢慢添加....express
Twisted urllib2 scrapy MySQLdbubuntu
5.python2.x與python3.x庫方法的不一樣,在後續慢慢體現....vim
在這裏我我推薦安裝Python3,由於隨着時間的推移Python3,一定是將來的趨勢,咱們要順應潮流。在Python的官網能夠下載相應的版本,網址是https://www.python.org/downloads/,安裝上面的提示安裝好便可,就不在多說了,此外後面的操做都是基於Ubuntu 15.10下Python3.5.1操做,默認是Python2.7.10版本windows
建議使用pyenv(Python版本控制2.7和3.5之間隨意切換)、virtualenv(Python虛擬環境)、pycharm(Python的IDE工具)、pip(Python包管理工具)。
windows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
1
、下載安裝包
https:
/
/
www.python.org
/
downloads
/
2
、安裝python2.
7.11
默認安裝路徑:C:\python27
3
、配置環境變量
【右鍵計算機】
-
-
》【屬性】
-
-
》【高級系統設置】
-
-
》【高級】
-
-
》【環境變量】
-
-
》【在第二個內容框中找到 變量名爲Path 的一行,雙擊】
-
-
> 【Python安裝目錄追加到變值值中,用 ; 分割】
如:原來的值;C:\python27,切記前面有分號
4
、安裝python3.
5.1
默認安裝路徑: C:\python35
5
、將python3.
5
中的執行程序python.exe重命名成python3
6
、配置環境變量
【右鍵計算機】
-
-
》【屬性】
-
-
》【高級系統設置】
-
-
》【高級】
-
-
》【環境變量】
-
-
》【在第二個內容框中找到 變量名爲Path 的一行,雙擊】
-
-
> 【Python安裝目錄追加到變值值中,用 ; 分割】
如:原來的值;C:\python35,切記前面有分號
7
、這樣就實現python2.
7
和python3.
5
多版本
|
兩種方式輸出Hello World,第一種咱們用解釋器交互式環境,打開shell輸入python。
1
2
3
4
5
6
|
tomcat@node:~$ python
Python
3.5
.
1
(default, Jul
27
2016
,
18
:
07
:
46
)
[GCC
5.2
.
1
20151010
] on linux
Type
"help"
,
"copyright"
,
"credits"
or
"license"
for
more information.
>>>
print
(
"Hello World!"
)
Hello World!
|
第二種將代碼保存在 .py文件中,命令行下執行 python1.py 就能夠打印出來Hello World。
1
2
3
4
5
6
7
8
|
tomcat@node:~$ vim python1.py
#!/usr/bin/env python
# coding:utf-8
print
(
"Hello World!"
)
tomcat@node:~$ chmod
+
x python1.py
tomcat@node:~$ python python1.py
Hello World!
|
在Linux下執行的時候,第一行指出文件由python解釋器來執行,第二行是告訴解釋器在加載文件時,採用何種編碼,不加上這句的話,在python2中顯示中文會出現亂碼,在python3中則不會,因此你若是用的是windows並且用的是python3,其實能夠不用加這兩句,不過實際中仍是建議加上這兩句。到這裏咱們就用了兩種方式輸Hello World。
常量咱們約定俗成都爲大寫
一、變量聲明:
二、變量定義的規則:
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise','return', 'try', 'while', 'with', 'yield']
三、變量最佳命名方式:
注意:兩種命名方式不要混用,只要你喜歡的一種便可
四、變量命名慣例:
一、ASCII
ASCII(American Standard Code for Information Interchange,美國標準信息交換代碼)是基於拉丁字母的一套電腦編碼系統,主要用於顯示現代英語和其餘西歐語言,其最多隻能用 8 位來表示(一個字節),即:2**8 = 256-1,因此,ASCII碼最多隻能表示 255 個符號,python2.x解釋器默認是ASCII編碼。
顯然ASCII碼沒法將世界上的各類文字和符號所有表示,因此,就須要新出一種能夠表明全部字符和符號的編碼,即:Unicode
二、Unicode
Unicode(統一碼、萬國碼、單一碼)是一種在計算機上使用的字符編碼。Unicode 是爲了解決傳統的字符編碼方案的侷限而產生的,它爲每種語言中的每一個字符設定了統一而且惟一的二進制編碼,規定全部的字符和符號最少由 16 位來表示(2個字節),即:2 **16 = 65536,注:此處說的的是最少2個字節,可能更多,好比漢字就須要3個字節,python3.x解釋器默認是Unicode編碼。
UTF-8,是對Unicode編碼的壓縮和優化,他再也不使用最少使用2個字節,而是將全部的字符和符號進行分類:ASCII碼中的內容用1個字節保存、歐洲的字符用2個字節保存,東亞的字符用3個字節保存...
因此,python2.x解釋器在加載 .py 文件中的代碼時,會對內容進行編碼(默認ASCII),若是是以下代碼的話:
報錯:ascii碼沒法表示中文
1
2
3
4
5
6
|
tomcat@node:~$ vim a.py
#!/usr/bin/env python
print
"你好!世界"
<br>
tomcat@node:~$ python a.py
File
"a.py"
, line
2
SyntaxError: Non
-
ASCII character
'\xe4'
in
file
a.py on line
2
, but no encoding declared; see http:
/
/
python.org
/
dev
/
peps
/
pep
-
0263
/
for
details
|
改正:應該顯示的告訴python解釋器,用什麼編碼來執行源代碼,即:
1
2
3
4
5
6
7
|
tomcat@node:~$ vi a.py
#!/usr/bin/env python
# coding:utf-8
print
"你好!世界"
tomcat@node:~$ python a.py
你好!世界
|
注意:python3.x中字符集默認爲UTF-8,python2.x仍是ASCII因此須要設置#coding:utf-8
一、Python3.x提供了一個input(),可讓用戶輸入字符串。好比輸入用戶的名字:
python3中格式化輸出默認接收的都視爲字符串,若是你獲取的是要數字類型則須要另外強制轉換爲int()轉換爲數字類型才能得到數字
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
>>> name
=
input
(
"please input your name:"
)
please
input
your name:tomcatxiao
>>>
print
(
"Hello "
+
name)
Hello tomcatxiao
>>> age
=
input
(
"please enter your age:"
)
please enter your age:
21
>>>
type
(age)
<
class
'str'
>
>>> age1
=
input
(
"please enter your age:"
)
>>> age1
=
int
(age1)
>>>
type
(age1)
<
class
'int'
>
|
輸入密碼時,若是想要不可見,須要利用 getpass 模塊中的 getpass 方法,即:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
tomcat@node:~$ vi b.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import
getpass
# 將用戶輸入的內容賦值給 pwd變量
pwd
=
getpass.getpass(
"請輸入密碼:"
)
# 打印輸入的內容
print
(pwd)
tomcat@node:~$ python b.py
請輸入密碼:
123
|
注意:在pycharm IDE工具中這段代碼是行不通的,在Linux命令行或者Windows cmd中是能夠的
二、Python2.x提供了一個raw_input()和input(),input()在python2中基本不用忘了吧,固然我這裏會演示他們的區別
raw_input()在字符串和數值型都沒有問題
1
2
3
4
5
6
7
8
9
|
>>> name
=
raw_input
(
"please enter your name:"
)
please enter your name:tomcatxiao
>>>
print
name
tomcatxiao
>>> age
=
raw_input
(
"your age is:"
)
your age
is
:
21
>>>
print
age
21
|
input()在輸入字符串的時候報錯,變量未定義,數值型則沒有報錯,若是是字符串則須要引號'' or "",或者事先定義變量賦值
>>> name = input("please input your name:") please input your name:tomcatxiao Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'tomcatxiao' is not defined >>> age = input("your age is:") your age is:21
對於上面的代碼進行修改下,將字符串事先賦值給一個變量,而後從input中輸入則沒有報錯
>>> myname = "tomcatxiao" >>> name = input("please input your name:") please input your name:myname >>> print name tomcatxiao
Python中輸出是用print,Python2.x中print是語句,Python3.x中則是print()函數
1.Python2.x
1
|
print
"String %format1 %format2 ..."
%
(variable1,variable2)
|
2.Python3.x
1
|
print
(
"String %format1 %format2 ...."
%
(variable1,variable2))
|
3.拼接效率比較低
1
2
|
print
"String"
+
variable1
print
(
"String"
+
variable1)
|
input()和格式化輸出時要特別要注意input()輸入是個數字須要int()轉換,格式化輸出的時候使用%d纔不會報錯
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
tomcat@node:~$ vi c.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
name
=
input
(
"input your name:"
)
age
=
input
(
"input your age:"
)
job
=
input
(
"input your job:"
)
msg
=
'''
Information of %s
-------------
Name: %s
Age : %s
Job : %s
'''
%
(name,name,age,job)
print
(msg)
tomcat@node:~$ python c.py
|
注意:python3中格式化輸出默認接收的都視爲字符串,若是是數字則須要另外強制轉換爲int()轉換爲數字類型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
name
=
input
(
"input your name:"
)
age
=
input
(
"input your age:"
)
job
=
input
(
"input your job:"
)
msg
=
'''
Information of %s
-------------
Name: %s
Age : %d
Job : %s
'''
%
(name,name,age,job)
print
(msg)
|
這裏的Age用%d進行格式化若是沒有強制轉換爲數字則會報錯,執行上面的代碼則會報錯,int()轉換了則不會報錯
1
2
3
4
5
6
7
|
input
your name:tomcatxiao
input
your age:
21
input
your job:IT
Traceback (most recent call last):
File
"/home/tomcat/PycharmProjects/s13/day01/dsfg.py"
, line
15
,
in
<module>
'''
%
(name,name,age,job)
TypeError:
%
d
format
: a number
is
required,
not
str
|
#號能夠從一行的任何地方開始
'''''',"""""",三引號用於多行註釋
\,表示續行符
注意:若是''''''三引號是在一個def 函數或者class 定義類的下方則是對這個函數或者類的說明,能夠經過__doc__動態得到文檔子串
Python的強大之處在於他有很是豐富和強大的標準庫和第三方庫,幾乎你想實現的任何功能都有相應的Python庫支持,之後的課程中會深刻講解經常使用到的各類庫,如今,咱們先來象徵性的學2個簡單的。
sys
1
2
3
4
5
6
7
8
9
10
11
12
|
tomcat@node:~$ vi d.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import
sys
print
(sys.argv)
#輸出
tomcat@node:~$ python d.py helo world
[
'test.py'
,
'helo'
,
'world'
]
#把執行腳本時傳遞的參數獲取到了
|
os
1
2
|
>>>
import
os
>>> os.system(
"df -h"
)
#調用系統命令
|
注意:os.system()執行系統命令,若是有變量存儲該執行的結果,該變量只會存儲該命令執行成功或者失敗返回值,不會存儲命令執行的結果,os.system("df -h")會有返回值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
>>> result
=
os.system(
"df -h"
)
df: ‘
/
mnt
/
hgfs’: Protocol error
Filesystem Size Used Avail Use
%
Mounted on
udev
3.9G
0
3.9G
0
%
/
dev
tmpfs
797M
9.4M
788M
2
%
/
run
/
dev
/
sda1
189G
10G
170G
6
%
/
tmpfs
3.9G
16M
3.9G
1
%
/
dev
/
shm
tmpfs
5.0M
4.0K
5.0M
1
%
/
run
/
lock
tmpfs
3.9G
0
3.9G
0
%
/
sys
/
fs
/
cgroup
cgmfs
100K
0
100K
0
%
/
run
/
cgmanager
/
fs
tmpfs
797M
76K
797M
1
%
/
run
/
user
/
1000
>>>
print
(result)
256
|
若是須要保存命令執行的結果需喲使用os.popen("系統命令").read(),而後使用變量賦值輸出便可
1
2
3
4
5
6
7
8
9
10
11
12
|
>>> result
=
os.popen(
"df -h"
).read()
>>>
print
(result)
Filesystem Size Used Avail Use
%
Mounted on
udev
3.9G
0
3.9G
0
%
/
dev
tmpfs
797M
9.4M
788M
2
%
/
run
/
dev
/
sda1
189G
10G
170G
6
%
/
tmpfs
3.9G
16M
3.9G
1
%
/
dev
/
shm
tmpfs
5.0M
4.0K
5.0M
1
%
/
run
/
lock
tmpfs
3.9G
0
3.9G
0
%
/
sys
/
fs
/
cgroup
cgmfs
100K
0
100K
0
%
/
run
/
cgmanager
/
fs
tmpfs
797M
76K
797M
1
%
/
run
/
user
/
1000
|
sys與os結合使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
tomcat@node:~$ vi e.py
#!/usr/bin/env python
import
os,sys
os.system(''.join(sys.argv[
1
:]))
# 執行
tomcat@node:~$ python e.py df
df: ‘
/
mnt
/
hgfs’: Protocol error
Filesystem
1K
-
blocks Used Available Use
%
Mounted on
udev
4059116
0
4059116
0
%
/
dev
tmpfs
815812
9596
806216
2
%
/
run
/
dev
/
sda1
198036724
10435852
177518160
6
%
/
tmpfs
4079040
15996
4063044
1
%
/
dev
/
shm
tmpfs
5120
4
5116
1
%
/
run
/
lock
tmpfs
4079040
0
4079040
0
%
/
sys
/
fs
/
cgroup
cgmfs
100
0
100
0
%
/
run
/
cgmanager
/
fs
tmpfs
815812
76
815736
1
%
/
run
/
user
/
1000
|
本身寫個補全模塊tab.py適合python2.x,python3.5都有自帶補全功能
#!/usr/bin/env python # python startup file import sys import readline import rlcompleter import atexit import os # tab completion readline.parse_and_bind('tab: complete') # history file histfile = os.path.join(os.environ['HOME'], '.pythonhistory') try: readline.read_history_file(histfile) except IOError: pass atexit.register(readline.write_history_file, histfile) del os, histfile, readline, rlcompleter
寫完後保存,導入就可使用
tomcat@node:~$ python Python 2.7.11 (default, Jul 27 2016, 18:09:58) [GCC 5.2.1 20151010] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import tab >>> import os >>> os. Display all 238 possibilities? (y or n) os.EX_CANTCREAT os.fchdir( os.EX_CONFIG os.fchmod( os.EX_DATAERR os.fchown( os.EX_IOERR os.fdatasync( os.EX_NOHOST os.fdopen(
你會發現,上面本身寫的tab.py模塊只能在當前目錄下導入,若是想在系統的何何一個地方都使用怎麼辦呢? 此時你就要把這個tab.py放到python全局環境變量目錄裏啦,用sys.path能夠查看,ubuntu是在/usr/lib/python2.7/dist-packages/,centos是在/usr/lib/python2.7/site-packages/
>>> import sys >>> sys.path ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-kylin-sso-client', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']
全部的Python對象都支持比較操做:
測試操做符:
python中不一樣類型的比較方法:
python中真和假的含義:
比較和相等測試會遞歸地應用於數據結構中
返回值爲True或False
if boolean_expression1: suite1 elif boolean_expression2: suite2 else: else_suite
注意:
elif語句是可選的
僅用與佔位,然後在填充相關語句時,可使用pass
一般在爲某變量設定默認值時一般用到以下表達式
A = X if Y else Z
或:
if Y: A = X else A = Z
其通用條件表達式語法格式爲:
expression1 if boolean_express else expression2
若是boolean_express的值爲True,則條件表達式的結果爲express1,不然爲express2
循環機制及應用場景
while循環:
for循環:
python也提供了一些可以進行隱性迭代的工具:
break: 跳出最內層的循環
continue: 跳出所處的最近層循環的開始處
pass: 佔位語句
while True: 死循環
語法格式:
while boolean_express: while_suite else: else_suite
注意:
示例1: >>> url = 'www.mageedu.com' >>> while url: print(url) url = url[1:] 示例2: >>> x = 0;y = 100 >>> while x < y: print(x) x += 1 示例3: >>> url = 'www.mageedu.com' >>> while url: print(url) url = url[:-1] else: print('game over')
while大量練習:
語法格式:
for expression1 in iterable: for_suite else: else_suite
一般,expression或是一個單獨的變量,或是一個變量序列,通常以元組的形式給出
若是以元組或列表用於expression,則其中的每一個數據項都會拆分到表達式的項
T = [(1,2),(3,4),(5,6),(7,8)] for (a,b) in T: print(a,b)
編寫循環的技巧:
(1)for循環比while循環執行速度快
(2)python提供了兩個內置函數,用於在for循環中定製特殊的循環python3.x 只有range,python2.x有(range,xrange)
range()函數:非完備遍歷
用於每隔必定的個數元素挑選一個元素
>>> S = 'How are you these days?' >>> range(0,len(S),2) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22] >>> for i in range(0,len(S),2): print(S[i])
修改列表
>>> L = [1,2,3,4,5] >>> for i in range(len(L)): L[i] += 1 >>> L
zip()函數:並行遍歷
取得一個或多個序列爲參數,將給定序列中的並排的元素配成元組,返回這些元組的列表
當參數長度不一樣時,zip會以最短序列的長度爲準
1.可在for循環中用於實現並行迭代
>>> L1 = [1,2,3,4,5,6,7] >>> L2 = ['a','b','c','d','e','f','g'] >>> zip(L1,L2)
2.zip也經常使用於動態構造字典
>>> keys = [1,2,3,4,5,6,7] >>> vaules = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] >>> D = {} >>> for (k,v) in zip(keys,values) D[k] = v >>> D
for大量練習:
場景1、用戶登錄驗證
#!/usr/bin/env python # -*- coding:utf-8 -*- import getpass name = 'tom' pwd = 123456 count = 0 while True: if count < 3: print("Please enter your name and password !") username = input("username:") password = getpass.getpass("password:") if username == name and password == pwd: print("恭喜你登錄成功!") break else: print("登錄失敗!用戶名或者密碼錯誤") else: print("你已經輸錯3次,正在退出....") break count += 1
場景2、猜年齡遊戲
#!/usr/bin/env python # -*- coding:utf-8 -*- age = 22 count = 0 for i in range(10): if count < 3: a = int(input("please input num:")) if a == age: print("恭喜你,答對了") break elif a > age: print("你猜的數字大了") else: print("你猜的數字小了") else: b = input("你太笨了,這都猜不對,你繼續玩嗎?(yes or not):") if b == 'yes': count = 0 continue else: print("Bye!下次再玩") count += 1