python語言基礎(chǔ)知識有哪些-創(chuàng)新互聯(lián)

這篇文章主要介紹python語言基礎(chǔ)知識有哪些,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

成都創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比故城網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式故城網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋故城地區(qū)。費用合理售后完善,10多年實體公司更值得信賴。

Python 是 90 年代初由 Guido Van Rossum 創(chuàng)立的。它是當(dāng)前最流行的程序語言之一。它那純凈的語法令我一見傾心,它簡直就是可以運行的偽碼。

請注意:本文以 Python 2.7 為基準(zhǔn),但也應(yīng)該適用于所有 2.X 版本。還要繼續(xù)學(xué)習(xí)最新的 Python 3 哦!

# Single line comments start with a hash.
# 單行注釋由一個井號開頭。
""" Multiline strings can be written
 using three "'s, and are often used
 as comments
 三個雙引號(或單引號)之間可以寫多行字符串,
 通常用來寫注釋。
"""
 
####################################################
## 1. Primitive Datatypes and Operators
## 1. 基本數(shù)據(jù)類型和操作符
####################################################
 
# You have numbers
# 數(shù)字就是數(shù)字
3 #=> 3
 
# Math is what you would expect
# 四則運算也是你所期望的那樣
1 + 1 #=> 2
8 - 1 #=> 7
10 * 2 #=> 20
35 / 5 #=> 7
 
# Division is a bit tricky. It is integer division and floors the results
# automatically.
# 除法有一點棘手。
# 對于整數(shù)除法來說,計算結(jié)果會自動取整。
5 / 2 #=> 2
 
# To fix division we need to learn about floats.
# 為了修正除法的問題,我們需要先學(xué)習(xí)浮點數(shù)。
2.0  # This is a float
2.0  # 這是一個浮點數(shù)
11.0 / 4.0 #=> 2.75 ahhh...much better
11.0 / 4.0 #=> 2.75 啊……這樣就好多了
 
# Enforce precedence with parentheses
# 使用小括號來強制計算的優(yōu)先順序
(1 + 3) * 2 #=> 8
 
# Boolean values are primitives
# 布爾值也是基本數(shù)據(jù)類型
True
False
 
# negate with not
# 使用 not 來取反
not True #=> False
not False #=> True
 
# Equality is ==
# 等式判斷用 ==
1 == 1 #=> True
2 == 1 #=> False
 
# Inequality is !=
# 不等式判斷是用 !=
1 != 1 #=> False
2 != 1 #=> True
 
# More comparisons
# 還有更多的比較運算
1 < 10 #=> True
1 > 10 #=> False
2 <= 2 #=> True
2 >= 2 #=> True
 
# Comparisons can be chained!
# 居然可以把比較運算串連起來!
1 < 2 < 3 #=> True
2 < 3 < 2 #=> False
 
# Strings are created with " or '
# 使用 " 或 ' 來創(chuàng)建字符串
"This is a string."
'This is also a string.'
 
# Strings can be added too!
# 字符串也可以相加!
"Hello " + "world!" #=> "Hello world!"
 
# A string can be treated like a list of characters
# 一個字符串可以視為一個字符的列表
# (譯注:后面會講到“列表”。)
"This is a string"[0] #=> 'T'
 
# % can be used to format strings, like this:
# % 可以用來格式化字符串,就像這樣:
"%s can be %s" % ("strings", "interpolated")
 
# A newer way to format strings is the format method.
# This method is the preferred way
# 后來又有一種格式化字符串的新方法:format 方法。
# 我們推薦使用這個方法。
"{0} can be {1}".format("strings", "formatted")
 
# You can use keywords if you don't want to count.
# 如果你不喜歡數(shù)數(shù)的話,可以使用關(guān)鍵字(變量)。
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
 
# None is an object
# None 是一個對象
None #=> None
 
# Don't use the equality `==` symbol to compare objects to None
# Use `is` instead
# 不要使用相等符號 `==` 來把對象和 None 進行比較,
# 而要用 `is`。
"etc" is None #=> False
None is None #=> True
 
# The 'is' operator tests for object identity. This isn't
# very useful when dealing with primitive values, but is
# very useful when dealing with objects.
# 這個 `is` 操作符用于比較兩個對象的標(biāo)識。
# (譯注:對象一旦建立,其標(biāo)識就不會改變,可以認(rèn)為它就是對象的內(nèi)存地址。)
# 在處理基本數(shù)據(jù)類型時基本用不上,
# 但它在處理對象時很有用。
 
# None, 0, and empty strings/lists all evaluate to False.
# All other values are True
# None、0 以及空字符串和空列表都等于 False,
# 除此以外的所有值都等于 True。
0 == False #=> True
"" == False #=> True
 
 
####################################################
## 2. Variables and Collections
## 2. 變量和集合
####################################################
 
# Printing is pretty easy
# 打印輸出很簡單
print "I'm Python. Nice to meet you!"
 
 
# No need to declare variables before assigning to them.
# 在賦值給變量之前不需要聲明
some_var = 5 # Convention is to use lower_case_with_underscores
    # 變量名的約定是使用下劃線分隔的小寫單詞
some_var #=> 5
 
# Accessing a previously unassigned variable is an exception.
# See Control Flow to learn more about exception handling.
# 訪問一個未賦值的變量會產(chǎn)生一個異常。
# 進一步了解異常處理,可參見下一節(jié)《控制流》。
some_other_var # Raises a name error
    # 會拋出一個名稱錯誤
 
# if can be used as an expression
# if 可以作為表達(dá)式來使用
"yahoo!" if 3 > 2 else 2 #=> "yahoo!"
 
# Lists store sequences
# 列表用于存儲序列
li = []
# You can start with a prefilled list
# 我們先嘗試一個預(yù)先填充好的列表
other_li = [4, 5, 6]
 
# Add stuff to the end of a list with append
# 使用 append 方法把元素添加到列表的尾部
li.append(1) #li is now [1]
    #li 現(xiàn)在是 [1]
li.append(2) #li is now [1, 2]
    #li 現(xiàn)在是 [1, 2]
li.append(4) #li is now [1, 2, 4]
    #li 現(xiàn)在是 [1, 2, 4]
li.append(3) #li is now [1, 2, 4, 3]
    #li 現(xiàn)在是 [1, 2, 4, 3]
# Remove from the end with pop
# 使用 pop 來移除最后一個元素
li.pop()  #=> 3 and li is now [1, 2, 4]
    #=> 3,然后 li 現(xiàn)在是 [1, 2, 4]
# Let's put it back
# 我們再把它放回去
li.append(3) # li is now [1, 2, 4, 3] again.
    # li 現(xiàn)在又是 [1, 2, 4, 3] 了
 
# Access a list like you would any array
# 像訪問其它語言的數(shù)組那樣訪問列表
li[0] #=> 1
# Look at the last element
# 查詢最后一個元素
li[-1] #=> 3
 
# Looking out of bounds is an IndexError
# 越界查詢會產(chǎn)生一個索引錯誤
li[4] # Raises an IndexError
  # 拋出一個索引錯誤
 
# You can look at ranges with slice syntax.
# (It's a closed/open range for you mathy types.)
# 你可以使用切片語法來查詢列表的一個范圍。
# (這個范圍相當(dāng)于數(shù)學(xué)中的左閉右開區(qū)間。)
li[1:3] #=> [2, 4]
# Omit the beginning
# 省略開頭
li[2:] #=> [4, 3]
# Omit the end
# 省略結(jié)尾
li[:3] #=> [1, 2, 4]
 
# Remove arbitrary elements from a list with del
# 使用 del 來刪除列表中的任意元素
del li[2] # li is now [1, 2, 3]
   # li 現(xiàn)在是 [1, 2, 3]
 
# You can add lists
# 可以把列表相加
li + other_li #=> [1, 2, 3, 4, 5, 6] - Note: li and other_li is left alone
    #=> [1, 2, 3, 4, 5, 6] - 請留意 li 和 other_li 并不會被修改
 
# Concatenate lists with extend
# 使用 extend 來合并列表
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
     # 現(xiàn)在 li 是 [1, 2, 3, 4, 5, 6]
 
# Check for existence in a list with in
# 用 in 來檢查是否存在于某個列表中
1 in li #=> True
 
# Examine the length with len
# 用 len 來檢測列表的長度
len(li) #=> 6
 
 
# Tuples are like lists but are immutable.
# 元組很像列表,但它是“不可變”的。
tup = (1, 2, 3)
tup[0] #=> 1
tup[0] = 3 # Raises a TypeError
   # 拋出一個類型錯誤
 
# You can do all those list thingies on tuples too
# 操作列表的方式通常也能用在元組身上
len(tup) #=> 3
tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
tup[:2] #=> (1, 2)
2 in tup #=> True
 
# You can unpack tuples (or lists) into variables
# 你可以把元組(或列表)中的元素解包賦值給多個變量
a, b, c = (1, 2, 3)  # a is now 1, b is now 2 and c is now 3
      # 現(xiàn)在 a 是 1,b 是 2,c 是 3
# Tuples are created by default if you leave out the parentheses
# 如果你省去了小括號,那么元組會被自動創(chuàng)建
d, e, f = 4, 5, 6
# Now look how easy it is to swap two values
# 再來看看交換兩個值是多么簡單。
e, d = d, e  # d is now 5 and e is now 4
    # 現(xiàn)在 d 是 5 而 e 是 4
 
 
# Dictionaries store mappings
# 字典用于存儲映射關(guān)系
empty_dict = {}
# Here is a prefilled dictionary
# 這是一個預(yù)先填充的字典
filled_dict = {"one": 1, "two": 2, "three": 3}
 
# Look up values with []
# 使用 [] 來查詢鍵值
filled_dict["one"] #=> 1
 
# Get all keys as a list
# 將字典的所有鍵名獲取為一個列表
filled_dict.keys() #=> ["three", "two", "one"]
# Note - Dictionary key ordering is not guaranteed.
# Your results might not match this exactly.
# 請注意:無法保證字典鍵名的順序如何排列。
# 你得到的結(jié)果可能跟上面的示例不一致。
 
# Get all values as a list
# 將字典的所有鍵值獲取為一個列表
filled_dict.values() #=> [3, 2, 1]
# Note - Same as above regarding key ordering.
# 請注意:順序的問題和上面一樣。
 
# Check for existence of keys in a dictionary with in
# 使用 in 來檢查一個字典是否包含某個鍵名
"one" in filled_dict #=> True
1 in filled_dict #=> False
 
# Looking up a non-existing key is a KeyError
# 查詢一個不存在的鍵名會產(chǎn)生一個鍵名錯誤
filled_dict["four"] # KeyError
     # 鍵名錯誤
 
# Use get method to avoid the KeyError
# 所以要使用 get 方法來避免鍵名錯誤
filled_dict.get("one") #=> 1
filled_dict.get("four") #=> None
# The get method supports a default argument when the value is missing
# get 方法支持傳入一個默認(rèn)值參數(shù),將在取不到值時返回。
filled_dict.get("one", 4) #=> 1
filled_dict.get("four", 4) #=> 4
 
# Setdefault method is a safe way to add new key-value pair into dictionary
# Setdefault 方法可以安全地把新的名值對添加到字典里
filled_dict.setdefault("five", 5) #filled_dict["five"] is set to 5
         #filled_dict["five"] 被設(shè)置為 5
filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5
         #filled_dict["five"] 仍然為 5
 
 
# Sets store ... well sets
# set 用于保存集合
empty_set = set()
# Initialize a set with a bunch of values
# 使用一堆值來初始化一個集合
some_set = set([1,2,2,3,4]) # some_set is now set([1, 2, 3, 4])
       # some_set 現(xiàn)在是 set([1, 2, 3, 4])
 
# Since Python 2.7, {} can be used to declare a set
# 從 Python 2.7 開始,{} 可以用來聲明一個集合
filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
        # (譯注:集合是種無序不重復(fù)的元素集,因此重復(fù)的 2 被濾除了。)
        # (譯注:{} 不會創(chuàng)建一個空集合,只會創(chuàng)建一個空字典。)
 
# Add more items to a set
# 把更多的元素添加進一個集合
filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
     # filled_set 現(xiàn)在是 {1, 2, 3, 4, 5}
 
# Do set intersection with &
# 使用 & 來獲取交集
other_set = {3, 4, 5, 6}
filled_set & other_set #=> {3, 4, 5}
 
# Do set union with |
# 使用 | 來獲取并集
filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
 
# Do set difference with -
# 使用 - 來獲取補集
{1,2,3,4} - {2,3,5} #=> {1, 4}
 
# Check for existence in a set with in
# 使用 in 來檢查是否存在于某個集合中
2 in filled_set #=> True
10 in filled_set #=> False
 
 
####################################################
## 3. Control Flow
## 3. 控制流
####################################################
 
# Let's just make a variable
# 我們先創(chuàng)建一個變量
some_var = 5
 
# Here is an if statement. Indentation is significant in python!
# prints "some_var is smaller than 10"
# 這里有一個條件語句??s進在 Python 中可是很重要的哦!
# 程序會打印出 "some_var is smaller than 10"
# (譯注:意為“some_var 比 10 小”。)
if some_var > 10:
 print "some_var is totally bigger than 10."
 # (譯注:意為“some_var 完全比 10 大”。)
elif some_var < 10: # This elif clause is optional.
      # 這里的 elif 子句是可選的
 print "some_var is smaller than 10."
 # (譯注:意為“some_var 比 10 小”。)
else:   # This is optional too.
    # 這一句也是可選的
 print "some_var is indeed 10."
 # (譯注:意為“some_var 就是 10”。)
 
 
"""
For loops iterate over lists
for 循環(huán)可以遍歷列表
prints:
如果要打印出:
 dog is a mammal
 cat is a mammal
 mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
 # You can use % to interpolate formatted strings
 # 別忘了你可以使用 % 來格式化字符串
 print "%s is a mammal" % animal
 # (譯注:意為“%s 是哺乳動物”。)
 
"""
`range(number)` returns a list of numbers 
from zero to the given number
`range(數(shù)字)` 會返回一個數(shù)字列表,
這個列表將包含從零到給定的數(shù)字。
prints:
如果要打印出:
 0
 1
 2
 3
"""
for i in range(4):
 print i
 
"""
While loops go until a condition is no longer met.
while 循環(huán)會一直繼續(xù),直到條件不再滿足。
prints:
如果要打印出:
 0
 1
 2
 3
"""
x = 0
while x < 4:
 print x
 x += 1 # Shorthand for x = x + 1
   # 這是 x = x + 1 的簡寫方式
 
# Handle exceptions with a try/except block
# 使用 try/except 代碼塊來處理異常
 
# Works on Python 2.6 and up:
# 適用于 Python 2.6 及以上版本:
try:
 # Use raise to raise an error
 # 使用 raise 來拋出一個錯誤
 raise IndexError("This is an index error")
 # 拋出一個索引錯誤:“這是一個索引錯誤”。
except IndexError as e:
 pass # Pass is just a no-op. Usually you would do recovery here.
   # pass 只是一個空操作。通常你應(yīng)該在這里做一些恢復(fù)工作。
 
 
####################################################
## 4. Functions
## 4. 函數(shù)
####################################################
 
# Use def to create new functions
# 使用 def 來創(chuàng)建新函數(shù)
def add(x, y):
 print "x is %s and y is %s" % (x, y)
 # (譯注:意為“x 是 %s 而且 y 是 %s”。)
 return x + y # Return values with a return statement
     # 使用 return 語句來返回值
 
# Calling functions with parameters
# 調(diào)用函數(shù)并傳入?yún)?shù)
add(5, 6) #=> prints out "x is 5 and y is 6" and returns 11
   # (譯注:意為“x 是 5 而且 y 是 6”,并返回 11)
 
# Another way to call functions is with keyword arguments
# 調(diào)用函數(shù)的另一種方式是傳入關(guān)鍵字參數(shù)
add(y=6, x=5) # Keyword arguments can arrive in any order.
    # 關(guān)鍵字參數(shù)可以以任意順序傳入
 
# You can define functions that take a variable number of
# positional arguments
# 你可以定義一個函數(shù),并讓它接受可變數(shù)量的定位參數(shù)。
def varargs(*args):
 return args
 
varargs(1, 2, 3) #=> (1,2,3)
 
 
# You can define functions that take a variable number of
# keyword arguments, as well
# 你也可以定義一個函數(shù),并讓它接受可變數(shù)量的關(guān)鍵字參數(shù)。
def keyword_args(**kwargs):
 return kwargs
 
# Let's call it to see what happens
# 我們試著調(diào)用它,看看會發(fā)生什么:
keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
 
# You can do both at once, if you like
# 你還可以同時使用這兩類參數(shù),只要你愿意:
def all_the_args(*args, **kwargs):
 print args
 print kwargs
"""
all_the_args(1, 2, a=3, b=4) prints:
 (1, 2)
 {"a": 3, "b": 4}
"""
 
# When calling functions, you can do the opposite of varargs/kwargs!
# Use * to expand tuples and use ** to expand kwargs.
# 在調(diào)用函數(shù)時,定位參數(shù)和關(guān)鍵字參數(shù)還可以反過來用。
# 使用 * 來展開元組,使用 ** 來展開關(guān)鍵字參數(shù)。
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
     # 相當(dāng)于 all_the_args(1, 2, 3, 4)
all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
      # 相當(dāng)于 all_the_args(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
        # 相當(dāng)于 all_the_args(1, 2, 3, 4, a=3, b=4)
 
# Python has first class functions
# 函數(shù)在 Python 中是一等公民
def create_adder(x):
 def adder(y):
  return x + y
 return adder
 
add_10 = create_adder(10)
add_10(3) #=> 13
 
# There are also anonymous functions
# 還有匿名函數(shù)
(lambda x: x > 2)(3) #=> True
 
# There are built-in higher order functions
# 還有一些內(nèi)建的高階函數(shù)
map(add_10, [1,2,3]) #=> [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
 
# We can use list comprehensions for nice maps and filters
# 我們可以使用列表推導(dǎo)式來模擬 map 和 filter
[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
 
####################################################
## 5. Classes
## 5. 類
####################################################
 
# We subclass from object to get a class.
# 我們可以從對象中繼承,來得到一個類。
class Human(object):
 
 # A class attribute. It is shared by all instances of this class
 # 下面是一個類屬性。它將被這個類的所有實例共享。
 species = "H. sapiens"
 
 # Basic initializer
 # 基本的初始化函數(shù)(構(gòu)造函數(shù))
 def __init__(self, name):
  # Assign the argument to the instance's name attribute
  # 把參數(shù)賦值為實例的 name 屬性
  self.name = name
 
 # An instance method. All methods take self as the first argument
 # 下面是一個實例方法。所有方法都以 self 作為第一個參數(shù)。
 def say(self, msg):
  return "%s: %s" % (self.name, msg)
 
 # A class method is shared among all instances
 # They are called with the calling class as the first argument
 # 類方法會被所有實例共享。
 # 類方法在調(diào)用時,會將類本身作為第一個函數(shù)傳入。
 @classmethod
 def get_species(cls):
  return cls.species
 
 # A static method is called without a class or instance reference
 # 靜態(tài)方法在調(diào)用時,不會傳入類或?qū)嵗囊谩? @staticmethod
 def grunt():
  return "*grunt*"
 
 
# Instantiate a class
# 實例化一個類
i = Human(name="Ian")
print i.say("hi")  # prints out "Ian: hi"
      # 打印出 "Ian: hi"
 
j = Human("Joel")
print j.say("hello") # prints out "Joel: hello"
      # 打印出 "Joel: hello"
 
# Call our class method
# 調(diào)用我們的類方法
i.get_species() #=> "H. sapiens"
 
# Change the shared attribute
# 修改共享屬性
Human.species = "H. neanderthalensis"
i.get_species() #=> "H. neanderthalensis"
j.get_species() #=> "H. neanderthalensis"
 
# Call the static method
# 調(diào)用靜態(tài)方法
Human.grunt() #=> "*grunt*"
 
 
####################################################
## 6. Modules
## 6. 模塊
####################################################
 
# You can import modules
# 你可以導(dǎo)入模塊
import math
print math.sqrt(16) #=> 4
 
# You can get specific functions from a module
# 也可以從一個模塊中獲取指定的函數(shù)
from math import ceil, floor
print ceil(3.7) #=> 4.0
print floor(3.7) #=> 3.0
 
# You can import all functions from a module.
# Warning: this is not recommended
# 你可以從一個模塊中導(dǎo)入所有函數(shù)
# 警告:不建議使用這種方式
from math import *
 
# You can shorten module names
# 你可以縮短模塊的名稱
import math as m
math.sqrt(16) == m.sqrt(16) #=> True
 
# Python modules are just ordinary python files. You
# can write your own, and import them. The name of the 
# module is the same as the name of the file.
# Python 模塊就是普通的 Python 文件。
# 你可以編寫你自己的模塊,然后導(dǎo)入它們。
# 模塊的名稱與文件名相同。
 
# You can find out which functions and attributes
# defines a module.
# 你可以查出一個模塊里有哪些函數(shù)和屬性
import math
dir(math)

以上是“python語言基礎(chǔ)知識有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

當(dāng)前名稱:python語言基礎(chǔ)知識有哪些-創(chuàng)新互聯(lián)
URL分享:http://muchs.cn/article28/coejjp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、標(biāo)簽優(yōu)化、網(wǎng)頁設(shè)計公司、軟件開發(fā)微信公眾號、建站公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司