python基础语法
编码默认为utf-8,也可以指定编码:
# -*- coding: utf-8 -*-
标识符是用户编程时使用的名字,用于给变量、常量、函数、语句块等命名。在python中,标识符必须以字母或下划线开头,其他部分由字母、数字和下划线组成,对大小写敏感
保留字即关键字,我们不能把它们用作任何标识符名称。Python 的标准库提供了一个 keyword 模块,可以输出当前版本的所有关键字:
import keyword print(keyword.kwlist)
结果为:
['False', 'None', 'True', '__peg_parser__', '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']
单行注释:
# 大湘菜的注释
可以在空白行输入快捷键Ctrl+/来创建注释,如果在非空白行输入此快捷键会将此行代码变作注释,再次输入此快捷键又会将注释变作代码:
# print('大湘菜')
多行注释:
''' 大 湘 菜 '''
或:
""" 大 湘 菜 """
python最具特色的就是使用缩进来表示代码块:
if True: print ("大湘菜") else: print ("小湘菜")
如果缩进不一致,会报错:
IndentationError: expected an indented block
数字类型:
print(int(1.23)) # 整数 print(bool(1)) # 布尔值 print(float(1.23)) # 浮点数 print(complex(1)) # 复数
结果为:
1 True 1.23 (1+0j)
字符串
''和""完全相同:
print('微湘菜') print("小湘菜") print(''' 大 湘 菜 ''') print(""" 巨 湘 菜 """)
结果为:
微湘菜
小湘菜
大
湘
菜
巨
湘
菜
转义符为\,在字符串前面使用r可以让\不发生转义:
print('大\n湘\n菜') print(r'大\n湘\n菜')
结果为:
大
湘
菜
大\n湘\n菜
字符串相关的运算符:
print('小湘菜' + '大湘菜') print('大湘菜' * 2)
结果为:
小湘菜大湘菜
大湘菜大湘菜
字符串截取:
s = '小湘菜大湘菜' print(s[1:3:1]) # 变量[头下标:尾下标:步长] print(s[-1:-3:-1]) # 从右往左以-1开始
结果为:
湘菜
菜湘
字符串不可改变:
s = '大湘菜' s[0] = '小' print(s)
结果会报错:
TypeError: 'str' object does not support item assignment
让用户输入:
s = input('输入:')
s即为用户输入的字符串变量
代码组为缩进相同的一组语句构成的代码块
用print()方法输出,默认换行,如若要实现不换行:
print('小湘菜', end='') print('大湘菜', end='')
结果为:
小湘菜大湘菜
导入模块:
import os # 导入整个模块 from os import open # 导入某个函数 from os import open, close # 导入多个函数 from os import * # 导入所有函数
在命令行窗口输入:
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 : turn on parser debugging output (for experts only, only works on debug builds); 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. The following options are available: -X faulthandler: enable faulthandler -X oldparser: enable the traditional LL(1) parser; also PYTHONOLDPARSER -X showrefcount: output the total reference count and number of used memory blocks when the program finishes or after each statement in the interactive interpreter. This only works on debug builds -X tracemalloc: start tracing Python memory allocations using the tracemalloc module. By default, only the most recent frame is stored in a traceback of a trace. Use -X tracemalloc=NFRAME to start tracing with a traceback limit of NFRAME frames -X importtime: show how long each import takes. It shows module name, cumulative time (including nested imports) and self time (excluding nested imports). Note that its output may be broken in multi-threaded application. Typical usage is python3 -X importtime -c 'import asyncio' -X dev: enable CPython's "development mode", introducing additional runtime checks which are too expensive to be enabled by default. Effect of the developer mode: * Add default warning filter, as -W default * Install debug hooks on memory allocators: see the PyMem_SetupDebugHooks() C function * Enable the faulthandler module to dump the Python traceback on a crash * Enable asyncio debug mode * Set the dev_mode attribute of sys.flags to True * io.IOBase destructor logs close() exceptions -X utf8: enable UTF-8 mode for operating system interfaces, overriding the default locale-aware mode. -X utf8=0 explicitly disables UTF-8 mode (even when it would otherwise activate automatically) -X pycache_prefix=PATH: enable writing .pyc files to a parallel tree rooted at the given directory instead of to the code tree --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>\python{major}{minor}. PYTHONPLATLIBDIR : override sys.platlibdir. PYTHONCASEOK : ignore case in 'import' statements (Windows). PYTHONUTF8: if set to 1, enable the UTF-8 mode. 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 and bytes 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. PYTHONBREAKPOINT: if this variable is set to 0, it disables the default debugger. 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.
浙公网安备 33010602011771号