Python 文档阅读01

python语言特性

  • 相比于shell脚本,pytho提供更多的支持
  • 相比于C,python提供更多的参数检查
  • 是一种高级语言,内置很多数据类型
  • 允许在单行语句中执行复杂的操作
  • 语句通过缩进进行分组(4个空格),不是括号
  • 是一种动态语言,变量可重新赋值
  • 变量不需要参数声明,没有变量也可以
  • 本身附带很多的模块,也可以将程序拆分成很多模块
  • 可用于Web开发,图形界面,科学运算,机器学习等方面
  • 是一种解释性语言,可以极大节约开发时间
  • 代码风格紧凑,易读性好
  • Python是以BBC节目“Monty Python’s Flying Circus”命名的,与爬行动物无关

Python使用简介

#后面内容代表单行注释,例如
# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
将Python作为计算器

可以想其它语言一样使用+, -, *, /,也可以使用()进行分组,例如

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6

整数(2, 100, -6)的类型是整型int,有小数部分(1.6, -6.0)的类型是浮点型float;除法/永远返回浮点数,使用地板除//可以得到一个向下取整的整数,使用%可以得到余数;Python可以使用**,来表示冥运算例如

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

=表示赋值,将值指定给变量名,应理解为将变量名指向变量,调用为赋值的变量会报错

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

包含浮点数的运算,结果总会返回浮点数;在python解释器中,可用_表示上一次打印的值,例如

>>> 4 * 3.75 - 1
14.0
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

字符串

Python中,将"...", '...'括起的内容表示字符串,在字符串里,可以使用\转义符,显示单个括号,例如

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

输出易读字符串使用print()函数,注意:特殊的字符应该使用反斜杠转义;也可以使用r'...'表示原始字符串,内部不转义,例如

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.
>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\name

字符串也可以书写多行字符串,使用三括号"""...""", '''...''', 最后一行默认包含一行字符串,通常为了避免它,使用\,例如

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")
# output
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

字符串可以使用+进行拼接和使用*进行重复;当只有两个字符串相邻,默认拼接在一起,但变量或者表达式就不行,如果想拼接变量或表达式,可以使用+;上面这种特性可以方便输入长字符串,例如

>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
>>> 'Py' 'thon'
'Python'
>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  ...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  ...
SyntaxError: invalid syntax
>>> prefix + 'thon'
'Python'
>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

字符串也可以被索引,第一个位置索引为0,也可以从右侧索引,起始位置为-1,例如

>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'
>>> word[-1]  # last character
'n'
>>> word[-2]  # second-last character
'o'
>>> word[-6]
'P'

切片也适用于字符串,返回一个子集;起始位置总包含在内,而结束位置则不包含,是为了s[:i] + s[i:]==s;起始位置忽略是默认为0,终止位置忽略时默认到后面全部可切片值,例如

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

切片原理助记;当索引太大时,会报错,但切片太大时,则不会报错

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> word[4:42]
'on'
>>> word[42:]
''

字符串是不可以更改的,所以是不能通过索引重新赋值的;但我们可以通过创建一个新的来达到目的;内置函数len()可以获取字符串长度,例如

>>> word[0] = 'J'
  ...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
  ...
TypeError: 'str' object does not support item assignment
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

Lists列表

列表可以包含不同数据类型的数据,但建议他们都是一种类型,通过[]表示列表;列表支持切片和索引(有序地),例如:

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]

切片返回一个请求元素的新列表,是一种浅拷贝;列表也支持链接+;列表是可变的,可以重新赋值,可以使用append()添加一条数据到末尾,例如

>>> squares[:]
[1, 4, 9, 16, 25]
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]
>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

通过切片改变列表;len()函数可以计算列表元素多少;列表也可以作为列表的元素,例如

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

编程第一步

可以使用Python做更复杂的任务,例如斐波拉契数列,例如

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print(b)
...     a, b = b, a+b
...
1
1
2
3
5
8
  • 上面第一行,同时对多个参数进行初始赋值,一一对应,如果包含运算,则会先计算右侧或将整个表达式复制给左侧变量
  • while循环,当后面条件为真(非空非0:non-zero)的时候就会执行缩进代码块,标准的比较方式与C一样,>, <, >=, =<, !=
  • 循环的内容是缩进的,在Python中通过缩进对代码进行分组
  • print()函数,将参数的值打印到屏幕,也可以接受另一个参数end='..',,来改变输出样式,默认换行
>>> a, b = 0, 1
>>> while b < 1000:
...     print(b, end=',')
...     a, b = b, a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值