【Python】Python3基本語法-寫給Java程序員

推薦《Python編程:從入門到實踐》,很適合Python3入門,但是介紹的不深也不全。對於有經驗的程序員一天就可看完,瞭解下基本語法即可。本文就是我看完對Python的語法的基本總結(只記錄了Python的特殊之處),便於以後翻閱。

說下我看完本書對 Python3 語言的感覺:兩個字:方便,三個字:真方便。

首先,語法結構簡潔。

沒有語句結尾的分號,沒有包裹代碼塊的花括號,連註釋都是一個字符 #,而不是兩個斜線。

作爲腳本語言,無需聲明變量的類型,無需擔心String和StringBuffer的效率問題,只管給變量起名然後賦值就行了。

其次,語法特性豐富。

取字符串最後一個字符:

Python3是

 str[-1]

Java是

str.charAt(str.length() - 1)

去掉最後一個字符:

Python3是

str[:-1]

Java是

str.substring(0, str.length() -1)

看到這,我還能說什麼呢。很明顯,Java語法設計還停留在 C/C++ 的時代,而 Python 語法設計之初就考慮到很多便利性。

Python在大數據、在人工智能熱潮中流行是有原因的。我相信這是未來的語言趨勢。

人生苦短,我用Python

看來大佬們說的沒錯,所以我也來了。

 

 

================================================
==             Python3語法簡單說明
==                           ——針對Java程序員
==        摘自《Python編程:從入門到實踐》
================================================

--------------------------------------------------
----  基本語法
--------------------------------------------------

myVar = 1        #變量聲明無需類型
                 #語句不需要分號 ;結束

# 字符串拼接換行需要縮進
print("AAA and " +
    "BBB" +
    "CCC")

# if-else語句
if ( name =="Tom" ):
    print("Yes")
elif ():
    print()
else:
    print()

# 函數
def myFunction():
    """顯示簡單的問候語"""
    print("Hello!")

myFunction()


----------------------------------------
----  主要結構
----------------------------------------

---------列表 list-----------

myList[0]
myList[-2]     # 倒數第二個元素
list.append()
list.insert(0,newval)

list.pop()
list.remove(val)
del list[3]

min(list),max(list), sum(list)

#生成列表[1,4,9,16....]
squares = [values**2 for values in range(1,11)]

#列表解析
range(1,3)     # 左閉右開 1,2
numList[0:3]   # 0,1,2 不返回numList[3]
list[:4] , list[2:]

#列表複製
newList = origalList[:]

#判斷列表是否爲空
if myList:
    xxxx
#檢查是否在列表中
'apple' in friut
'desk' not in friut

#for 循環是一種遍歷列表的有效方式,但在for 循環中不應修改列表,否則將導致Python難以跟蹤其中的元素。
#應使用 while循環修改列表元素。


---------- 元組---------------

#元組 Tuple,不可改變的列表,圓括號
myTuple = (200,50)
print myTuple[0]    # 輸出200

#元組變列表
list(myTuple)

--------字典,鍵值對---------

dic = {'color' : 'green', 'num' : 5}
print( dic['color'] )

#添加鍵值對
#鍵必須不可變,可以用數字,字符串或元組充當,但不能用列表
dic['newKey'] = 'newValue'

#添加或更新鍵值對
dic1 = {'color' : 'red', 'num':5}
dic2 = {'length' : '3'}
dic1.update(dic2)
#dic1就變成{'color' : 'red', 'num':5, 'length' : '3'}
#如果是重複鍵值,則是覆蓋更新


#刪除鍵值對
del dic['color']
dic.pop('color')

#多行鍵值對
mutiline = {
    'first' : 'Tom',
    'sec' : 'Jay',
}
#可預留最後一個逗號,方便下次增加元素

#遍歷
for k,v in myDic:
    print()
for k in myDic.keys():
    print()
for v in myDic.values():
    print()
if 'AAA' not in myDic.keys():
    print()
#排序遍歷
for name in sorted(myDic.keys()):
    print()
#不重複輸出值
for myVal in set(myDic.values()):
    print(myVal)


---------循環-----------

#循環for語句後需加 冒號 :
for v in range(1,11):

#判斷
#if語句後面需要加 冒號:
if (yourname == "Tom"):
    xxx
else:
    yyy

if () :
    xxx
elif ():
    yyy
else:
    zzz

---- while ----
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)


------------函數------------------

def describe_pet(pet_name, animal_type='dog'):
    print(animal_type)
    #return animal_type
describe_pet()

# 排版,可在函數定義中輸入左括號後按回車鍵,
# 並在下一行按兩次Tab鍵,從而將形參列表和只縮進一層的函數體區分開來。
def function_name(
        parameter_0, parameter_1, parameter_2,
        parameter_3, parameter_4, parameter_5):
    function body...

# 關鍵字實參
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')

# 函數參數傳入 列表副本,防止列表被修改
function_name(list_name[:])

# 不固定參數,將實參封裝爲元組
def make_pizza(*toppings):
"""打印顧客點的所有配料"""
    print(toppings)
    make_pizza('pepperoni')
    make_pizza('mushrooms', 'green peppers', 'extra cheese')

# 使用任意數量的關鍵字實參
def build_profile(first, last, **user_info):
"""創建一個字典,其中包含我們知道的有關用戶的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
    profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein',
                                   location='princeton',
                                   field='physics')
print(user_profile)

-----------模塊----------------

import myPyFile
myPyFile.myFun()

from myPyFile import myFun1, myFun2
myFun1()
myFun2()

from myPyFile import myFun1 as func
func()

import myPyFile as p
p.myFun()


=============類==============


-----------------【類結構】----------------------
class Dog():
    """這是是文件描述"""

    def __init__(self, name, age):
        """初始化屬性name和age"""
        self.name = name
        self.age = age
    
     def sit(self):
        """模擬蹲下"""
        print(self.name.title() + " is now sitting.")
----------------------------------------------------
    #類的首字母大寫,駝峯命名法
    #方法 __init__() 爲必須且首個參數必須爲 self
    #使用 self. 來引用 實例屬性
    

--------------------【繼承】----------------------
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init()__(make, model, year)
        self.newAttr = 0
    
    def myNewFun():
        print("New Fun.")
----------------------------------------------------
    #重名函數會覆蓋父類的函數

from car import Car
from car import Car, ElectricCar
import Car
    #先導入標準庫,再換行導入自己編寫的模塊


-----------文件-------------

# 輸出文件內容
with open('filepath\my.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())

# 關鍵字with 在不再需要訪問文件後將其關閉。
# 在這個程序中,注意到我們調用了open() ,但沒有調用close() ;
# 你也可以調用open() 和close() 來打開和關閉文件,但
# 這樣做時,如果程序存在bug,導致close() 語句未執行,文件將不會關閉。
# 這看似微不足道,但未妥善地關閉文件可能會導致數據丟失或受損。如果在程序中過早地調
# 用close() ,你會發現需要使用文件時它已關閉 (無法訪問),這會導致更多的錯誤。
# 並非在任何情況下都能輕鬆確定關閉文件的恰當時機,但通過使用前面所示的結構,可
# 讓Python去確定:你只管打開文件,並在需要時使用它,Python自會在合適的時候自動將其關閉。

# 因爲read() 到達文件末尾時返回一個空字符串,而將這個空字符串顯示出來時就是一個空行。
# 需要使用 rstrip() 刪除多餘空行

# 逐行讀取
with open('filepath\my.txt') as file_object:
    for line in file_object:
    print(line.rstrip())

# 因爲在這個文件中,每行的末尾都有一個看不見的換行符,而print 語句也會加上一個換行符,
# 因此每行末尾都有兩個換行符:一個來自文件,另一個來自print 語句。
# 要消除這些多餘的空白行,可在print 語句中使用rstrip() 

# 文件複製到列表中
filename = 'pi_digits.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())


-----------讀取多個文件----------

filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)

----------寫文件----------

# 需要手動添加換行符
filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")


----------異常---------------

try:
    answer = int(first_number) / int(second_number)
    print(  )
except ZeroDivisionError:
    print("Error: divide by zero!")
else:
    print( answer )


----------存儲數據-----------
#將數據保存爲json文件存儲到硬盤
#讀取硬盤上的json文件的內容

import json
numbers = [2,3,5,7]

filename = 'numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)
-----
import json
filename = 'numbers.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)
    print(numbers)


----------------------------------------
----  代碼案例
----------------------------------------
# 轉移列表元素到新列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print("Verifying user: " + current_user.title())
    confirmed_users.append(current_user)

# 刪除列表中指定元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

# Python將非空字符串解讀爲True
def get_formatted_name(first_name, last_name, middle_name=''):
    """返回整潔的姓名"""
    if middle_name:
         full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = first_name + ' ' + last_name
    return full_name.title()
    musician = get_formatted_name('jimi', 'hendrix')
    print(musician)
    musician = get_formatted_name('john', 'hooker', 'lee')
    print(musician)

# 不固定參數,將實參封裝爲元組
def make_pizza(*toppings):
"""打印顧客點的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

是不是很簡單,Python的語法對於Java程序員來說真的是簡單。但是如果動手寫個小工具,就還要需要了解Python的各種庫了。Python很方便的在安裝時打包了很多有用的庫。剩下的可以自己主動去了解下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章