资源描述
Python
1.基本某些
1.1 下载地址&学习地址
官网下载即可。
1.2 作为计算器使用
>>> 2 + 2
4
>>> 50 - 5 * 6
20
>>> (50 - 5 * 6 ) / 4
5.0
>>> 8 / 5 #除法总是返回浮点数
1.6
>>> 17 / 3 #典型分区返回一种浮点数
5.667
>>>
>>> 17 // 3 #分区丢弃小数某些
5
>>> 17 % 3 #%运算符返回分区剩余某些
2
>> > 5 * 3 + 2 #成果*除数+余数
17
>>> 5 ** 2 #5平方
25
>>> 2 ** 7 #2 7
128 幂
>>> width = 20 #等号(=)用于为变量赋值
>>> height = 5 * 9
>>> width * height
900
>>> a=3+5j #支持虚数
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _ #在交互模式下最后打印表达式被分派给变量_(只读)
113.0625
>>> round (_ , 2 )
113.06
1.3 字符串
字符串表达可以用单引号('...')或双引号("...")括起来,成果相似。 \可以用来逃避引号:
(与其她语言不同,特殊字符(如\n单引号'...'和双"..."引号)具备相似含义。两者之间唯一区别在于,在单引号内,您不需要转义"(但您必要转义\'),反之亦然。)
>>> '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()函数通过省略封闭引号并打印转义字符和特殊字符,产生更易读输出:
>>> '"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.
如果您不但愿此前缀字符\被解释为特殊字符,则可以通过在第一种引号之前添加一种字符串来使用原始字符串r:
>>> 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
""")
产生如下输出(请注意,不涉及初始换行符):
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'
当您想要分隔长字符串时,此功能特别有用:
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
这只合用于两个文字,而不是变量或表达式:
>>> 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'
字符串可以被索引(下标),第一种字符索引为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'
请注意,由于-0与0相似,负指数从-1开始。
除了索引之外,还支持切片。虽然索引用于获取单个字符,但切片容许您获取子字符串:
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
请注意始终包括开始,并始终排除结尾。这可以保证始终等于:s[:i] + s[i:]s
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
切片索引具备有用默认值; 省略第一种索引默以为零,省略第二个索引默以为正在切片字符串大小。
>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'
要记住片工作是怎么想指数作为指着一种方向 之间字符,第一种字符左边沿编号为0之后字符串最后一种字符右边沿ñ字符具备指数ñ,例如:
+ --- + --- + --- + --- + --- + --- +
| P | y | t | h | o | n |
+ --- + --- + --- + --- + --- + --- +
0 1 2 3 4 5 6
- 6 - 5 - 4 - 3 - 2 - 1
第一行数字给出字符串中索引0 ... 6位置; 第二行给出相应负指数。从i到 j片段分别由标记为i和j边沿之间所有字符构成。
对于非负数指数,如果两者都在边界内,那么切片长度就是指数差值。例如,长度word[1:3]是2。
尝试使用太大索引会导致错误:
>>> 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:]
''
Python字符串不能变化 - 它们是不可变。因而,分派给字符串中索引位置会导致错误:
>>> 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'
内置函数len()返回一种字符串长度:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
1.4 列表
Python懂得许多复合数据类型,用于将其她值组合在一起。最通用是该列表,其可以写成方括号之间逗号分隔值(项目)列表。列表也许包括不同类型项目,但普通这些项目都具备相似类型。
>>> 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]
所有切片操作都会返回一种包括所祈求元素新列表。这意味着下面切片将返回列表新(浅)副本:
>>> 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]
您也可以使用该append() 办法在列表末尾添加新项目(咱们将在背面看到更多关于办法信息):
>>> 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]
对切片分派也是也许,这甚至可以变化列表大小或完全清除它:
>>> letters = ['a','b','c','d','e','f','g']
>>> letters
['a','b','c','d','e','f','g']
>>> # replace some values
>>> letters[2:5] = ['C','D','E']
>>> letters
['a','b','C','D','E','f','g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a','b','f','g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]
内置函数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'
1.5 简朴例子
>>> # 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
2.控制流程语句
2.1 if
>>> x = int(input("Please enter an integer:"))
Please enter an integer:42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
More
2.2 for
forPython中语句与您在C或Pascal中习惯使用语言有些不同。Pythonfor语句并不总是迭代数字算术级数(例如在Pascal中),或者让顾客可以定义迭代环节和停止条件(如C),Python 语句迭代任何序列项目(一种列表或一种字符串),按顺序出当前序列中。例如(没有双关意图):
>>> # Measure some strings:
... words = ['cat','window','defenestrate']
>>> for w in words:
... print(w,len(w))
...
cat 3
window 6
defenestrate 12
如果您需要修改在循环中迭代序列(例如复制选定项目),建议您先制作一份副本。遍历一种序列并不会隐式地创立一种副本。切片符号使这特别以便:
>>> for w in words[:]: # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0,w)
...
>>> words
['defenestrate','cat','window','defenestrate']
2.3 range()
如果您的确需要迭代一系列数字,则内置函数 range()将派上用场。它生成算术级数:
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
给定终点不是生成序列一某些; range(10)生成10个值,即长度为10序列项目合法索引。可以让范畴从另一种数字开始,或者指定一种不同增量(甚至是负数;有时这称为“环节”):
range(5,10)
5,6,7,8,9
range(0,10,3)
0,3,6,9
range(-10,-100,-30)
-10,-40,-70
要遍历序列指数,你可以结合range()和 len()如下:
>>> a = ['Mary','had','a','little','lamb']
>>> for i in range(len(a)):
... print(i,a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
如果您只打印一种范畴,会发生一件奇怪事情:
>>> print(range(10))
range(0,10)
在许多方面,返回对象range()行为就好像它是一种列表,但事实上并非如此。它是一种对象,它在您迭代时返回所需序列持续项,但它并不真正生成列表,从而节约空间。
咱们说这样一种对象是可迭代,也就是说,适合伙为函数和构造目的,盼望它们可以从中获得持续项目,直到耗尽。咱们已经看到这个for陈述是这样一种迭代器。该功能list() 是另一种; 它会依照迭代创立列表:
>>> list(range(5))
[0,1,2,3,4]
2.4 break,continue&else
break和在c语言里面同样,用于跳出for和while循环。
循环语句也许有一种else子句; 当循环通过用尽列表(with for)或当条件变为false(with while)时终结时执行,但当循环由break语句终结时不执行。这由如下循环来举例阐明,该循环搜索素数:
>>> for n in range(2,10):
... for x in range(2,n):
... if n % x == 0:
... print(n,'equals',x,'*',n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n,'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
上述else属于for,而不是if
continue语句也从C中借用,继续循环下一次迭代:
>>> for num in range(2,10):
... if num % 2 == 0:
... print("Found an even number",num)
... continue
... print("Found a number",num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
2.5 pass
该pass语句什么也不做。当语句需要语法时可以使用它,但程序不需要任何操作。例如:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
这通惯用于创立最小类:
>>> class MyEmptyClass:
... pass
...
另一种地方pass可以作为一种函数或条件体占位符,当你在解决新代码时,容许你继续思考一种更抽象层次。这pass是默默忽视:
>>> def initlog(*args):
... pass # Remember to implement this!
...
2.6 定义函数
咱们可以创立一种将斐波那契数列写入任意边界函数:
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a,b = 0,1
... while a < n:
... print(a,end=' ')
... a,b = b,a+b
... print()
...
>>> # Now call the function we just defined:
... fib()
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
核心字def引入了一种函数定义。它必要跟随函数名称和形式参数括号括起来列表。构成函数主体语句从下一行开始,并且必要缩进。
函数体第一种语句可以可选地是一种字符串文字; 此字符串文字是函数文档字符串或docstring。(关于文档字符串更多信息可以在文档字符串某些找到。)有某些工具可以使用文档自动生成在线或打印文档,或让顾客交互式浏览代码; 在您编写代码中包括文档字符串是一种较好做法,请养成习惯。
函数执行引入了一种用于函数局部变量新符号表。更确切地说,函数中所有变量赋值都将值存储在本地符号表中; 而变量引用一方面在本地符号表中查找,然后在封闭函数本地符号表中,然后在全局符号表中,最后在内置名称表中查找。因而,全局变量不能直接在函数内赋值(除非在global语句中命名),尽管它们也许被引用。
函数调用实际参数(参数)在被调用函数本地符号表中引入时被调用; 因而,参数通过值调用传递(其中值始终是对象引用,而不是对象值)。[1]当函数调用另一种函数时,为该调用创立一种新本地符号表。
函数定义在当前符号表中引入函数名称。函数名称值具备由解释器辨以为顾客定义函数类型。这个值可以分派给另一种名字,然后也可以作为一种函数使用。这是一种通用重命名机制:
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f (100 )
0 1 1 2 3 5 8 13 21 34 55 89
来自其她语言,你也许会反对,这fib不是一种函数,而是一种过程,由于它不返回一种值。事实上,虽然没有return声明函数也会 返回一种值,尽管这个值很无聊。这个值被调用None(这是一种内置名字)。写入值None普通会被解释器抑制,如果它是唯一写入值。你可以看到它,如果你真想使用print():
>>> fib(0)
>>> print(fib(0))
None
编写一种返回斐波那契数列表函数,而不是打印它函数很简朴:
>>> def fib2(n): # return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... result = []
... a,b = 0,1
... while a < n:
... result.append(a) # see below
... a,b = b,a+b
... return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0,1,1,2,3,5,8,13,21,34,55,89]
像往常同样,这个例子演示了某些新Python特性:
· 该return语句返回一种函数值。 return没有表达式参数返回None。掉落一种函数结尾也会返回None。
· 该语句result.append(a)调用列表对象 办法result。办法是一种“属于”对象并被命名函数obj.methodname,其中obj某个对象(这也许是一种表达式),并且methodname是由该对象类型定义办法名称。不同类型定义不同办法。不同类型办法可以具备相似名称而不会导致歧义。(可以使用类定义自己对象类型和办法,请参阅类)append()示例中显示办法是为列表对象定义; 它在列表末尾添加了一种新元素。在这个例子中它相称于result = result + [a] ,但更有效。
2.7带参数函数
也可以使用可变数量参数来定义函数。有三种形式,可以合并。
2.7.1 默认参数值
最有用形式是为一种或各种参数指定默认值。这创立了一种函数,它可以用比它定义容许参数更少参数来调用。例如:
def ask_ok(prompt,retries=4,reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y','ye','yes'):
return True
if ok in ('n','no','nop','nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
这个功能可以通过几种方式调用:
· 只给出强制性参数: ask_ok('Do you really want to quit?')
· 给出一种可选参数: ask_ok('OK to overwrite the file?', 2)
· 给出所有参数: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
这个例子还简介了in核心字。这测试一种序列与否包括某个值。
默认值是在定义范畴中函数定义点处计算 ,因而打印为5。
i = 5
def f(arg=i):
print(arg)
i = 6
f()
重要警告: 默认值只计算一次。当默认值是可变对象(如列表,字典或大多数类实例)时,这会有所不同。例如,如下函数会累积在后续调用中传递给它参数:
def f(a,L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
这将打印
[ 1 ]
[ 1 , 2 ]
[ 1 , 2 , 3 ]
如果你不想在后续调用之间共享默认值,你可以这样写:
def f(a,L=None):
if L is None:
L = []
L.append(a)
return L
2.7.2 核心字参数
也可以使用 表单核心字参数来调用函数kwarg=value。例如,如下功能:
def parrot(voltage,state='a stiff',action='voom',type='Norwegian Blue'):
print("-- This parrot wouldn't",action,end=' ')
print("if you put",voltage,"volts through it.")
print("-- Lovely plumage,the",type)
print("-- It's",state,"!")
接受一种所需参数(voltage)和三个可选参数(state,action,和type)。该功能可以通过如下任何方式调用:
parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000,action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM',voltage=1000000) # 2 keyword arguments
parrot('a million','bereft of life','jump') # 3 positional arguments
parrot('a thousand',state='pushing up the daisies') # 1 positional,1 keyword
但如下所有调用都是无效:
parrot() # required argument missing
parrot(voltage=5.0,'dead') # non-keyword argument after a keyword argument
parrot(110,voltage=220) # duplicate value for the same argument
parrot(actor='John Cleese') # unknown keyword argument
在函数调用中,核心字参数必要跟随位置参数。所有传递核心字参数必要与函数接受参数之一相匹配(例如actor,不是该parrot函数有效参数 ),它们顺序并不重要。这也涉及非可选参数(例如parrot(voltage=1000)也是有效)。没有参数也许会多次收到一种值。如下是由于此限制而失败示例:
>>> def function(a):
... pass
...
>>> function(0,a=0)
Traceback (most recent call last):
File "<stdin>",line 1,in <module>
TypeError:function() got multiple values for keyword argument 'a'
当表单最后形式参数**name存在时,它会接受一种包括所有核心字参数字典(参见映射类型 - 词典),除了那些相应于正式参数核心字参数。这可以与形式形式参数*name(在下一小节中描述)结合,其接受包括形式参数列表之外位置参数元组。(*name必要在之前浮现**name)。例如,如果咱们定义一种像这样函数:
def cheeseshop(kind,*arguments,**keywords):
print("-- Do you have any",kind,"?")
print("-- I'm sorry,we're all out of",kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw,":",keywords[kw])
它可以这样调用:
cheeseshop("Limburger","It's very runny,sir.",
"It's really very,VERY runny,sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
固然它会打印:
-- Do you have any Limburger ?
-- I'm sorry,we're all out of Limburger
It's very runny,sir.
It's really very,VERY runny,sir.
----------------------------------------
shopkeeper :Michael Palin
client :John Cleese
sketch :Cheese Shop Sketch
请注意,打印核心字参数顺序保证与它们在函数调用中提供顺序相匹配。
2.7.3 任意参数列表
最后,最不经常使用选项是指定可以用任意数量参数调用一种函数。这些参数将包括在一种元组中(请参阅元组和序列)。在可变数量参数之前,也许会浮现零个或各种正常参数。
def write_multiple_items(file,separator,*args):
file.write(separator.join(args))
普通,这些variadic参数将在形式参数列表中最后一种,由于它们会获取传递给该函数所有剩余输入参数。在参数背面浮现任何形式参数*args 都是“仅核心字”参数,这意味着它们只能用作
展开阅读全文