1.保留字

保留字即关键字,我们不能把它们用作任何标识符名称。Python 的标准库提供了一个 keyword 模块,可以输出当前版本的所有关键字

>>> import keyword
>>> 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']

2.注释

多行注释可以用多个 # 号,还有 ‘’’“”"

# 第一个注释
# 第二个注释

'''
第三注释
第四注释
'''

"""
第五注释
第六注释
"""
print ("这是咱的第一个python!")

3.缩进与行

【缩紧】python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {} 。缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。

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

【行与换行】Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠()来实现多行语句。在 [], {}, 或 () 中的多行语句,不需要使用反斜杠()

total = num1 + \
num2 + \
num3
week = ['星期一','星期二','星期三','星期四','星期五','星期六','星期天']

4.数字类型 Number

数字的四种类型:整型 布尔 浮点数 复数

· int 证书类型. 1

·bool 布尔类型 True. True False

·float 浮点数. 1.23 3E-2

·complex 复数. 1+2j、 1.1+2.2j

4.字符串 String

·python中单引号和双引号一样 word = ‘字符串’ word = “字符串”

·三引号(‘’’ 或者"“”) 指定一个多行字符串。注意开闭统一

·转译符号 ‘’

·反斜杠用来转移 r防止反斜杠转移 如:r’zhao Phor \n’ 的\n会显示

·按字面意义级联字符串,如"this " "is " "string"会被自动转换为this is string

·字符串拼接 + *运算符重复. 如:print(str * 2) # 输出字符串两次

·两种索引方式:0 左起➡️右 -1右起 ⬅️

·Python中的字符串不能改变。 解释如下 4.a

·Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。

·字符串的截取的语法格式如下:变量[头下标:尾下标:步长]

4.a Python中的字符串不能改变

python中字符串是不可变类型,即无法直接修改字符串的某一位字符。
例如想把'abc123'修改成'abcd23',若执行下面代码:
a = 'abc123'
a[3] = 'd' # 字符串下标是从0开始的,3代表第4个字符
会报错:
TypeError: 'str' object does not support item assignment
因为python语法中,字符串不支持直接赋值。

我们在编程时会经常遇到处理字符串,python修改字符串主要有3种方法:切片法、重新赋值和replace函数。

设当前字符串a = 'abc123',想要修改成'abcd123'。

法一:切片法
把字符串“切开”,在需要的地方添加进去新字符,再用加号连接。
# 设当前字符串a = "abc123",想要修改成"abcd123"
a = 'abc123'
a = a[:3] + 'd' + a[3:6] # [m:n]代表从下标m开始到下标n-1的字符;不写m的话默认为0
# 此处相当于取出来'abc',再后面加上'd',再加上'123'
print(a) # 输出abcd123
该方法是根据下标来执行的,当处理频繁修改字符串时,在for循环里执行切片法,效率是最高的。

法二:重新赋值
最简单粗暴的方法,直接覆盖掉原变量。
但其实变量并没有真的被“修改”,前后变量a占用的是不同的内存指针。可以用 id(a) 观察实际的内存指针。
# 法二:重新赋值
# 设当前字符串a = "abc123",想要修改成"abcd123"
a = 'abc123'
print(id(a))
a = 'abcd123'
print(id(a))
print(a) # 输出abcd123
执行上面代码,得到的输出是:
2138944357488
2138944252016
abcd123
可以看到,最终得到了我们想要的字符串'abcd123'。但前后变量a的内存并不相同。
这说明原本的a并没有被修改,而是被配置到了新的内存。

法三:replace函数
python自带的replace函数,能替换掉指定的部分。
a = a.replace('c', 'cd')意味着把a中的'c'改为'cd'。
a = 'abc123'
a = a.replace('c', 'cd')
print(a) # 输出abcd123

字符串测试:

str = 'Runoob'

print(str) # 输出字符串
print(str[0:-1]) # 输出第一个到倒数第二个的所有字符
print(str[0]) # 输出字符串第一个字符
print(str[2:5]) # 输出从第三个开始到第五个的字符
print(str[2:]) # 输出从第三个开始后的所有字符
print(str * 2) # 输出字符串两次
print(str + '你好') # 连接字符串

print('------------------------------')

print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义
/Users/zhaoxinglu/PycharmProjects/pythonProject/venv/bin/python /Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev/pydevd.py --multiprocess --qt-support=auto --client 127.0.0.1 --port 58494 --file /Users/zhaoxinglu/PycharmProjects/pythonProject/test.py 
Connected to pydev debugger (build 223.8617.48)
Runoob
Runoo
R
noo
noob
RunoobRunoobRunoob
Runoob你好
------------------------------
hello
runoob
hello\nrunoob

Process finished with exit code 0

5.空行

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。

类和函数入口之间也用一行空行分隔,以突出函数入口的开始。

空行与代码缩进不同,空行并不是Python语法的一部分。

书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。

**记住:**空行也是程序代码的一部分。

6.同一行显示多条语句

Python可以在同一行中使用多条语句,语句之间使用分号(;)分割

str1 = "hello";str2 = "world"; print(str1+str2)
helloworld

7.多个语句构成代码组

缩进相同的一组语句构成一个代码块,我们称之代码组。像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。

我们将首行及后面的代码组称为一个子句(clause)。

if True :
print("🤔")
else :
print("no")

8.Print 输出

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end=“”

print("Hi ")
print("Word!")

print("Hi ",end="")
print("Word!")
Hi 
Word!
Hi Word!

9.import 与 from...import

在 python 用 import 或者 from…import 来导入相应的模块。

将整个模块(somemodule)导入,格式为: import somemodule

从某个模块中导入某个函数,格式为: from somemodule import somefunction

从某个模块中导入多个函数,格式为: from somemodule import firstfunc, secondfunc, thirdfunc

将某个模块中的全部函数导入,格式为: from somemodule import *

import sys
print('================Python import mode==========================')
print ('命令行参数为:')
for i in sys.argv:
print (i)
print ('\n python 路径为',sys.path)
================Python import mode==========================
命令行参数为:
/Users/zhaoxinglu/PycharmProjects/pythonProject/test.py

python 路径为 ['/Users/zhaoxinglu/PycharmProjects/pythonProject', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/third_party/thriftpy', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev', '/Users/zhaoxinglu/PycharmProjects/pythonProject', '/Users/zhaoxinglu/Library/Caches/JetBrains/PyCharmCE2022.3/cythonExtensions', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python39.zip', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/zhaoxinglu/PycharmProjects/pythonProject/venv/lib/python3.9/site-packages']

10.命令行参数

很多程序可以执行一些操作来查看一些基本信息,Python可以使用-h参数查看各参数帮助信息:

zhaoxinglu@zhaoxingludeMBP ~ % python3 -h
usage: /Library/Developer/CommandLineTools/usr/bin/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 .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>/lib/pythonX.X.
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.