python3筆記html
源於:https://www.runoob.com/python3/python3-tutorial.htmlpython
Python 是一個高層次的結合瞭解釋性、編譯性、互動性和麪向對象的腳本語言。express
基礎語法centos
編碼app
默認狀況下 ,python3源碼文件以UTF-8編碼,全部字符串都是unicode字符串。固然能夠另外指定不一樣的編碼:dom
# -*- coding: cp-1252 -*-
上述定義容許在源文件中使用 Windows-1252 字符集中的字符編碼,對應適合語言爲保加利亞語、白羅斯語、馬其頓語、俄語、塞爾維亞語。async
標識符函數
在python3中,能夠用中文做爲變量名,非ASCII標識符也是容許的了。ui
python保留字this
>>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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/python #第一個註釋 print ("hello,world!") #第二個註釋
執行上述代碼,輸出結果爲
hello,world!
多行註釋能夠用多個#號,還有'''和"""
#!/usr/bin/python #第一個註釋 #第二個註釋 ''' 第三個註釋 第四個註釋 ''' """ 第五個註釋 第六個註釋 """ print ("hello,world!")
行與縮進
python最具特點的就是使用縮進來表示代碼塊,不須要使用大括號{}。
縮進的空格數是可變的,可是同一個代碼塊的語句必須包含相同的縮進空格數。實例以下:
if Ture: print ("Ture") else: print ("False")
多行語句
python一般是一行寫完一條語句,但若是語句很長,咱們可使用反斜槓(\)來實現多行語句,例如:
total = item_one + \ item_two + \ item_three
在[]、{}、或()中的多行語句,不須要使用反斜槓(\),例如:
total = ['item_one', 'item_two', 'item_four','item_five']
數字(number)類型
python中數字有四種類型:整數、布爾型、浮點數和複數。
字符串
#!/usr/bin/python str='hello, world!' print(str) #輸出字符 print(str[0:-1]) #輸出第一個到倒數第二個的全部字符 print(str[0]) #輸出字符串的第一個字符 print(str[3:7]) #輸出從第四個到第八個的字符 print(str[3:]) #輸出從第三個開始後的全部字符 print(str * 2) #輸出字符串兩次 print(str + '你好') #鏈接字符串 print('-------------------') print('hello,\nworld!') #使用反斜槓(\)+n轉義特殊字符 print(r'hello,\nworld!') #在字符串前面添加一個 r,表示原始字符串,不會發生轉義
這裏的 r 指 raw,即 raw string。
輸出結果爲:
hello, world! hello, world h lo, lo, world! hello, world!hello, world! hello, world!你好 ------------------- hello, world! hello,\nworld!
空行
函數之間或類的方法之間用空行分隔,表示一段新的代碼的開始。類和函數入口之間也用一行空行分隔,以突出函數入口的開始。
空行與代碼縮進不一樣,空行並非python語法的一部分。書寫時不插入空行,python解釋器運行也不會出錯。可是空行的做用在於分隔兩段不一樣功能或含義的代碼,便於往後代碼維護或重構。
記住:空行也是程序代碼的一部分。
等待用戶輸入
執行下面的程序在按回車鍵後就會等待用戶輸入:
>>> input("\n\n按下 enter 鍵後退出。") 按下 enter 鍵後退出。dfadsfasdfasdfasdfafsdasdfasdfasdfasdfasdfasdfasdf 'dfadsfasdfasdfasdfafsdasdfasdfasdfasdfasdfasdfasdf' >>>
以上代碼中,"\n\n"在結果輸出前會輸出兩個新的空行。一旦用戶按下enter鍵時,程序將退出。
同一行顯示多條語句
python能夠在同一行中使用多條語句,語句之間使用分號(;)分割,如下是一個簡單的實例:
#!/usr/bin/python import sys; x = 'test'; sys.stdout.write(x + '\n')
使用腳本執行上述代碼,輸出結果爲:
test
使用交互式命令行執行,輸出結果爲:
>>> import sys; x = 'test'; sys.stdout.write(x + '\n') test 5 >>>
此處5表示字符數。
多個語句構成代碼組
縮進相同的一組語句構成一個代碼塊,咱們稱之爲代碼組。
像if、while、def和class這樣的複合語句,首行以關鍵字開始,以冒號(:)結束,該行以後的一行或多行代碼構成代碼組。
咱們將首行及後面的代碼組稱爲一個字句(clause)。
以下實例:
if expression : suite elif expression : suite else : suite
print輸出
print默認輸出是換行的,若是要實現不換行須要在變量末尾加上end=""
#!/usr/bin/python x="a" y="b" #換行輸出 print(x) print(y) print(--------------------------) #不換行輸出 print( x, end=" " ) print( y, end="" ) print()
執行結果爲
a b -------------------------- a b
import與from...import
在python中import或者from...import來導入相應的模塊
將整個模塊(somemodule)導入,格式爲:import somemodule
從某個模塊中導入某個函數,格式爲:from somemodule import somefunction
從某個模塊中導入多個函數,格式爲:from somemodule importy firstfunc, secondfunc, thirdfunc
將某個模塊中的所有函數導入,格式爲:from somemodule import *
#!/usr/bin/python import sys print('================python import mode==============') print ('命令行參數爲:') for i in sys.argv: print (i) print ('\n python 路徑爲', sys.path) from sys import argv,path #導入特定的成員 print('================python import mode==============') print('path:',path) #由於已經導入path成員,因此此處引用時不須要加sys.path
執行結果
================python import mode============== 命令行參數爲: test3.py python 路徑爲 ['/root/python', '/usr/local/python3/lib/python37.zip', '/usr/local/python3/lib/python3.7', '/usr/local/python3/lib/python3.7/lib-dynload', '/usr/local/python3/lib/python3.7/site-packages'] ================python import mode============== path: ['/root/python', '/usr/local/python3/lib/python37.zip', '/usr/local/python3/lib/python3.7', '/usr/local/python3/lib/python3.7/lib-dynload', '/usr/local/python3/lib/python3.7/site-packages']
命令行參數
不少程序能夠執行一些操做來查看一些基本信息,Python可使用-h參數查看各參數幫助信息:
[root@centos6 python]# python -h usage: python [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 .pyc 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) -i : inspect interactively after running script; forces a prompt even if stdin does not appear to be a terminal; also PYTHONINSPECT=x -I : isolate Python from the user's environment (implies -E and -s) -m mod : run library module as a script (terminates option list) -O : remove assert and __debug__-dependent statements; add .opt-1 before .pyc extension; also PYTHONOPTIMIZE=x -OO : do -O changes and also discard docstrings; add .opt-2 before .pyc extension -q : don't print version and copyright messages on interactive startup -s : don't add user site directory to sys.path; also PYTHONNOUSERSITE -S : don't imply 'import site' on initialization -u : force the stdout and stderr streams to be unbuffered; this option has no effect on stdin; also PYTHONUNBUFFERED=x -v : verbose (trace import statements); also PYTHONVERBOSE=x can be supplied multiple times to increase verbosity -V : print the Python version number and exit (also --version) when given twice, print more information about the build -W arg : warning control; arg is action:message:category:module:lineno also PYTHONWARNINGS=arg -x : skip first line of source, allowing use of non-Unix forms of #!cmd -X opt : set implementation-specific option --check-hash-based-pycs always|default|never: control how Python invalidates hash-based .pyc files file : program read from script file - : program read from stdin (default; interactive mode if a tty) arg ...: arguments passed to program in sys.argv[1:] Other environment variables: PYTHONSTARTUP: file executed on interactive startup (no default) PYTHONPATH : ':'-separated list of directories prefixed to the default module search path. The result is sys.path. PYTHONHOME : alternate <prefix> directory (or <prefix>:<exec_prefix>). The default module search path uses <prefix>/lib/pythonX.X. PYTHONCASEOK : ignore case in 'import' statements (Windows). PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr. PYTHONFAULTHANDLER: dump the Python traceback on fatal errors. PYTHONHASHSEED: if this variable is set to 'random', a random value is used to seed the hashes of str, bytes and datetime objects. It can also be set to an integer in the range [0,4294967295] to get hash values with a predictable seed. PYTHONMALLOC: set the Python memory allocators and/or install debug hooks on Python memory allocators. Use PYTHONMALLOC=debug to install debug hooks. PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of locale coercion and locale compatibility warnings on stderr. PYTHONDEVMODE: enable the development mode. [root@centos6 python]#