日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 人文社科 > 生活经验 >内容正文

生活经验

【Python之路】第二篇--初识Python

發(fā)布時(shí)間:2023/11/27 生活经验 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Python之路】第二篇--初识Python 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Python簡(jiǎn)介?

  Python可以應(yīng)用于眾多領(lǐng)域,如:數(shù)據(jù)分析、組件集成、網(wǎng)絡(luò)服務(wù)、圖像處理、數(shù)值計(jì)算和科學(xué)計(jì)算等眾多領(lǐng)域。目前業(yè)內(nèi)幾乎所有大中型互聯(lián)網(wǎng)企業(yè)都在使用Python,如:Youtube、Dropbox、BT、Quora(中國(guó)知乎)、豆瓣、知乎、Google、Yahoo!、Facebook、NASA、百度、騰訊、汽車之家、美團(tuán)等。互聯(lián)網(wǎng)公司廣泛使用Python來(lái)做的事一般有:自動(dòng)化運(yùn)維自動(dòng)化測(cè)試大數(shù)據(jù)分析、爬蟲(chóng)、Web 等。

Python的種類

    • Cpython
      ? ? Python的官方版本,使用C語(yǔ)言實(shí)現(xiàn),使用最為廣泛,CPython實(shí)現(xiàn)會(huì)將源文件(py文件)轉(zhuǎn)換成字節(jié)碼文件(pyc文件),然后運(yùn)行在Python虛擬機(jī)上。
    • Jyhton
      ? ? Python的Java實(shí)現(xiàn),Jython會(huì)將Python代碼動(dòng)態(tài)編譯成Java字節(jié)碼,然后在JVM上運(yùn)行。
    • IronPython
      ? ? Python的C#實(shí)現(xiàn),IronPython將Python代碼編譯成C#字節(jié)碼,然后在CLR上運(yùn)行。(與Jython類似)
    • PyPy(特殊)
      ? ? Python實(shí)現(xiàn)的Python,具有JIT(just In time)Compiler , 將Python的字節(jié)碼字節(jié)碼再編譯成機(jī)器碼。
    • RubyPython、Brython ...

?

為什么說(shuō)pypy會(huì)比Cpython快?

代碼有兩種常見(jiàn)的執(zhí)行方式,一種叫做編譯執(zhí)行,也就是直接將代碼轉(zhuǎn)換為CPU指令,然后連續(xù)執(zhí)行這些指令,好處當(dāng)然是非常快,一條多余的指令都沒(méi)有;壞處則是難以支持許多動(dòng)態(tài)特性。

一種叫做解釋執(zhí)行,也就是對(duì)每條語(yǔ)句在運(yùn)行時(shí)用解釋器去執(zhí)行它相應(yīng)的動(dòng)作,好處是實(shí)現(xiàn)起來(lái)非常簡(jiǎn)單,也很容易添加新特性,壞處則是執(zhí)行得非常慢,大部分CPU時(shí)間花在了解釋器運(yùn)行上面。

JIT技術(shù)是兩者的結(jié)合,首先讓代碼解釋執(zhí)行,同時(shí)收集信息,在收集到足夠信息的時(shí)候,將代碼動(dòng)態(tài)編譯成CPU指令,然后用CPU指令替代解釋執(zhí)行的過(guò)程,因?yàn)榫幾g發(fā)生在馬上要執(zhí)行之前,所以叫做Just-In-Time Compiler。編譯之后速度就是編譯執(zhí)行的速度了,自然比解釋執(zhí)行要快得多,所以運(yùn)用JIT的PyPy要比CPython快不少。

安裝Python

  windows:

1、下載安裝包https://www.python.org/downloads/2、安裝默認(rèn)安裝路徑:C:\python273、配置環(huán)境變量【右鍵計(jì)算機(jī)】--》【屬性】--》【高級(jí)系統(tǒng)設(shè)置】--》【高級(jí)】--》【環(huán)境變量】--》【在第二個(gè)內(nèi)容框中找到 變量名為Path 的一行,雙擊】 --> 【Python安裝目錄追加到變值值中,用 ; 分割】如:原來(lái)的值 ;C:\python27 切記前面有分號(hào)!!    

  Linux:

無(wú)需安裝,原裝Python環(huán)境
ps:如果自帶2.6,請(qǐng)更新至2.7

更新Python:

  Windows:

卸載重裝即可

  Linux:

Linux的yum依賴自帶Python,為防止錯(cuò)誤,此處更新其實(shí)就是再安裝一個(gè)Python查看默認(rèn)Python版本
python -V1、安裝gcc,用于編譯Python源碼yum install gcc
2、下載源碼包,https://www.python.org/ftp/python/
3、解壓并進(jìn)入源碼文件
4、編譯安裝./configuremake allmake install
5、查看版本/usr/local/bin/python2.7 -V
6、修改默認(rèn)Python版本mv /usr/bin/python /usr/bin/python2.6ln -s /usr/local/bin/python2.7 /usr/bin/python
7、防止yum執(zhí)行異常,修改yum使用的Python版本vi /usr/bin/yum將頭部 #!/usr/bin/python 修改為 #!/usr/bin/python2.6

Python 入門(mén)

解釋器

? ? ?我們經(jīng)常在py腳本的第一行 看到如下的代碼:

#!/usr/bin/python  或者  #!/usr/bin/env python  那么它的作用是?

  #!/usr/bin/Python 是告訴操作系統(tǒng)執(zhí)行這個(gè)腳本的時(shí)候,調(diào)用/usr/bin下的python解釋器;

  #!/usr/bin/env python這種用法是為了防止操作系統(tǒng)用戶沒(méi)有將python裝在默認(rèn)的/usr/bin路徑里。當(dāng)系統(tǒng)看到這一行的時(shí)候,首先會(huì)到env設(shè)置里查找python的安裝路徑,再調(diào)用對(duì)應(yīng)路徑下的解釋器程序完成操作。推薦這種寫(xiě)法

  如此一來(lái),我們就可以通過(guò):?./hello.py?執(zhí)行即可。

  ps:執(zhí)行前需給予 hello.py 執(zhí)行權(quán)限,chmod 755 hello.py

內(nèi)容編碼

  python解釋器在加載 .py 文件中的代碼時(shí),會(huì)對(duì)內(nèi)容進(jìn)行編碼(默認(rèn)ascill)

  顯然ASCII碼無(wú)法將世界上的各種文字和符號(hào)全部表示,所以,就需要新出一種可以代表所有字符和符號(hào)的編碼,即:Unicode

  Unicode(統(tǒng)一碼、萬(wàn)國(guó)碼、單一碼)是一種在計(jì)算機(jī)上使用的字符編碼。Unicode 是為了解決傳統(tǒng)的字符編碼方案的局限而產(chǎn)生的,它為每種語(yǔ)言中的每個(gè)字符設(shè)定了統(tǒng)一并且唯一的二進(jìn)制編碼,規(guī)定雖有的字符和符號(hào)最少由 16 位來(lái)表示(2個(gè)字節(jié)),即:2 **16 =?65536,注:此處說(shuō)的的是最少2個(gè)字節(jié),可能更多

  UTF-8,是對(duì)Unicode編碼的壓縮和優(yōu)化,他不再使用最少使用2個(gè)字節(jié),而是將所有的字符和符號(hào)進(jìn)行分類:ascii碼中的內(nèi)容用1個(gè)字節(jié)保存、歐洲的字符用2個(gè)字節(jié)保存,東亞的字符用3個(gè)字節(jié)保存...

  所以,python解釋器在加載 .py 文件中的代碼時(shí),會(huì)對(duì)內(nèi)容進(jìn)行編碼(默認(rèn)ascill),如果是如下代碼的話:

  報(bào)錯(cuò):ascii碼無(wú)法表示中文

#!/usr/bin/env pythonprint "你好,世界"

改正:應(yīng)該顯示的告訴python解釋器,用什么編碼來(lái)執(zhí)行源代碼,即:

#!/usr/bin/env python
# -*- coding: utf-8 -*-print "你好,世界"

Python2 中字符串的類型:

  Str:Bytes 類型

  Unicode:unicode 類型

# coding:utf8

s = '你好'
print len(s)     # 6
print type(s)   #  <str>
print repr(s)   #  utf8格式 : '\xe4\xbd\xa0\xe5\xa5\xbd'# Unicode 形式:

s = u'你好'
print len(s)     # 2
print type(s)   #  <unicode>
print repr(s)   #  u'\u4f60\u597d'# bytes 與 Unicode 混用拼接
print 'hello'+u'world'      # 先把 bytes => unicode
print '你好'+u'世界'         # 報(bào)錯(cuò), 只能將Ascii碼轉(zhuǎn)換,其余字符不行!

Python3 中字符串的類型:

  Str:Unicode 類型?

  Bytes:Bytes 類型

# bytes 與 Unicode 混用拼接
print 'hello'+b'world'      # 報(bào)錯(cuò),嚴(yán)格區(qū)分str和bytes

Python 編碼形式:

Python 編碼方式有兩種:

s = 'hello'
b = b'hello'#  編碼 encode  Str => Bytes
s.encode('utf8')
bytes(s,encoding='utf8')#  解碼 decode  Bytes => Str  (需要知道原先的編碼格式 utf8 or GBK ..)
b.decode('utf8')                 
str(s,encoding='utf8')

cmd 下的字符顯示問(wèn)題:

print('你好')# py2下為bytes 類型,根據(jù)cmd的編碼形式去顯示 修改為:print(u'你好')
# py3下為unicode 類型,正常顯示,符合ISO統(tǒng)一標(biāo)準(zhǔn)的,

查看.py文件的編碼格式:

import sys
print sys.getdefaultencoding()# py2: ascii
# py3: utf8

print問(wèn)題:

在py2里

# coding:utf8
print('你好')           # 你好
print(['你好','hello']) # ['\xe4\xbd\xa0\xe5\xa5\xbd', 'hello']

在py3里

# coding:utf8
print('你好')            # 你好
print(['你好','hello'])  # ['你好', 'hello']

Python 中,print語(yǔ)句都會(huì)執(zhí)行了:str()

# python2
sys.stdout.write(str(A) + '\n')

栗子:py3,將中文字符轉(zhuǎn)換成二進(jìn)制(bytes類型進(jìn)行for循環(huán)print,會(huì)輸出10進(jìn)制數(shù)!)

name = "李路"len(name)
#長(zhǎng)度等于2for i in name:print(i)bytes_list = bytes(i , encoding='utf-8')print(bytes_list )for b in bytes_list:print(b,bin(b))#李
#b'\xe6\x9d\x8e'
#230 0b11100110
#157 0b10011101
#142 0b10001110
#路
#b'\xe8\xb7\xaf'
#232 0b11101000
#183 0b10110111
#175 0b10101111

Str 與 Bytes

x = str()
# 功能:
# 1.創(chuàng)建字符串
# 2.轉(zhuǎn)換成字符串	  編碼類型x = bytes()
# 功能:
# 1.創(chuàng)建字節(jié)
# 2.轉(zhuǎn)換成字節(jié)	編碼類型
def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__"""str(object='') -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat will be decoded using the given encoding and error handler.Otherwise, returns the result of object.__str__() (if defined)or repr(object).encoding defaults to sys.getdefaultencoding().errors defaults to 'strict'.# (copied from class doc)"""pass
str
def __init__(self, value=b'', encoding=None, errors='strict'): # known special case of bytes.__init__"""bytes(iterable_of_ints) -> bytesbytes(string, encoding[, errors]) -> bytesbytes(bytes_or_buffer) -> immutable copy of bytes_or_bufferbytes(int) -> bytes object of size given by the parameter initialized with null bytesbytes() -> empty bytes objectConstruct an immutable array of bytes from:- an iterable yielding integers in range(256)- a text string encoded using the specified encoding- any object implementing the buffer API.- an integer# (copied from class doc)"""pass
bytes

三、注釋

  單行注釋:# 被注釋內(nèi)容

  多行注釋:""" 被注釋內(nèi)容 """

四、執(zhí)行腳本傳入?yún)?shù)

Python內(nèi)部提供一個(gè) sys 的模塊,其中的 sys.argv 用來(lái)捕獲執(zhí)行執(zhí)行python腳本時(shí)傳入的參數(shù)

#!/usr/bin/env python
# -*- coding: utf-8 -*-import sys
print sys.argv

比如用python test.py arg1 arg2運(yùn)行test.py代碼,那么argv列表的內(nèi)容是[' test.py','arg1','arg2']

五、 pyc 文件

執(zhí)行Python代碼時(shí),如果導(dǎo)入了其他的 .py 文件,那么,執(zhí)行過(guò)程中會(huì)自動(dòng)生成一個(gè)與其同名的 .pyc 文件,該文件就是Python解釋器編譯之后產(chǎn)生的字節(jié)碼。

ps:代碼經(jīng)過(guò)編譯可以產(chǎn)生字節(jié)碼;字節(jié)碼通過(guò)反編譯也可以得到代碼。執(zhí)行時(shí)優(yōu)先搜索字節(jié)碼文件

六、變量

變量定義的規(guī)則:

  • 變量名只能是 字母、數(shù)字或下劃線的任意組合
  • 變量名的第一個(gè)字符不能是數(shù)字
  • 以下關(guān)鍵字不能聲明為變量名
  • ['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']

七、輸入

#!/usr/bin/env python
# -*- coding: utf-8 -*-# 將用戶輸入的內(nèi)容賦值給 name 變量
name = raw_input("請(qǐng)輸入用戶名:")#python3
name = input("請(qǐng)輸入用戶名:")# 打印輸入的內(nèi)容
print(name)

輸入密碼時(shí),如果想要不可見(jiàn),需要利用getpass 模塊中的 getpass方法,即:

#!/usr/bin/env python
# -*- coding: utf-8 -*-import getpass# 將用戶輸入的內(nèi)容賦值給 name 變量
pwd = getpass.getpass("請(qǐng)輸入密碼:")# 打印輸入的內(nèi)容
print pwd

八、流程控制和縮進(jìn)

需求一、用戶登陸驗(yàn)證

#!/usr/bin/env python
# -*- coding: encoding -*-# 提示輸入用戶名和密碼# 驗(yàn)證用戶名和密碼
#     如果錯(cuò)誤,則輸出用戶名或密碼錯(cuò)誤
#     如果成功,則輸出 歡迎,XXX!import getpassname = raw_input('請(qǐng)輸入用戶名:')
pwd = getpass.getpass('請(qǐng)輸入密碼:')if name == "alex" and pwd == "cmd":print "歡迎,alex!"
else:print "用戶名和密碼錯(cuò)誤"

需求二、根據(jù)用戶輸入內(nèi)容輸出其權(quán)限

# 根據(jù)用戶輸入內(nèi)容打印其權(quán)限# alex --> 超級(jí)管理員
# eric --> 普通管理員
# tony,rain --> 業(yè)務(wù)主管
# 其他 --> 普通用戶name = raw_input('請(qǐng)輸入用戶名:')if name == "alex":print "超級(jí)管理員"
elif name == "eric":print "普通管理員"
elif name == "tony" or name == "rain":print "業(yè)務(wù)主管"
else:print "普通用戶"

九、while循環(huán)

1、基本循環(huán)

while 條件:# 循環(huán)體# 如果條件為真,那么循環(huán)體則執(zhí)行# 如果條件為假,那么循環(huán)體不執(zhí)行

2、break

break用于退出所有循環(huán)

while True:print "123"breakprint "456"

3、continue

continue用于退出當(dāng)前循環(huán),繼續(xù)下一次循環(huán)

while True:print "123"continueprint "456"

?

十、練習(xí)題

1、使用while循環(huán)輸入 1 2 3 4 5 6 ? ? 8 9 10

1 #!/usr/bin/env python
2 # -*-coding:utf-8 -*-
3 num = 0
4 while num <10:
5     num += 1
6     if num == 7:
7         continue
8     print(num)
View Code

2、求1-100的所有數(shù)的和

1 #!/usr/bin/env python
2 # -*-coding:utf-8 -*-
3 num = 1
4 sum = 0
5 while num<=100:
6     sum = sum + num
7     num +=1
8 
9 print(sum)
View Code

3、輸出 1-100 內(nèi)的所有奇數(shù)

 1 #!/usr/bin/env python
 2 # -*-coding:utf-8 -*-
 3 
 4 num = 1
 5 
 6 while 1:
 7     if  num % 2 == 1:
 8         print(num)
 9     num += 1
10     if num == 100:
11         break
View Code

4、輸出 1-100 內(nèi)的所有偶數(shù)

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3  
 4 num = 1
 5  
 6 while 1:
 7     if num % 2 ==0:
 8         print(num)
 9     if num == 100:
10         break
11     num += 1
View Code

5、求1-2+3-4+5 ... 99的所有數(shù)的和

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3  
 4 num = 1
 5 sum =0
 6  
 7 while 1:
 8     if num == 100:
 9         break
10     if num % 2 == 1:
11         sum = sum + num
12     else:
13         sum = sum - num
14     num +=1
15  
16 print(sum)
View Code

6、用戶登陸(三次機(jī)會(huì)重試)

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3  
 4 count = 0
 5  
 6 while 1:
 7     if count == 3:
 8         break
 9     username = input("username :")
10     password = input("password :")
11  
12     if username == 'admin' and password == 'admin123':
13         print(" Welcome !")
14         break
15     else:
16         count +=1
17         continue
View Code

?

  

轉(zhuǎn)載于:https://www.cnblogs.com/5poi/p/6046495.html

總結(jié)

以上是生活随笔為你收集整理的【Python之路】第二篇--初识Python的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。