Python基礎--Python3基礎文法

來源:互聯網
上載者:User

標籤:關鍵字   continue   except   import   keyword   

Python3 基礎文法

編碼

預設情況下,Python3源碼檔案以UTF-8編碼,所有字串都是Unicode字串。當然也可以為源碼檔案指定不同的編碼,例如:

# -*- coding: cp-1252 -*-


標識符

1.第一個字元必須是字母表中字母或底線;

2.標識符的其他的部分有字母、數字和底線組成;

3.標識符對大小寫敏感。

註:在Python3中,非ASCII標識符也是允許的。


Python保留字

保留字即關鍵字,我們不能把它們用作任何標識符名稱。Python的標準庫提供了一個keyword模組,可以輸出目前的版本的所有關鍵字:

>>> import keyword>>> keyword.kwlist[‘False‘, ‘None‘, ‘True‘, ‘and‘, ‘as‘, ‘assert‘, ‘break‘, ‘class‘, ‘continue‘, ‘def‘, ‘del‘, ‘elif‘, ‘else‘, ‘except‘, ‘finally‘, ‘for‘, ‘from‘, ‘global‘, ‘if‘, ‘import‘, ‘in‘, ‘is‘, ‘lambda‘, ‘nonlocal‘, ‘not‘, ‘or‘, ‘pass‘, ‘raise‘,  ‘return‘, ‘try‘, ‘while‘, ‘with‘, ‘yield‘]


注釋

Python中單行注釋以#開頭,舉例如下:

#!/usr/bin/python3#第一個注釋print ("Hello,Python!") #第二個注釋

執行以上代碼,輸出結果為:

Hello,Python!

多行注釋可以用多個#號:

#!/usr/bin/python3#第一個注釋#第二個注釋print ("Hello,Python!")

執行以上代碼,輸出結果為:

Hello,Python!


行與縮排

Python最具特色的就是使用縮排來表示代碼塊,不需要使用大括弧{}。

做進的空格數是可變的,但是同一個代碼塊的語句必須包含相同的縮排空格數。

例如:

if True:    print("True")else:    print("False")


以下代碼最後一行語句縮排數的空格數不一致,會導致運行錯誤:

if True:    print("Answer")    print("True")else:    print("Answer")  print("False")    #縮排不一致,會導致運行錯誤


以上程式由於縮排不一致,執行後會出現類似以下錯誤:

  File "C:/Users/wuli/PycharmProjects/test.py", line 10    print("False")    #縮排不一致,會導致運行錯誤                                    ^IndentationError: unindent does not match any outer indentation level


多行語句

Python通常是一行寫完一條語句,但如果語句很長,我們可以使用反斜線(\)來實現多行語句,例如:

total = ‘item_one +         item_two +         item_three‘


在[],{},或()中的多行語句,不需要使用反斜線(\),例如:

total = [‘item_one‘,‘item_two‘,‘item_three‘, ‘item_four‘,‘item_five‘]


資料類型

Python中數有四種類型:整數、長整數、浮點數和複數。

1.整數,例如1

2.長整數,比較大的整數

3.浮點數,例如1.23、3E-2

4.複數,例如1+2j、1.1+2.2j 


字串

1.Python中單引號和雙引號使用完全相同;

2.使用三引號(‘‘‘或""")可以指定一個多行字串;

3.轉義符‘\‘

4.自然字串,通過在字串前加r或R。例如:r"this is a line with \n"則\n會顯示,並不是換行;

5.python允許處理Unicode字串,加首碼u或U,例如:u"this is an unicode string"

6.字串是不可變的。

7.按字面 意義級聯字串,例如:"this" "is" "string"會被自動轉換為this is string

word = ‘字串‘

sentence = "這是一個句子"

paragraph = """這是一個段落,

可以有多行組成"""


空行

函數之間或類的方法之間用空行分隔,表示一段新的代碼的開始。類和函數入口之間也用一行空行分隔,以突出函數入口的開始。

空行與代碼縮排不同,空行並不是Python文法的一部分。書寫時不插入空行,Python解譯器運行也不會出錯。但是空行的作用在於分隔兩段不同功能或含義的代碼,便於日後代碼維護或重構。

謹記:空行也是程式碼的一部分。


等待使用者輸入

執行下面的程式在按斷行符號鍵後就會等待使用者輸入:

#!/usr/bin/python3input("\n\n按下enter鍵後退出。")


以上代碼中,"\n\n"在結果輸出前會輸出兩個新的空行。一旦使用者按下鍵時,程式將退出。


同一行顯示多條語句

Python可以在同一行中使用多條語句,語句之間使用分號(;)分割,案例如下:

#!/usr/bin/python3import sys; x = ‘python‘;sys.stdout.write(x + ‘\n‘)


執行以上代碼,結果輸出為:

python


多個語句構成程式碼群組

縮排相同的一組語句構成一個代碼塊,我們稱之程式碼群組。

像if、while、def和class這樣的複合陳述式,首行以關鍵字開始,以冒號(:)結束,該行之後的一行或多行代碼構成程式碼群組。

我們將首行及後面的程式碼群組稱為一個子句(clause)。

例如:

if expression:    suiteelif expression:    suiteelse:    suite


print輸出

print預設輸出是換行的,如果要實現不換行需要在變數末尾加上end="":

x = ‘a‘y = ‘b‘#換行輸出print(x)print(y)print(‘------‘)#不換行輸出print(x,end=" ")print(y,end=" ")print()


以上執行結果為:

ab------a b


import與from...import

在Python用import或者form...import來匯入相應的模組。

將整個模組(somemodule)匯入,格式為:import somemodule

從某個模組中匯入某個函數,格式為:from somemodule import somefunction

從某個模組中匯入多個函數,格式為:from somemodule import firstfunc,secondfunc,thirdfunc

將某個模組中的全部函數匯入,格式為:from somemodule import *


匯入sys模組

import sysprint(‘================Python import mode==========================‘);print (‘命令列參數為:‘)for i in sys.argv:    print (i)print (‘\n python 路徑為‘,sys.path)


輸出為:

================Python import mode==========================命令列參數為:C:/Users/wuli/PycharmProjects/Project20170523-python3/Day1/test1.py python 路徑為 [‘C:\\Users\\wuli\\PycharmProjects\\Project20170523-python3\\Day1‘,  ‘C:\\Users\\wuli\\PycharmProjects\\Project20170523-python3‘,  ‘C:\\Users\\wuli\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip‘,  ‘C:\\Users\\wuli\\AppData\\Local\\Programs\\Python\\Python36\\DLLs‘,  ‘C:\\Users\\wuli\\AppData\\Local\\Programs\\Python\\Python36\\lib‘,  ‘C:\\Users\\wuli\\AppData\\Local\\Programs\\Python\\Python36‘,  ‘C:\\Users\\wuli\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages‘]


 

匯入sys模組的argv,path成員

from sys import argv,path  #  匯入特定的成員 print(‘================python from import===================================‘)print(‘path:‘,path) # 因為已經匯入path成員,所以此處引用時不需要加sys.path


輸出為:

================python from import===================================path: [‘C:\\Users\\wuli\\PycharmProjects\\Project20170523-python3\\Day1‘, ‘C:\\Users\\wuli\\PycharmProjects\\Project20170523-python3‘, ‘C:\\Users\\wuli\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip‘, ‘C:\\Users\\wuli\\AppData\\Local\\Programs\\Python\\Python36\\DLLs‘, ‘C:\\Users\\wuli\\AppData\\Local\\Programs\\Python\\Python36\\lib‘, ‘C:\\Users\\wuli\\AppData\\Local\\Programs\\Python\\Python36‘, ‘C:\\Users\\wuli\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages‘]



命令列參數

很多程式可以執行一些操作來查看一些基本資料,Python可以使用-h參數查看各參數協助資訊:

C:\Users\wuli>python3 -husage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...Options and arguments (and corresponding environment variables):-b     : issue warnings about str(bytes_instance), str(bytearray_instance)         and comparing bytes/bytearray with str. (-bb: issue errors)-B     : don‘t write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x-c cmd : program passed in as string (terminates option list)-d     : debug output from parser; also PYTHONDEBUG=x-E     : ignore PYTHON* environment variables (such as PYTHONPATH)-h     : print this help message and exit (also --help)[etc.]


注意事項:

1. 在Windows下可以不寫第一行注釋:

#!/usr/bin/python3

第一行注釋標的是指向 python 的路徑,告訴作業系統執行這個指令碼的時候,調用 /usr/bin 下的 python 解譯器。

此外還有以下形式(推薦寫法):

#!/usr/bin/env python3

這種用法先在 env(環境變數)設定裡尋找 python 的安裝路徑,再調用對應路徑下的解譯器程式完成操作。


2. 關於注釋,也可以使用‘‘‘ ‘‘‘的格式在三引號之間書寫較長的注釋;

‘‘‘ ‘‘‘還可以用於在函數的首部對函數進行一個說明:

def example(anything):    ‘‘‘形參為任意類型的對象,       這個樣本函數會將其原樣返回。    ‘‘‘    return anything


3. help()函數

調用python的help()函數可以列印輸出一個函數的文檔字串:

# 如下執行個體,查看 max 內建函數的參數列表和規範的文檔

>>> help(max)Help on built-in function max in module builtins:max(...)    max(iterable, *[, default=obj, key=func]) -> value    max(arg1, arg2, *args, *[, key=func]) -> value    With a single iterable argument, return its biggest item. The    default keyword-only argument specifies an object to return if    the provided iterable is empty.    With two or more arguments, return the largest argument.


按下:q兩個按鍵即退出說明文檔(linux當中退出方式)

如果僅僅想得到文檔字串:

>>> print(max.__doc__) #注意,doc的前後分別是兩個底線max(iterable, *[, default=obj, key=func]) -> valuemax(arg1, arg2, *args, *[, key=func]) -> valueWith a single iterable argument, return its biggest item. Thedefault keyword-only argument specifies an object to return ifthe provided iterable is empty.With two or more arguments, return the largest argument.


本文出自 “wuli_blog” 部落格,請務必保留此出處http://wuli03960405.blog.51cto.com/1470785/1930651

Python基礎--Python3基礎文法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.