2、运行.py文件、字符串、保留字符、行和缩进、多行语句、引号、注释、等待用户输入、同一行显示多条语句、命令行参数
2Python基礎(chǔ)語(yǔ)法
2.1運(yùn)行.py文件
運(yùn)行方式類(lèi)似:
$ python test.py2.2Python標(biāo)識(shí)符
在Python里,標(biāo)識(shí)符由字母、數(shù)字、下劃線(xiàn)組成。 在Python中,所有標(biāo)識(shí)符可以包括英文、數(shù)字以及下劃線(xiàn)(_),但并不能以數(shù)字開(kāi)頭。
Python中的標(biāo)識(shí)符是區(qū)分大小寫(xiě)的。
- 以下劃線(xiàn)開(kāi)頭的標(biāo)識(shí)符是有特殊意義的。以單下劃線(xiàn)開(kāi)頭 _foo 的代表不能直接訪(fǎng)問(wèn)的類(lèi)屬性,需通過(guò)類(lèi)提供的接口進(jìn)行訪(fǎng)問(wèn),不能用 from xxx import * 而導(dǎo)入。
- 以雙下劃線(xiàn)開(kāi)頭的__foo代表類(lèi)的私有成員,以雙下劃線(xiàn)開(kāi)頭和結(jié)尾的__foo__代表Python里特殊方法專(zhuān)用的標(biāo)識(shí),如__init__()代表類(lèi)的構(gòu)造函數(shù)。
- Python 可以同一行顯示多條語(yǔ)句,方法是用分號(hào) ; 分開(kāi)
2.3Python保留字符
下面的列表現(xiàn)實(shí)和了在Python的保留字。這些保留字不能用作常數(shù)或變數(shù),或任何其它標(biāo)識(shí)符名稱(chēng)。
and exec not assert finally or break for pass class from print continue global raise def if return del import try elif in while else is with except lambda yield2.4行和縮進(jìn)
學(xué)習(xí)Python與其他語(yǔ)法最大的區(qū)別就是,Python的代碼不使用大括號(hào){}來(lái)控制類(lèi),函數(shù)以及其他邏輯判斷。Python最具特色的就是用縮進(jìn)來(lái)寫(xiě)模塊。
縮進(jìn)的空白數(shù)量是可變的,但是所有代碼塊語(yǔ)句必須包含相同的縮進(jìn)空白數(shù)量,這個(gè)必須嚴(yán)格執(zhí)行。
以下實(shí)例縮進(jìn)為四個(gè)空格:
# -*- coding: UTF-8 -*-if True:print("Answer")print("True") else:print("Answer")#沒(méi)有嚴(yán)格縮進(jìn),在執(zhí)行時(shí)會(huì)報(bào)錯(cuò)(下面的代碼有嚴(yán)格縮進(jìn),所以不會(huì)報(bào)錯(cuò))print("False")運(yùn)行結(jié)果:
D:\installed\Anaconda3\python.exe E:/workspace/python/python/01_Python中文編碼/02_行和縮進(jìn).py Answer True以下代碼將會(huì)執(zhí)行錯(cuò)誤:
# -*- coding: UTF-8 -*-if True:print("Answer")print("True") else:print("Answer")#沒(méi)有嚴(yán)格縮進(jìn),在執(zhí)行時(shí)會(huì)報(bào)錯(cuò)print("False")執(zhí)行結(jié)果:
D:\installed\Anaconda3\python.exe E:/workspace/python/python/01_Python中文編碼/02_行和縮進(jìn).pyFile "E:/workspace/python/python/01_Python中文編碼/02_行和縮進(jìn).py", line 9print("False")^ IndentationError: unindent does not match any outer indentation levelIndentationError: unindent does not match any outer indentation level錯(cuò)誤表明,你使用的縮進(jìn)方式不一致,有的是tab鍵縮進(jìn),有的是空格縮進(jìn),改為一致即可。
如果是 IndentationError: unexpected indent 錯(cuò)誤, 則 python 編譯器是在告訴你"Hi,老兄,你的文件里格式不對(duì)了,可能是tab和空格沒(méi)對(duì)齊的問(wèn)題",所有 python 對(duì)格式要求非常嚴(yán)格。
因此,在 Python 的代碼塊中必須使用相同數(shù)目的行首縮進(jìn)空格數(shù)。
建議你在每個(gè)縮進(jìn)層次使用 單個(gè)制表符 或 兩個(gè)空格 或 四個(gè)空格 , 切記不能混用
2.5多行語(yǔ)句
Python語(yǔ)句中一般以新行作為語(yǔ)句的結(jié)束符。
但是我們可以使用斜杠(\)將一行的語(yǔ)句分為多行顯示,如下所示:
語(yǔ)句中包含[],{}或()括號(hào)就不需要使用多行連接符。如下實(shí)例:
days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday']2.6Python引號(hào)
Python可以使用引號(hào)(‘)、雙引號(hào)(‘’’或”””)來(lái)表示字符串,引號(hào)的開(kāi)始與結(jié)束必須得相同類(lèi)型的。
其中三引號(hào)可以由多行組成,編寫(xiě)多行文本的快捷語(yǔ)法,常用語(yǔ)文檔字符串,在文件的特定地點(diǎn),被當(dāng)做注釋。
# -*- coding: UTF-8 -*-""" 下面是三種引號(hào)的寫(xiě)法 """ word = 'word' sentence = "設(shè)置一個(gè)句子" paragraph = """這是一個(gè)段落。 包含了多個(gè)語(yǔ)句 """print("word = ",word) print("sentence = " + sentence) print("paragraph = "+paragraph)運(yùn)行結(jié)果:
D:\installed\Anaconda3\python.exe E:/workspace/python/python/01_Python中文編碼/03_python引號(hào).py word = word sentence = 設(shè)置一個(gè)句子 paragraph = 這是一個(gè)段落。 包含了多個(gè)語(yǔ)句Process finished with exit code 02.7Python注釋
Python中單行注釋采用#開(kāi)頭。
# -*- coding: UTF-8 -*-#第一個(gè)注釋 print("Hello,Python") #第二個(gè)注釋python 中多行注釋使用三個(gè)單引號(hào)(’’’)或三個(gè)雙引號(hào)(""")。
實(shí)例:
# -*- coding: UTF-8 -*-''' 這是多行注釋,使用單引號(hào)。 這是多行注釋,使用單引號(hào)。 這是多行注釋,使用單引號(hào)。 '''""" 這是多行注釋,使用雙引號(hào)。 這是多行注釋,使用雙引號(hào)。 這是多行注釋,使用雙引號(hào)。 """2.8等待用戶(hù)輸入
下面的程序執(zhí)行后就會(huì)等待用戶(hù)輸入,按回車(chē)鍵后就會(huì)退出:
# -*- coding: UTF-8 -*-input("按下enter鍵退出,其他任意鍵顯示...\n")運(yùn)行結(jié)果:
D:\installed\Anaconda3\python.exe E:/workspace/python/python/Python/06_等待用戶(hù)輸入.py 按下enter鍵退出,其他任意鍵顯示...Process finished with exit code 0以上代碼中,\n實(shí)現(xiàn)換行。一旦用戶(hù)按下enter(回車(chē))鍵退出,其它鍵顯示。
2.9同一行顯示多條語(yǔ)句
# -*- coding: UTF-8 -*-import sys; x = 'runoob'; sys.stdout.write(x + '\n')輸出結(jié)果:
D:\installed\Anaconda3\python.exe E:/workspace/python/python/Python/07_同一行顯示多條語(yǔ)句.py runoobProcess finished with exit code 02.10多個(gè)語(yǔ)句構(gòu)成代碼組
縮進(jìn)相同的一組語(yǔ)句構(gòu)成一個(gè)代碼塊,我們稱(chēng)之代碼組。
像if、while、del和class這樣的符合語(yǔ)句,首航以關(guān)鍵字開(kāi)始,以冒號(hào)(:)結(jié)束,該行之后的一行或多行代碼構(gòu)成代碼組。
我們將首行及后面的代碼組稱(chēng)為一個(gè)子句(clause)。
如下實(shí)例:
if expression : suite elif expression : suite else : suite2.11命令行參數(shù)
很多程序可以執(zhí)行一些操作來(lái)查看一些基本信息,Python可以使用-h參數(shù)查看個(gè)參數(shù)幫助信息:
C:\Users\toto>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 evenif 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=xcan 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:linenoalso 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 thedefault module search path. The result is sys.path. PYTHONHOME : alternate <prefix> directory (or <prefix>;<exec_prefix>).The default module search path uses <prefix>\python{major}{minor}. 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 usedto seed the hashes of str and bytes objects. It can also be set to aninteger in the range [0,4294967295] to get hash values with apredictable seed. PYTHONMALLOC: set the Python memory allocators and/or install debug hookson Python memory allocators. Use PYTHONMALLOC=debug to install debughooks. PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the localecoercion behavior. Use PYTHONCOERCECLOCALE=warn to request display oflocale coercion and locale compatibility warnings on stderr. PYTHONBREAKPOINT: if this variable is set to 0, it disables the defaultdebugger. It can be set to the callable of your debugger of choice. PYTHONDEVMODE: enable the development mode. PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files.C:\Users\toto>總結(jié)
以上是生活随笔為你收集整理的2、运行.py文件、字符串、保留字符、行和缩进、多行语句、引号、注释、等待用户输入、同一行显示多条语句、命令行参数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 阿尔及利亚现在打仗吗?
- 下一篇: 狂斩三国3怎么才能无限造兵