2、运行.py文件、字符串、保留字符、行和缩进、多行语句、引号、注释、等待用户输入、同一行显示多条语句、命令行参数
2Python基礎語法
2.1運行.py文件
運行方式類似:
$ python test.py2.2Python標識符
在Python里,標識符由字母、數字、下劃線組成。 在Python中,所有標識符可以包括英文、數字以及下劃線(_),但并不能以數字開頭。
Python中的標識符是區分大小寫的。
- 以下劃線開頭的標識符是有特殊意義的。以單下劃線開頭 _foo 的代表不能直接訪問的類屬性,需通過類提供的接口進行訪問,不能用 from xxx import * 而導入。
- 以雙下劃線開頭的__foo代表類的私有成員,以雙下劃線開頭和結尾的__foo__代表Python里特殊方法專用的標識,如__init__()代表類的構造函數。
- Python 可以同一行顯示多條語句,方法是用分號 ; 分開
2.3Python保留字符
下面的列表現實和了在Python的保留字。這些保留字不能用作常數或變數,或任何其它標識符名稱。
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行和縮進
學習Python與其他語法最大的區別就是,Python的代碼不使用大括號{}來控制類,函數以及其他邏輯判斷。Python最具特色的就是用縮進來寫模塊。
縮進的空白數量是可變的,但是所有代碼塊語句必須包含相同的縮進空白數量,這個必須嚴格執行。
以下實例縮進為四個空格:
# -*- coding: UTF-8 -*-if True:print("Answer")print("True") else:print("Answer")#沒有嚴格縮進,在執行時會報錯(下面的代碼有嚴格縮進,所以不會報錯)print("False")運行結果:
D:\installed\Anaconda3\python.exe E:/workspace/python/python/01_Python中文編碼/02_行和縮進.py Answer True以下代碼將會執行錯誤:
# -*- coding: UTF-8 -*-if True:print("Answer")print("True") else:print("Answer")#沒有嚴格縮進,在執行時會報錯print("False")執行結果:
D:\installed\Anaconda3\python.exe E:/workspace/python/python/01_Python中文編碼/02_行和縮進.pyFile "E:/workspace/python/python/01_Python中文編碼/02_行和縮進.py", line 9print("False")^ IndentationError: unindent does not match any outer indentation levelIndentationError: unindent does not match any outer indentation level錯誤表明,你使用的縮進方式不一致,有的是tab鍵縮進,有的是空格縮進,改為一致即可。
如果是 IndentationError: unexpected indent 錯誤, 則 python 編譯器是在告訴你"Hi,老兄,你的文件里格式不對了,可能是tab和空格沒對齊的問題",所有 python 對格式要求非常嚴格。
因此,在 Python 的代碼塊中必須使用相同數目的行首縮進空格數。
建議你在每個縮進層次使用 單個制表符 或 兩個空格 或 四個空格 , 切記不能混用
2.5多行語句
Python語句中一般以新行作為語句的結束符。
但是我們可以使用斜杠(\)將一行的語句分為多行顯示,如下所示:
語句中包含[],{}或()括號就不需要使用多行連接符。如下實例:
days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday']2.6Python引號
Python可以使用引號(‘)、雙引號(‘’’或”””)來表示字符串,引號的開始與結束必須得相同類型的。
其中三引號可以由多行組成,編寫多行文本的快捷語法,常用語文檔字符串,在文件的特定地點,被當做注釋。
# -*- coding: UTF-8 -*-""" 下面是三種引號的寫法 """ word = 'word' sentence = "設置一個句子" paragraph = """這是一個段落。 包含了多個語句 """print("word = ",word) print("sentence = " + sentence) print("paragraph = "+paragraph)運行結果:
D:\installed\Anaconda3\python.exe E:/workspace/python/python/01_Python中文編碼/03_python引號.py word = word sentence = 設置一個句子 paragraph = 這是一個段落。 包含了多個語句Process finished with exit code 02.7Python注釋
Python中單行注釋采用#開頭。
# -*- coding: UTF-8 -*-#第一個注釋 print("Hello,Python") #第二個注釋python 中多行注釋使用三個單引號(’’’)或三個雙引號(""")。
實例:
# -*- coding: UTF-8 -*-''' 這是多行注釋,使用單引號。 這是多行注釋,使用單引號。 這是多行注釋,使用單引號。 '''""" 這是多行注釋,使用雙引號。 這是多行注釋,使用雙引號。 這是多行注釋,使用雙引號。 """2.8等待用戶輸入
下面的程序執行后就會等待用戶輸入,按回車鍵后就會退出:
# -*- coding: UTF-8 -*-input("按下enter鍵退出,其他任意鍵顯示...\n")運行結果:
D:\installed\Anaconda3\python.exe E:/workspace/python/python/Python/06_等待用戶輸入.py 按下enter鍵退出,其他任意鍵顯示...Process finished with exit code 0以上代碼中,\n實現換行。一旦用戶按下enter(回車)鍵退出,其它鍵顯示。
2.9同一行顯示多條語句
# -*- coding: UTF-8 -*-import sys; x = 'runoob'; sys.stdout.write(x + '\n')輸出結果:
D:\installed\Anaconda3\python.exe E:/workspace/python/python/Python/07_同一行顯示多條語句.py runoobProcess finished with exit code 02.10多個語句構成代碼組
縮進相同的一組語句構成一個代碼塊,我們稱之代碼組。
像if、while、del和class這樣的符合語句,首航以關鍵字開始,以冒號(:)結束,該行之后的一行或多行代碼構成代碼組。
我們將首行及后面的代碼組稱為一個子句(clause)。
如下實例:
if expression : suite elif expression : suite else : suite2.11命令行參數
很多程序可以執行一些操作來查看一些基本信息,Python可以使用-h參數查看個參數幫助信息:
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>總結
以上是生活随笔為你收集整理的2、运行.py文件、字符串、保留字符、行和缩进、多行语句、引号、注释、等待用户输入、同一行显示多条语句、命令行参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阿尔及利亚现在打仗吗?
- 下一篇: 狂斩三国3怎么才能无限造兵