Python官方文档学习笔记
原文:https://docs.python.org/3/tutorial/introduction.html
版本:3.11.2
Using Python as a Calculator
Numbers
- Division
(/)
always returns a float. - To do floor division and get an integer result you can use the
//
operator; - To calculate the remainder you can use
%
- With Python, it is possible to use the
**
operator to calculate powers
4/2
Out[2]: 2.0
4//2
Out[3]: 2
5 % 2
Out[4]: 1
2 ** 3
Out[5]: 8
- In interactive mode, the last printed expression is assigned to the variable
_
. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
>>> 4/2
2.0
>>> _ + 1
3.0
Strings
\
can be used to escape quotes 转义字符: \ !
>>> "doesn\'t"
"doesn't"
>>> '"doesn\'t"'
'"doesn\'t"'
''
单引号内套双引号,可以使转义字符失效;但print()
会删掉外侧的单引号,又使得转义字符生效
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
- Raw strings
>>> print('C:\some\name') # \n被识别为换行符
C:\some
ame
>>> print(r'C:\some\name') # 在括号外面加上r可以打印出原字符
C:\some\name
>>> print("""\
... Usage: thingy [OPTIONS]
... -h Display this usage message
... -H hostname Hostname to connect to
... """)
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
>>> print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
\""")
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
- Python strings cannot be changed — they are immutable.
如果需要更改字符串,应该使其赋值等于一个新的变量。
Lists
- All slice operations return a new list containing the requested elements. This means that the slice returns a shallow copy of the list.
对列表的切片会返回一个原列表的浅复制 - Unlike strings, which are immutable, lists are a mutable type
First Steps Towards Programming
- 非零整数的布尔值为真,零为False。
- 长度不为零的Sequence对象为True,空的sequence为False。
More Control Flow Tools
for
Statements
Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
对一个sequence循环时,如果还需要对sequence本身进行修改,最好对sequence的copy进行循环
# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}
# Strategy: 对sequence本身循环
for user, status in users.items():
if status == 'inactive':
del users[user]
# 上述循环也可以正常返回删除inactive后的字典。
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status
上述例子中,如果直接对users本身循环,则默认是对key循环,所以不能添加两个参数。同时对key和value循环,必须得是对users.items()
break
andcontinue
Statements
break结束最内侧的循环,continue直接开始下一次循环match
Statements (released in python3.10)
Only the first pattern that matches gets executed and it can also extract components (sequence elements or object attributes) from the value into variables.
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
_
可以代表任何情况
Defining Functions
- 没有返回值的函数,会默认返回None
>>> def add(a,b):
... a + b
>>> add(1,2) # 没有任何输出
>>> print(add(1,2))
None # 输出None
- A method is a function that ‘belongs’ to an object and is named
obj.methodname
, whereobj
is some object - 假设定义函数时将参数的默认值设为某个变量,如果在函数定义前后改变这个变量的值,那么该参数的默认值将取定以前的变量值.
i = 5
def f(arg=i):
print(arg)
i = 6
f() # 将会输出5
- 参数的默认值只在第一次调用函数时生效,如果第一次调用函数时改变了参数的默认值,该参数将会沿用改变后的值.
def f(a, L=[]):
L.append(a)
return L
print(f(1)) # [1]
print(f(2)) # [1,2]
print(f(3)) # [1,2,3]
Class
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'