Python官方文档学习笔记

发布时间 2023-03-29 22:22:09作者: 梁书源

原文: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