字符串:格式化

>>> "{0} love {1}.{2}" .format("I","pyton","com")

'I love pyton.com'

>>> 

>>> "{a} love {b}.{c}" .format(a='I',b='python',c='com')

'I love python.com'

>>> "{0} love {b}.{c}" .format('I',b='python',c='com')

'I love python.com'

>>> 

>>> "{a} love {b}.{0}" .format(a='I',b='python','com')

SyntaxError: positional argument follows keyword argument

>>>

>>> print('\ta')

a

>>> print ('\\')

\

>>> "`0`" .format("不打印")

'{0}'

>>> '{0:.1f}{1}'.format(27.658,'GB')

'27.7GB'

>>>

6.Python入门到精通_第1张图片

>>> '%c' % 97

'a'

>>> '%c %c %c' % (97,98,99)

'a b c'

>>> '%s' % 'I love Python'

'I love Python'

>>> '%d + %d = %d' %(4,5,4+5)

'4 + 5 = 9'

>>> '%o' % 10

'12'

>>> '%x' % 10

'a'

>>> '%X' % 10

'A'

>>> '%f' % 27.658

'27.658000'

>>> '%e' % 27.658

'2.765800e+01'

>>> '%E' % 27.658

'2.765800E+01'

>>> '%G' % 27.658

'27.658'

>>>

6.Python入门到精通_第2张图片

>>> '%f' % 27.658

'27.658000'

>>> '%e' % 27.658

'2.765800e+01'

>>> '%E' % 27.658

'2.765800E+01'

>>> '%G' % 27.658

'27.658'

>>> '%5.1f' % 27.658

' 27.7'

>>> '%.2e' % 27.658

'2.77e+01' 

>>> '%10d' % 5

'         5'

>>> '%-10d' % 5

'5         '

>>> '%+10d' % 5

'        +5'

>>>

>>> '%#o' % 10

'0o12'

>>> '%#X' % 108

'0X6C'

>>> '%#d' % 10

'10'

>>> '%010d' %5

'0000000005'

>>> '%-010d' %5

'5         '

>>>

6.Python入门到精通_第3张图片 

序列!序列!

列表、元组和字符串的共同点

都可以通过索引得到每一个元素

默认索引值总是从0开始

可以通过分片的方法得到一个范围内的元素的集合

有很多共同的操作符(重复操作符、拼接操作符、成员关系操作符)

>>> help(list)

Help on class list in module builtins:

 

class list(object)

 |  list() -> new empty list

 |  list(iterable) -> new list initialized from iterable's items

 |  

 |  Methods defined here:

 |  

 |  __add__(self, value, /)

 |      Return self+value.

 |  

 |  __contains__(self, key, /)

 |      Return key in self.

 |  

 |  __delitem__(self, key, /)

 |      Delete self[key].

 |  

 |  __eq__(self, value, /)

 |      Return self==value.

 |  

 |  __ge__(self, value, /)

 |      Return self>=value.

 |  

 |  __getattribute__(self, name, /)

 |      Return getattr(self, name).

 |  

 |  __getitem__(...)

 |      x.__getitem__(y) <==> x[y]

 |  

 |  __gt__(self, value, /)

 |      Return self>value.

 |  

 |  __iadd__(self, value, /)

 |      Implement self+=value.

 |  

 |  __imul__(self, value, /)

 |      Implement self*=value.

 |  

 |  __init__(self, /, *args, **kwargs)

 |      Initialize self.  See help(type(self)) for accurate signature.

 |  

 |  __iter__(self, /)

 |      Implement iter(self).

 |  

 |  __le__(self, value, /)

 |      Return self<=value.

 |  

 |  __len__(self, /)

 |      Return len(self).

 |  

 |  __lt__(self, value, /)

 |      Return self

 |  

 |  __mul__(self, value, /)

 |      Return self*value.n

 |  

 |  __ne__(self, value, /)

 |      Return self!=value.

 |  

 |  __new__(*args, **kwargs) from builtins.type

 |      Create and return a new object.  See help(type) for accurate signature.

 |  

 |  __repr__(self, /)

 |      Return repr(self).

 |  

 |  __reversed__(...)

 |      L.__reversed__() -- return a reverse iterator over the list

 |  

 |  __rmul__(self, value, /)

 |      Return self*value.

 |  

 |  __setitem__(self, key, value, /)

 |      Set self[key] to value.

 |  

 |  __sizeof__(...)

 |      L.__sizeof__() -- size of L in memory, in bytes

 |  

 |  append(...)

 |      L.append(object) -> None -- append object to end

 |  

 |  clear(...)

 |      L.clear() -> None -- remove all items from L

 |  

 |  copy(...)

 |      L.copy() -> list -- a shallow copy of L

 |  

 |  count(...)

 |      L.count(value) -> integer -- return number of occurrences of value

 |  

 |  extend(...)

 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable

 |  

 |  index(...)

 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.

 |      Raises ValueError if the value is not present.

 |  

 |  insert(...)

 |      L.insert(index, object) -- insert object before index

 |  

 |  pop(...)

 |      L.pop([index]) -> item -- remove and return item at index (default last).

 |      Raises IndexError if list is empty or index is out of range.

 |  

 |  remove(...)

 |      L.remove(value) -> None -- remove first occurrence of value.

 |      Raises ValueError if the value is not present.

 |  

 |  reverse(...)

 |      L.reverse() -- reverse *IN PLACE*

 |  

 |  sort(...)

 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

 |  

 |  ----------------------------------------------------------------------

 |  Data and other attributes defined here:

 |  

 |  __hash__ = None

 

>>>

迭代是重复反馈过程活动,其目的通常是为了接近达到所需的目标或结果。

>>> a = list()

>>> a

[]

>>> b = 'I love Pyton'

>>> b = list(b)

>>> b

['I', ' ', 'l', 'o', 'v', 'e', ' ', 'P', 'y', 't', 'o', 'n']

>>>

>>> c = (1,1,2,3,5,8,13,21,34)

>>> c = list(c)

>>> c

[1, 1, 2, 3, 5, 8, 13, 21, 34]

>>>

Tuple([iterable])把一个可迭代对象转换为元组

>>> help(tuple)

Help on class tuple in module builtins:

 

class tuple(object)

 |  tuple() -> empty tuple

 |  tuple(iterable) -> tuple initialized from iterable's items

 |  

 |  If the argument is a tuple, the return value is the same object.

 |  

 |  Methods defined here:

 |  

 |  __add__(self, value, /)

 |      Return self+value.

 |  

 |  __contains__(self, key, /)

 |      Return key in self.

 |  

 |  __eq__(self, value, /)

 |      Return self==value.

 |  

 |  __ge__(self, value, /)

 |      Return self>=value.

 |  

 |  __getattribute__(self, name, /)

 |      Return getattr(self, name).

 |  

 |  __getitem__(self, key, /)

 |      Return self[key].

 |  

 |  __getnewargs__(...)

 |  

 |  __gt__(self, value, /)

 |      Return self>value.

 |  

 |  __hash__(self, /)

 |      Return hash(self).

 |  

 |  __iter__(self, /)

 |      Implement iter(self).

 |  

 |  __le__(self, value, /)

 |      Return self<=value.

 |  

 |  __len__(self, /)

 |      Return len(self).

 |  

 |  __lt__(self, value, /)

 |      Return self

 |  

 |  __mul__(self, value, /)

 |      Return self*value.n

 |  

 |  __ne__(self, value, /)

 |      Return self!=value.

 |  

 |  __new__(*args, **kwargs) from builtins.type

 |      Create and return a new object.  See help(type) for accurate signature.

 |  

 |  __repr__(self, /)

 |      Return repr(self).

 |  

 |  __rmul__(self, value, /)

 |      Return self*value.

 |  

 |  count(...)

 |      T.count(value) -> integer -- return number of occurrences of value

 |  

 |  index(...)

 |      T.index(value, [start, [stop]]) -> integer -- return first index of value.

 |      Raises ValueError if the value is not present.

 

>>>

Str(obj)obj对象转换为字符串

>>> len(a)

0

>>> len(b)

12

>>> b

['I', ' ', 'l', 'o', 'v', 'e', ' ', 'P', 'y', 't', 'o', 'n']

max()返回序列或者参数集合中的最大值

>>> max(1,2,3,4,5)

5

>>> max(b)

'y'

>>> numbers = [1,18,13,0,-98,34,67,89,32]

>>> max(numbers)

89

>>>

min()返回序列或者参数集合中的最小值

>>> min(numbers)

-98

>>> chars = '1234567890'

>>> min(chars)

'0'

>>> tuple1 = (1,2,3,4,5,6,7,8,9,0)

>>> min(tuple1)

0

>>>

sum(iterable[,start=0])返回序列iterable和可选参数start的总和

>>> tuple2 = (3,1,2,3,3,4)

>>> sum(tuple2)

16

>>> sum(tuple2,4)

20

>>>

>>> chars

'1234567890'

>>> sum(chars)

Traceback (most recent call last):

  File "", line 1, in

    sum(chars)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

>>>

>>> sorted(numbers)

[-98, 0, 1, 13, 18, 32, 34, 67, 89]

>>> reversed(numbers)

>>> list(reversed(numbers))

[32, 89, 67, 34, -98, 0, 13, 18, 1]

>>> enumerate(numbers)

>>> list(enumerate(numbers))

[(0, 1), (1, 18), (2, 13), (3, 0), (4, -98), (5, 34), (6, 67), (7, 89), (8, 32)]

>>> a = [1,2,3,4,5,6,7,8]

>>> b = [4,5,6,7,8]

>>> zip (a,b)

>>> list(zip(a,b))

[(1, 4), (2, 5), (3, 6), (4, 7), (5, 8)]

>>>

函数:Python的乐高积木

函数

对象

模块

6.Python入门到精通_第4张图片 

>>> def MySecondFunction(name):

print(name + '我爱你')

>>> MySecondFunction('jm')

jm我爱你

>>> MySecondFunction('j')

j我爱你

>>> def add(num1 , num2):

result = num1 + num2

print(result)

 

>>> def add(num1 , num2):

result = num1 + num2

print(result)

 


>>> add(1 , 2)

3

>>> def add(num1 , num2):

return (num1 + num2)

 

>>> print (add(5 , 6))

11

>>> print (11)

11

>>>

形参和实参

>>> def MyFirstFunction(name):

'函数定义过程中的name是叫形参'

#因为Ta只是一个形式,表示占据一个参数位置

print('传递进来的' + name + '叫做实参,因为Ta是具体的参数值!')

>>> MyFirstFunction('jm')

传递进来的jm叫做实参,因为Ta是具体的参数值!

形式参数(parameter)  实际参数(argument

函数文档

>>> def MyFirstFunction(name):

'函数定义过程中的name是叫形参'

#因为Ta只是一个形式,表示占据一个参数位置

print('传递进来的' + name + '叫做实参,因为Ta是具体的参数值!')

 

>>> MyFirstFunction('jm')

传递进来的jm叫做实参,因为Ta是具体的参数值!

>>> MyFirstFunction.__doc__

'函数定义过程中的name是叫形参'

>>>

>>> help(MyFirstFunction)

Help on function MyFirstFunction in module __main__:

 

MyFirstFunction(name)

    函数定义过程中的name是叫形参

 

>>> print .__doc__

"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile:  a file-like object (stream); defaults to the current sys.stdout.\nsep:   string inserted between values, default a space.\nend:   string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."

>>> help(print)

Help on built-in function print in module builtins:

 

print(...)

    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    

    Prints the values to a stream, or to sys.stdout by default.

    Optional keyword arguments:

    file:  a file-like object (stream); defaults to the current sys.stdout.

    sep:   string inserted between values, default a space.

    end:   string appended after the last value, default a newline.

    flush: whether to forcibly flush the stream.

 

>>>

关键字参数

>>> def SaySome(name , words):

print(name + '->' + words)

 


>>> SaySome('jm','让编程改变世界!')

jm->让编程改变世界!

>>> SaySome('让编程改变世界!','jm')

让编程改变世界!->jm

>>> SaySome(words='让编程改变世界!',name='jm')

jm->让编程改变世界!

>>>

默认参数

>>> def SaySome(name='jm',words='让编程改变世界!'):

print(name + '->' + words)

 


>>> SaySome()

jm->让编程改变世界!

>>> SaySome('j')

j->让编程改变世界!

>>> SaySome('j','m')

j->m

>>>

收集参数

>>> def test(*params):

print('参数的长度是:',len(params));

print('第二参数是:',params[1]);

 


>>> test(1,'jm',3,14,5,6,7,8,9)

参数的长度是: 9

第二参数是: jm

>>>

>>> def test(*params,exp):

print('参数的长度是:',len(params),exp);

print('第二参数是:',params[1]);

 


>>> test(1,'jm',3,14,5,6,7,8,9)

Traceback (most recent call last):

  File "", line 1, in

    test(1,'jm',3,14,5,6,7,8,9)

TypeError: test() missing 1 required keyword-only argument: 'exp'

>>> test(1,'jm',3,14,5,6,7,8,exp = 9)

参数的长度是: 8 9

第二参数是: jm

>>>

函数与过程

>> def hello():

print("Hello python")

 


>>> temp = hello()

Hello python

>>> temp

>>>

>>> print(temp)

None

>>>

>>> type(temp)

>>>

再谈谈返回值

>>> def back():

return [1,'a',3.14]

 

>>> back()

[1, 'a', 3.14]

>>> def back():

return 1,'a',3.14

 

>>> back()

(1, 'a', 3.14)

>>>

我的地盘听我的

def discounts(price, rate):

    final_price = price * rate

    old_price = 88 #这里试图修改全局变量

    print('修改后old_price的值是:', old_price)

    return final_price

 

old_price = float(input('请输入原价:'))

rate = float(input('请输入折扣率:'))

new_price = discounts(old_price, rate)

print('修改后old_price的值是:', old_price)

print('打折后价格是:', new_price)

函数:内嵌函数和闭包

>>> count = 5

>>> def MyFun():

count = 10

print(10)

 


>>> MyFun()

10

>>> print (count)

5

>>>

 

>>> def MyFun():

global count

count = 10

print (10)

 

>>> MyFun()

10

>>> print(count)

10

>>>

内嵌函数

>>> def fun1():

print('fun1()正在被调用...')

def fun2():

print('fun2()正在被调用...')

fun2()

 


>>> fun1()

fun1()正在被调用...

fun2()正在被调用...

>>>

 闭包

>>> def FunX(x):

def FunY(y):

return x * y

return FunY

 

>>> i=FunX(8)

>>> i

.FunY at 0x0000000002E406A8>

>>> type(i)

>>> i(5)

40

>>> FunX(8)(5)

40

>>>

>>> FunY(5)

Traceback (most recent call last):

  File "", line 1, in

    FunY(5)

NameError: name 'FunY' is not defined

>>>

>>> def Fun1():

x=5

def Fun2():

x *= x

return x

return Fun2()

 

>>> Fun1()

Traceback (most recent call last):

  File "", line 1, in

    Fun1()

  File "", line 6, in Fun1

    return Fun2()

  File "", line 4, in Fun2

    x *= x

UnboundLocalError: local variable 'x' referenced before assignment

>>>

>>> def Fun1():

x = [5]

def Fun2():

x[0] *= x[0]

return x[0]

return Fun2()

 

>>> Fun1()

25

>>>

>>> def Fun1():

x = 5

def Fun2():

nonlocal x

x *= x

return x

return Fun2()

 

>>> Fun1()

25

>>>

函数:lambda表达式

>>> def ds(x):

return 2* x + 1

 

>>> ds(5)

11

>>> lambda x : 2 * x + 1

at 0x0000000002E40AE8>

>>> g = lambda x : 2 * x + 1

>>> g(5)

11

>>> def add(x,y):

return x + y

 

>>> add(3,4)

7

>>> lambda x , y : x + y

at 0x0000000002E1DF28>

>>> g = lambda x , y : x + y

>>> g(3 , 4)

7

>>>

Python写一些执行脚本时,使用lambda就可以省下定义函数过程,比如说我们只是需要写个简单的脚本来管理服务器时间,我们就不需要专门定义一个函数然后再写调用,使用lambda就可以使得代码更加精简。

对于一些比较抽象并且整个程序执行下来只需要调用一两次的函数,有时候给函数起个名字也是比较头疼的问题,使用lambda就不需要考虑命名的问题了。

简化代码的可读性,由于普通的屌丝函数阅读经常要跳到开头def定义部分,使用lambda函数可以省去这样的步骤。

两个牛逼的BIF

>>> help(filter)

Help on class filter in module builtins:

 

class filter(object)

 |  filter(function or None, iterable) --> filter object

 |  

 |  Return an iterator yielding those items of iterable for which function(item)

 |  is true. If function is None, return the items that are true.

 |  

 |  Methods defined here:

 |  

 |  __getattribute__(self, name, /)

 |      Return getattr(self, name).

 |  

 |  __iter__(self, /)

 |      Implement iter(self).

 |  

 |  __new__(*args, **kwargs) from builtins.type

 |      Create and return a new object.  See help(type) for accurate signature.

 |  

 |  __next__(self, /)

 |      Implement next(self).

 |  

 |  __reduce__(...)

 |      Return state information for pickling.

 

>>> filter(None,[1,0,False,True])

>>> list(filter(None,[1,0,False,True]))

[1, True]

>>> def odd(x):

return x % 2

 

>>> temp = range(10)

>>> show = filter(odd,temp)

>>> list(show)

[1, 3, 5, 7, 9]

>>> list(filter(lambda x : x % 2, range(10)))

[1, 3, 5, 7, 9]

>>>

>>> list(map(lambda x : x * 2, range(10)))

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>>