最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

人生苦短我用python python如何快速入門(mén)?

 更新時(shí)間:2018年03月12日 14:22:41   投稿:lijiao  
這篇文章主要教大家如何快速入門(mén)python,一個(gè)簡(jiǎn)短而全面的入門(mén)教程帶你走入Python的大門(mén),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

假設(shè)你希望學(xué)習(xí)Python這門(mén)語(yǔ)言,卻苦于找不到一個(gè)簡(jiǎn)短而全面的入門(mén)教程。那么本教程將花費(fèi)十分鐘的時(shí)間帶你走入Python的大門(mén)。本文的內(nèi)容介于教程(Toturial)和速查手冊(cè)(CheatSheet)之間,因此只會(huì)包含一些基本概念。很顯然,如果你希望真正學(xué)好一門(mén)語(yǔ)言,你還是需要親自動(dòng)手實(shí)踐的。在此,我會(huì)假定你已經(jīng)有了一定的編程基礎(chǔ),因此我會(huì)跳過(guò)大部分非Python語(yǔ)言的相關(guān)內(nèi)容。本文將高亮顯示重要的關(guān)鍵字,以便你可以很容易看到它們。另外需要注意的是,由于本教程篇幅有限,有很多內(nèi)容我會(huì)直接使用代碼來(lái)說(shuō)明加以少許注釋。

Python的語(yǔ)言特性

Python是一門(mén)具有強(qiáng)類(lèi)型(即變量類(lèi)型是強(qiáng)制要求的)、動(dòng)態(tài)性、隱式類(lèi)型(不需要做變量聲明)、大小寫(xiě)敏感(var和VAR代表了不同的變量)以及面向?qū)ο?一切皆為對(duì)象)等特點(diǎn)的編程語(yǔ)言。

獲取幫助

你可以很容易的通過(guò)Python解釋器獲取幫助。如果你想知道一個(gè)對(duì)象(object)是如何工作的,那么你所需要做的就是調(diào)用help(<object>)!另外還有一些有用的方法,dir()會(huì)顯示該對(duì)象的所有方法,還有<object>.__doc__會(huì)顯示其文檔:

>>> help(5)
Help on int object:
(etc etc)>>> dir(5)
['__abs__', '__add__', ...]>>> abs.__doc__'abs(number) -> number

Return the absolute value of the argument.'

語(yǔ)法

Python中沒(méi)有強(qiáng)制的語(yǔ)句終止字符,且代碼塊是通過(guò)縮進(jìn)來(lái)指示的。縮進(jìn)表示一個(gè)代碼塊的開(kāi)始,逆縮進(jìn)則表示一個(gè)代碼塊的結(jié)束。聲明以冒號(hào)(:)字符結(jié)束,并且開(kāi)啟一個(gè)縮進(jìn)級(jí)別。單行注釋以井號(hào)字符(#)開(kāi)頭,多行注釋則以多行字符串的形式出現(xiàn)。賦值(事實(shí)上是將對(duì)象綁定到名字)通過(guò)等號(hào)(“=”)實(shí)現(xiàn),雙等號(hào)(“==”)用于相等判斷,”+=”和”-=”用于增加/減少運(yùn)算(由符號(hào)右邊的值確定增加/減少的值)。這適用于許多數(shù)據(jù)類(lèi)型,包括字符串。你也可以在一行上使用多個(gè)變量。例如:

>>> myvar = 3>>> myvar += 2>>> myvar5>>> myvar -= 1>>> myvar4"""This is a multiline comment.
The following lines concatenate the two strings.""">>> mystring = "Hello">>> mystring += " world.">>> print mystring
Hello world.# This swaps the variables in one line(!).# It doesn't violate strong typing because values aren't# actually being assigned, but new objects are bound to# the old names.>>> myvar, mystring = mystring, myvar


數(shù)據(jù)類(lèi)型

Python具有列表(list)、元組(tuple)和字典(dictionaries)三種基本的數(shù)據(jù)結(jié)構(gòu),而集合(sets)則包含在集合庫(kù)中(但從Python2.5版本開(kāi)始正式成為Python內(nèi)建類(lèi)型)。列表的特點(diǎn)跟一維數(shù)組類(lèi)似(當(dāng)然你也可以創(chuàng)建類(lèi)似多維數(shù)組的“列表的列表”),字典則是具有關(guān)聯(lián)關(guān)系的數(shù)組(通常也叫做哈希表),而元組則是不可變的一維數(shù)組(Python中“數(shù)組”可以包含任何類(lèi)型的元素,這樣你就可以使用混合元素,例如整數(shù)、字符串或是嵌套包含列表、字典或元組)。數(shù)組中第一個(gè)元素索引值(下標(biāo))為0,使用負(fù)數(shù)索引值能夠從后向前訪問(wèn)數(shù)組元素,-1表示最后一個(gè)元素。數(shù)組元素還能指向函數(shù)。來(lái)看下面的用法:

>>> sample = [1, ["another", "list"], ("a", "tuple")]>>> mylist = ["List item 1", 2, 3.14]>>> mylist[0] = "List item 1 again" # We're changing the item.>>> mylist[-1] = 3.21 # Here, we refer to the last item.>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}>>> mydict["pi"] = 3.15 # This is how you change dictionary values.>>> mytuple = (1, 2, 3)>>> myfunction = len>>> print myfunction(mylist)3

你可以使用:運(yùn)算符訪問(wèn)數(shù)組中的某一段,如果:左邊為空則表示從第一個(gè)元素開(kāi)始,同理:右邊為空則表示到最后一個(gè)元素結(jié)束。負(fù)數(shù)索引則表示從后向前數(shù)的位置(-1是最后一個(gè)項(xiàng)目),例如:

>>> mylist = ["List item 1", 2, 3.14]>>> print mylist[:]
['List item 1', 2, 3.1400000000000001]>>> print mylist[0:2]
['List item 1', 2]>>> print mylist[-3:-1]
['List item 1', 2]>>> print mylist[1:]
[2, 3.14]# Adding a third parameter, "step" will have Python step in# N item increments, rather than 1.# E.g., this will return the first item, then go to the third and# return that (so, items 0 and 2 in 0-indexing).>>> print mylist[::2]
['List item 1', 3.14]

字符串

Python中的字符串使用單引號(hào)(‘)或是雙引號(hào)(“)來(lái)進(jìn)行標(biāo)示,并且你還能夠在通過(guò)某一種標(biāo)示的字符串中使用另外一種標(biāo)示符(例如 “He said ‘hello'.”)。而多行字符串可以通過(guò)三個(gè)連續(xù)的單引號(hào)(”')或是雙引號(hào)(“””)來(lái)進(jìn)行標(biāo)示。Python可以通過(guò)u”This is a unicode string”這樣的語(yǔ)法使用Unicode字符串。如果想通過(guò)變量來(lái)填充字符串,那么可以使用取模運(yùn)算符(%)和一個(gè)元組。使用方式是在目標(biāo)字符串中從左至右使用%s來(lái)指代變量的位置,或者使用字典來(lái)代替,示例如下:

>>>print "Name: %s\
Number: %s\
String: %s" % (myclass.name, 3, 3 * "-")
Name: Poromenos
Number: 3String: ---

strString = """This is
a multiline
string."""# WARNING: Watch out for the trailing s in "%(key)s".>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}
This is a test.

流程控制

Python中可以使用if、for和while來(lái)實(shí)現(xiàn)流程控制。Python中并沒(méi)有select,取而代之使用if來(lái)實(shí)現(xiàn)。使用for來(lái)枚舉列表中的元素。如果希望生成一個(gè)由數(shù)字組成的列表,則可以使用range(<number>)函數(shù)。以下是這些聲明的語(yǔ)法示例:

rangelist = range(10)>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]for number in rangelist: # Check if number is one of
 # the numbers in the tuple.
 if number in (3, 4, 7, 9):  # "Break" terminates a for without
  # executing the "else" clause.
  break
 else:  # "Continue" starts the next iteration
  # of the loop. It's rather useless here,
  # as it's the last statement of the loop.
  continueelse: # The "else" clause is optional and is
 # executed only if the loop didn't "break".
 pass # Do nothingif rangelist[1] == 2: print "The second item (lists are 0-based) is 2"elif rangelist[1] == 3: print "The second item (lists are 0-based) is 3"else: print "Dunno"while rangelist[1] == 1: pass

函數(shù)

函數(shù)通過(guò)“def”關(guān)鍵字進(jìn)行聲明??蛇x參數(shù)以集合的方式出現(xiàn)在函數(shù)聲明中并緊跟著必選參數(shù),可選參數(shù)可以在函數(shù)聲明中被賦予一個(gè)默認(rèn)值。已命名的參數(shù)需要賦值。函數(shù)可以返回一個(gè)元組(使用元組拆包可以有效返回多個(gè)值)。Lambda函數(shù)是由一個(gè)單獨(dú)的語(yǔ)句組成的特殊函數(shù),參數(shù)通過(guò)引用進(jìn)行傳遞,但對(duì)于不可變類(lèi)型(例如元組,整數(shù),字符串等)則不能夠被改變。這是因?yàn)橹粋鬟f了該變量的內(nèi)存地址,并且只有丟棄了舊的對(duì)象后,變量才能綁定一個(gè)對(duì)象,所以不可變類(lèi)型是被替換而不是改變(譯者注:雖然Python傳遞的參數(shù)形式本質(zhì)上是引用傳遞,但是會(huì)產(chǎn)生值傳遞的效果)。例如:

# 作用等同于 def funcvar(x): return x + 1funcvar = lambda x: x + 1>>> print funcvar(1)2# an_int 和 a_string 是可選參數(shù),它們有默認(rèn)值# 如果調(diào)用 passing_example 時(shí)只指定一個(gè)參數(shù),那么 an_int 缺省為 2 ,a_string 缺省為 A default string。如果調(diào)用 passing_example 時(shí)指定了前面兩個(gè)參數(shù),a_string 仍缺省為 A default string。# a_list 是必備參數(shù),因?yàn)樗鼪](méi)有指定缺省值。def passing_example(a_list, an_int=2, a_string="A default string"):
 a_list.append("A new item")
 an_int = 4
 return a_list, an_int, a_string>>> my_list = [1, 2, 3]>>> my_int = 10>>> print passing_example(my_list, my_int)
([1, 2, 3, 'A new item'], 4, "A default string")>>> my_list
[1, 2, 3, 'A new item']>>> my_int10

類(lèi)

Python支持有限的多繼承形式。私有變量和方法可以通過(guò)添加至少兩個(gè)前導(dǎo)下劃線和最多尾隨一個(gè)下劃線的形式進(jìn)行聲明(如“__spam”,這只是慣例,而不是Python的強(qiáng)制要求)。當(dāng)然,我們也可以給類(lèi)的實(shí)例取任意名稱(chēng)。例如:

class MyClass(object):
 common = 10
 def __init__(self):
  self.myvariable = 3
 def myfunction(self, arg1, arg2):
  return self.myvariable # This is the class instantiation>>> classinstance = MyClass()>>> classinstance.myfunction(1, 2)3# This variable is shared by all classes.>>> classinstance2 = MyClass()>>> classinstance.common10>>> classinstance2.common10# Note how we use the class name# instead of the instance.>>> MyClass.common = 30>>> classinstance.common30>>> classinstance2.common30# This will not update the variable on the class,# instead it will bind a new object to the old# variable name.>>> classinstance.common = 10>>> classinstance.common10>>> classinstance2.common30>>> MyClass.common = 50# This has not changed, because "common" is# now an instance variable.>>> classinstance.common10>>> classinstance2.common50# This class inherits from MyClass. The example# class above inherits from "object", which makes# it what's called a "new-style class".# Multiple inheritance is declared as:# class OtherClass(MyClass1, MyClass2, MyClassN)class OtherClass(MyClass):
 # The "self" argument is passed automatically
 # and refers to the class instance, so you can set
 # instance variables as above, but from inside the class.
 def __init__(self, arg1):
  self.myvariable = 3
  print arg1>>> classinstance = OtherClass("hello")
hello>>> classinstance.myfunction(1, 2)3# This class doesn't have a .test member, but# we can add one to the instance anyway. Note# that this will only be a member of classinstance.>>> classinstance.test = 10>>> classinstance.test10

異常

Python中的異常由 try-except [exceptionname] 塊處理,例如:

def some_function():
 try:  # Division by zero raises an exception
  10 / 0
 except ZeroDivisionError:  print "Oops, invalid."
 else:  # Exception didn't occur, we're good.
  pass
 finally:  # This is executed after the code block is run
  # and all exceptions have been handled, even
  # if a new exception is raised while handling.
  print "We're done with that.">>> some_function()
Oops, invalid.
We're done with that.

導(dǎo)入

外部庫(kù)可以使用 import [libname] 關(guān)鍵字來(lái)導(dǎo)入。同時(shí),你還可以用 from [libname] import [funcname] 來(lái)導(dǎo)入所需要的函數(shù)。例如:

import randomfrom time import clock
randomint = random.randint(1, 100)>>> print randomint64

文件I / O

Python針對(duì)文件的處理有很多內(nèi)建的函數(shù)庫(kù)可以調(diào)用。例如,這里演示了如何序列化文件(使用pickle庫(kù)將數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)換為字符串):

import pickle
mylist = ["This", "is", 4, 13327]# Open the file C:\\binary.dat for writing. The letter r before the# filename string is used to prevent backslash escaping.myfile = open(r"C:\\binary.dat", "w")
pickle.dump(mylist, myfile)
myfile.close()

myfile = open(r"C:\\text.txt", "w")
myfile.write("This is a sample string")
myfile.close()

myfile = open(r"C:\\text.txt")>>> print myfile.read()'This is a sample string'myfile.close()# Open the file for reading.myfile = open(r"C:\\binary.dat")
loadedlist = pickle.load(myfile)
myfile.close()>>> print loadedlist
['This', 'is', 4, 13327]

其它雜項(xiàng)

  • 數(shù)值判斷可以鏈接使用,例如 1<a<3 能夠判斷變量 a 是否在1和3之間。
  • 可以使用 del 刪除變量或刪除數(shù)組中的元素。
  • 列表推導(dǎo)式(List Comprehension)提供了一個(gè)創(chuàng)建和操作列表的有力工具。列表推導(dǎo)式由一個(gè)表達(dá)式以及緊跟著這個(gè)表達(dá)式的for語(yǔ)句構(gòu)成,for語(yǔ)句還可以跟0個(gè)或多個(gè)if或for語(yǔ)句,來(lái)看下面的例子:
>>> lst1 = [1, 2, 3]>>> lst2 = [3, 4, 5]>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]# Check if an item has a specific property.# "any" returns true if any item in the list is true.>>> any([i % 3 for i in [3, 3, 4, 4, 3]])True# This is because 4 % 3 = 1, and 1 is true, so any()# returns True.# Check how many items have this property.>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)2>>> del lst1[0]>>> print lst1
[2, 3]>>> del lst1

全局變量在函數(shù)之外聲明,并且可以不需要任何特殊的聲明即能讀取,但如果你想要修改全局變量的值,就必須在函數(shù)開(kāi)始之處用global關(guān)鍵字進(jìn)行聲明,否則Python會(huì)將此變量按照新的局部變量處理(請(qǐng)注意,如果不注意很容易被坑)。例如:

number = 5def myfunc():
 # This will print 5.
 print numberdef anotherfunc():
 # This raises an exception because the variable has not
 # been bound before printing. Python knows that it an
 # object will be bound to it later and creates a new, local
 # object instead of accessing the global one.
 print number
 number = 3def yetanotherfunc():
 global number # This will correctly change the global.
 number = 3

推薦書(shū)單:

你眼中的Python大牛 應(yīng)該都有這份書(shū)單

Python書(shū)單 不將就

不可錯(cuò)過(guò)的十本Python好書(shū)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python中waitKey實(shí)例用法講解

    python中waitKey實(shí)例用法講解

    在本篇文章里小編給大家整理了一篇關(guān)于python中waitKey實(shí)例用法講解,有興趣的朋友們可以參考學(xué)習(xí)下。
    2021-04-04
  • python實(shí)現(xiàn)鍵盤(pán)輸入的實(shí)操方法

    python實(shí)現(xiàn)鍵盤(pán)輸入的實(shí)操方法

    在本篇文章里小編給各位分享了關(guān)于python怎么實(shí)現(xiàn)鍵盤(pán)輸入的圖文步驟以及相關(guān)知識(shí)點(diǎn)內(nèi)容,需要的朋友們參考下。
    2019-07-07
  • python實(shí)現(xiàn)將一個(gè)數(shù)組逆序輸出的方法

    python實(shí)現(xiàn)將一個(gè)數(shù)組逆序輸出的方法

    今天小編就為大家分享一篇python實(shí)現(xiàn)將一個(gè)數(shù)組逆序輸出的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • mvc框架打造筆記之wsgi協(xié)議的優(yōu)缺點(diǎn)以及接口實(shí)現(xiàn)

    mvc框架打造筆記之wsgi協(xié)議的優(yōu)缺點(diǎn)以及接口實(shí)現(xiàn)

    這篇文章主要給大家介紹了關(guān)于mvc框架打造筆記之wsgi協(xié)議的優(yōu)缺點(diǎn)以及接口實(shí)現(xiàn)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-08-08
  • Python實(shí)現(xiàn)批量轉(zhuǎn)換文件編碼的方法

    Python實(shí)現(xiàn)批量轉(zhuǎn)換文件編碼的方法

    這篇文章主要介紹了Python實(shí)現(xiàn)批量轉(zhuǎn)換文件編碼的方法,涉及Python針對(duì)文件的遍歷及編碼轉(zhuǎn)換實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-07-07
  • Pytorch中torch.utils.checkpoint()及用法詳解

    Pytorch中torch.utils.checkpoint()及用法詳解

    在PyTorch中,torch.utils.checkpoint?模塊提供了實(shí)現(xiàn)梯度檢查點(diǎn)(也稱(chēng)為checkpointing)的功能,這篇文章給大家介紹了Pytorch中torch.utils.checkpoint()的相關(guān)知識(shí),感興趣的朋友一起看看吧
    2024-03-03
  • 使用gunicorn部署django項(xiàng)目的問(wèn)題

    使用gunicorn部署django項(xiàng)目的問(wèn)題

    這篇文章主要介紹了使用gunicorn部署django項(xiàng)目,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12
  • python制作填詞游戲步驟詳解

    python制作填詞游戲步驟詳解

    在本文里我們給大家整理了關(guān)于python制作填詞游戲的具體步驟以及實(shí)例代碼,需要的朋友們跟著學(xué)習(xí)下。
    2019-05-05
  • Python第三方模塊apscheduler安裝和基本使用

    Python第三方模塊apscheduler安裝和基本使用

    本文主要介紹了Python第三方模塊apscheduler安裝和基本使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • Python Opencv任意形狀目標(biāo)檢測(cè)并繪制框圖

    Python Opencv任意形狀目標(biāo)檢測(cè)并繪制框圖

    這篇文章主要為大家詳細(xì)介紹了Python Opencv任意形狀目標(biāo)檢測(cè),并繪制框圖,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-07-07

最新評(píng)論

娄烦县| 禄劝| 兴和县| 张北县| 香河县| 贵溪市| 依安县| 汉寿县| 巴中市| 亳州市| 宁阳县| 青田县| 荥阳市| 招远市| 孟津县| 景德镇市| 青海省| 靖远县| 富平县| 腾冲县| 乌兰县| 河北省| 贵州省| 西吉县| 霞浦县| 沁阳市| 白水县| 桦南县| 仪陇县| 绥化市| 桂阳县| 石屏县| 吴川市| 张家界市| 赣榆县| 和田县| 邛崃市| 长兴县| 九龙坡区| 阿拉善右旗| 富裕县|