Python基础(一)
Python入门知识拾遗
1.标识符
1 字母数字下划线组成,不能以数字开头
2.关键字
1 系统定义的标识符我们不能再次定义
1 In [3]: help('keywords')
2
3 Here is a list of the Python keywords. Enter any keyword to get more help.
4
5 False def if raise
6 None del import return
7 True elif in try
8 and else is while
9 as except lambda with
10 assert finally nonlocal yield
11 break for not
12 class from or
13 continue global pass
注:其他常见帮助函数
查看python所有的modules:help("modules")
单看python所有的modules中包含指定字符串的modules: help("modules yourstr")
查看python中常见的topics: help("topics")
查看python标准库中的module:import os.path + help("os.path")
查看python内置的类型:help("list")
查看python类型的成员方法:help("str.find")
查看python内置函数:help("open")
3.作用域
在之前学习变量的作用域时,经常会提到局部变量和全局变量,之所有称之为局部、全局,就是因为他们的自作用的区域不同,这就是作用域
(1)Python无块级作用域
所谓块集作用域,需要先了解Python的代码块概念。Python遵从严格的缩进标准,可以认为处在同一缩进之间的代码即为一个代码块。如if判断,for,while循环等。
(2)Python以函数为作用域
Python语法中,函数体为单独的作用域。就行在运行代码时,遇到函数默认是不执行函数体里面的代码的,等待调用函数后才会执行。因此,函数内定义的变量只能在函数内调用。
1 #作用域链
2
3 name = "lzl"
4 def f1():
5 name = "Eric"
6 def f2():
7 name = "Snor"
8 print(name)
9 f2()
10 f1()
局部变量:函数里面定义的变量,只能在函数里面访问到,当超出其作用域时,将失去其作用
全局变量:函数外部定义的变量,无论在任何作用域都可以使用。当前作用域有相同变量名的局部变量时,局部变量生效。
全部变量定义的位置:函数定义之外,函数调用之前
(3)全局变量和局部变量名字相同时
1 当局部变量和全局变量名字相同时,默认对局部变量进行修改,若要对全局变量修改,需要声明global
1 '''
2 def get_wendu():
3 wendu = 33
4 return wendu
5
6 def print_wendu(wendu):
7 print("温度是%d"%wendu)
8
9 result = get_wendu() #如果一个函数有返回值,但是没有在调用函数之前 用个变量保存的话,那么没有任何意义
10 print_wendu(result)
11 '''
12
13 #定义一个全局变量,wendu
14 wendu = 0
15
16 def get_wendu():
17 #如果wendu这个变量已经在全局变量的位置定义了,此时还想在汉书中对全局变量进行进行修改的话
18 #那么 仅仅是wendu=一个值 这还不够,,此时这个wendu这个变量是一个局部变量,只不过与全局变量名字相同罢了
19 #wendu = 33
20
21 #使用global用来对一个全局变量的声明,那么这个函数中的wendu=33就不是定义一个局部变量,
22 #而是对全局变量进行修改
23 global wendu
24 wendu = 33
25
26 def print_wendu():
27 print("温度是%d"%wendu)
28
29 get_wendu()
30 print_wendu()
1 a = 100
2 #建议
3 #g_a = 100
4
5 def test():
6 a = 200#在函数中 如果对一个和全局变量名相同的变量进行=value的时候,默认是定义一个变量
7 #只不过这个变量的名字和全局变量的名字相同罢了
8 #
9 #如果想在执行a=value时,不是定义局部变量,而是对全局变量修改,那么可以添加global进行声明
10 print("a=%d"%a)
11
12 def test1():
13 print("a=%d"%a)#如果这里打印了100就声明了test函数没有对全局变量修改,而是定义了一个局部变量
14
15
16 test()
17 test1()
1 In [15]: x = [lambda :x for x in range(10)]
2
3 In [16]: x.__class__
4 Out[16]: list
5
6 In [17]: x[0].__class__
7 Out[17]: function
8
9 In [18]: x[0]()
10 Out[18]: 9
(4)列表和字典当做全局变量时
字典和列表为全局变量时,在函数内部进行修改时不需要声明global,可以直接修改
(5)命名空间
命名空间
大约来说,命名空间就是一个容器,其中包含的是映射到不同对象的名称。你可能已经听说过了,Python中的一切——常量,列表,字典,函数,类,等等——都是对象。
这样一种“名称-对象”间的映射,使得我们可以通过为对象指定的名称来访问它。
我们可以把命名空间描述为一个Python字典结构,其中关键词代表名称,而字典值是对象本身(这也是目前Python中命名空间的实现方式),如:
a_namespace = {'name_a':object_1, 'name_b':object_2, ...}
现在比较棘手的是,我们在Python中有多个独立的命名空间,而且不同命名空间中的名称可以重复使用(只要对象是独一无二的),比如:
a_namespace = {'name_a':object_1, 'name_b':object_2, ...}
b_namespace = {'name_a':object_3, 'name_b':object_4, ...}
举例来说,每次我们调用for循环或者定义一个函数的时候,就会创建它自己的命名空间。命名空间也有不同的层次(也就是所谓的“作用域”),
作用域:在上一节中,我们已经学习到命名空间可以相互独立地存在,而且它们被安排在某个特定层次,由此引出了“作用域”的概念。Python中的“作用域”定义了一个“层次”,
我们从其中的命名空间中查找特定的“名称-对象”映射对。
我们已经知道了多个命名空间可以独立存在,而且可以在不同的层次上包含相同的变量名。“作用域”定义了Python在哪一个层次上查找某个“变量名”对应的对象。接下来的问题就是:“Python在查找‘名称-对象’映射时,是按照什么顺序对命名空间的不同层次进行查找的?”
答案就是:使用的是LEGB规则,表示的是Local -> Enclosed -> Global -> Built-in,其中的箭头方向表示的是搜索顺序。
Local 可能是在一个函数或者类方法内部。
Enclosed 可能是嵌套函数内,比如说 一个函数包裹在另一个函数内部。
Global 代表的是执行脚本自身的最高层次。
Built-in 是Python为自身保留的特殊名称。
因此,如果某个name:object映射在局部(local)命名空间中没有找到,接下来就会在闭包作用域(enclosed)进行搜索,如果闭包作用域也没有找到,Python就会到全局(global)命名空间中进行查找,最后会在内建(built-in)命名空间搜索(注:如果一个名称在所有命名空间中都没有找到,就会产生一个NameError)。
4.三元运算
result = value1 if 条件 else value2 如果条件为真:result = value1 如果条件为假:result = value2
5.进制转换

In [25]: a = 10
In [26]: bin(a)
Out[26]: '0b1010'
In [27]: oct(a)
Out[27]: '0o12'
In [28]: hex(a)
Out[28]: '0xa'
Python基础

所以以下这些值都是对象: "zhangyafei"、23、['太原', '晋城', '北京'],并且是根据不同的类生成的对象。

一、整数(int)
12,23,111
每个整数具有如下功能
class int(object):
"""
int(x=0) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
"""
def bit_length(self): # real signature unknown; restored from __doc__
"""
int.bit_length() -> int
Number of bits necessary to represent self in binary.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
"""
return 0
def conjugate(self, *args, **kwargs): # real signature unknown
""" Returns self, the complex conjugate of any int. """
pass
@classmethod # known case
def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
int.from_bytes(bytes, byteorder, *, signed=False) -> int
Return the integer represented by the given array of bytes.
The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
The byteorder argument determines the byte order used to represent the
integer. If byteorder is 'big', the most significant byte is at the
beginning of the byte array. If byteorder is 'little', the most
significant byte is at the end of the byte array. To request the native
byte order of the host system, use `sys.byteorder' as the byte order value.
The signed keyword-only argument indicates whether two's complement is
used to represent the integer.
"""
pass
def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
int.to_bytes(length, byteorder, *, signed=False) -> bytes
Return an array of bytes representing an integer.
The integer is represented using length bytes. An OverflowError is
raised if the integer is not representable with the given number of
bytes.
The byteorder argument determines the byte order used to represent the
integer. If byteorder is 'big', the most significant byte is at the
beginning of the byte array. If byteorder is 'little', the most
significant byte is at the end of the byte array. To request the native
byte order of the host system, use `sys.byteorder' as the byte order value.
The signed keyword-only argument determines whether two's complement is
used to represent the integer. If signed is False and a negative integer
is given, an OverflowError is raised.
"""
pass
def __abs__(self, *args, **kwargs): # real signature unknown
""" abs(self) """
pass
def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass
def __and__(self, *args, **kwargs): # real signature unknown
""" Return self&value. """
pass
def __bool__(self, *args, **kwargs): # real signature unknown
""" self != 0 """
pass
def __ceil__(self, *args, **kwargs): # real signature unknown
""" Ceiling of an Integral returns itself. """
pass
def __divmod__(self, *args, **kwargs): # real signature unknown
""" Return divmod(self, value). """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __float__(self, *args, **kwargs): # real signature unknown
""" float(self) """
pass
def __floordiv__(self, *args, **kwargs): # real signature unknown
""" Return self//value. """
pass
def __floor__(self, *args, **kwargs): # real signature unknown
""" Flooring an Integral returns itself. """
pass
def __format__(self, *args, **kwargs): # real signature unknown
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __index__(self, *args, **kwargs): # real signature unknown
""" Return self converted to an integer, if self is suitable for use as an index into a list. """
pass
def __init__(self, x, base=10): # known special case of int.__init__
"""
int(x=0) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
# (copied from class doc)
"""
pass
def __int__(self, *args, **kwargs): # real signature unknown
""" int(self) """
pass
def __invert__(self, *args, **kwargs): # real signature unknown
""" ~self """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lshift__(self, *args, **kwargs): # real signature unknown
""" Return self<<value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
def __mod__(self, *args, **kwargs): # real signature unknown
""" Return self%value. """
pass
def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
def __neg__(self, *args, **kwargs): # real signature unknown
""" -self """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
"""
