Python程序设计基础大一期末自主复习--第二章

第二章

2.1

(1)在Python中不许需要事先声明变量名及其类型,直接赋值即可创建任意类型的对象变量。不仅变量的值是可以变化的,变量的类型也是可以随时发生变化的。

(2)Python中的变量并不直接存储值,而是存储了值的内存地址或者引用。

(3)Python是一种不折不扣的强类型编程语言。

(4)变量名必须以字母或者下划线开头。

(5)变量名里不能有空格或者标点符号。

(6)不能用关键字做变量名。

(7)不建议使用系统内置的模块名、类型名、或函数名以及已导入的模块名及其成员名作为变量名。这会改变其类型和含义,甚至会导致其他代码无法正常执行。,所有内置对象名称如下。

>>> dir(__builtins__)

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

(8)变量名对英文字母大小写敏感,age和Age是两个单词。

(9)应尽量避免在实数之间直接进行相等性测试,而是应该以两者之差的绝对值是否足够小作为两个实数是否相等的依据。

(10)支持在数字中间位置使用单个下划线作为分隔来提高数字的可读性。(但是不能出现在开头或者结尾,也不能使用多个下划线)

(11)Python3.x全面支持中文,中文和英文字母都作为一个字符对待,甚至可以使用中文作为变量名。

(12)对str类型的字符串调用encode()方法进行编码得到beytes字节串,对bytes字节串调用decode()方法并指定正确的编码格式得到str字符串。

例:

>> type('hello world')

<class 'str'>

>>> type(b'hello world')

<class 'bytes'>

>>> 'hello world'.encode ('utf8')

b'hello world'

>>> 'hello world'('gbk')

Traceback (most recent call last):

  File "<pyshell#3>", line 1, in <module>

    'hello world'('gbk')

TypeError: 'str' object is not callable

>>> 'hello world'.encode('gbk')

b'hello world'

>>> '赵睿'.encode('gbk')

b'\xd5\xd4\xee\xa3'

>>> '赵睿'.encode('utf8')

b'\xe8\xb5\xb5\xe7\x9d\xbf'

>>> _.decode ('utf8')

'赵睿'

(13)

比较项

列表list[]

元组tuple()

字典dict{}

集合set{}

是否可变

是否有序

是否支持下标

是(使用序号作为下标)

是(使用序号作为下标)

是(使用键作为下标)

对元素形式的要求

键:值

必须可哈希(可以用内置函数hash得出哈希值)(对任意对象0,如果0_hash_()返回一个整型值,则0就是可哈希)

对元素值的要求

‘键’必须可哈希

必须可哈希

元素是否可重复

‘键’不允许重复,‘值’可以重复

元素查找速度

非常慢

很慢

非常快

非常快

新增和删除元素的速度

尾部操作快,其他位置慢

不允许

例:>>> x_dict={'a':1}

>>>

>>> x_dict={'a':1,'b':14}

>>> x_set={6,6,6}

>>> rriint{x_list[1]}

SyntaxError: invalid syntax

>>> print(x_list[1])

9

>>> rrint(x_tupel[0])

Traceback (most recent call last):

  File "<pyshell#17>", line 1, in <module>

    rrint(x_tupel[0])

NameError: name 'rrint' is not defined

>>> print(x_tuple[0])

1

>>> printx

Traceback (most recent call last):

  File "<pyshell#19>", line 1, in <module>

    printx

NameError: name 'printx' is not defined

>>>

>>>

>>>

>>>

>>> print()File "<pyshell#17>", line 1, in <module>

SyntaxError: invalid syntax

>>>

>>> print(x_dict['a'])

1

>>> 6 in x_set

True

(14)Python还提供有range,map,zip,filter,enumerate,reversed等大量迭代对象(迭代对象可以理解为表示数据流的对象,每次返回一个数据)。这些迭代对象大多具有与Python序列相似的操作方法,比较大的区别在于这些迭代对象大多具有惰性求值的特点,仅在需要时才给出新的元素,减少了对内存的占用。

2.2

(1)在Python中一切都是对象。

(2)*算术乘法,序列重复             

     %求余数,字符串格式化

     //求整商,如果操作数中有实数,结果为实数形式的整数。

     |位或   ^位异或    <<左移位   >>右移位  ~位求反

     &集合交集   |并集   ^对称差集

     @矩阵相乘运算符

(3)Python内部把True当做1处理,False当做0处理

>>> True+3

4

>>> False+2

2

(4)%示例

>>> '%c,%d'%(65,65)

'A,65'

>>> '%s,%f'%(65,65)

'65,65.000000'

(5)**表示幂运算,等价于内置函数pow()。

例如:

>>> 9**2

81

>>> pow(9,2)

81

>>> pow(9,2,9)  #等价于9**2%9

0

>>> pow(9,2,4)

1

>>> pow(9,2,1,5)

Traceback (most recent call last):

  File "<pyshell#36>", line 1, in <module>

    pow(9,2,1,5)

TypeError: pow() takes at most 3 arguments (4 given)

(5)Python关系运算符可以连用,操作数之间必须可比较大小。

(6)具有惰性求值或者逻辑短路特点

(7)如果两个对象是同一个,两者具有相同的内存地

(8)位运算符只能用于整数,内部执行过程为:首先将整数转换为二进制数,然后右对齐,必要时左侧补0,按位进行运算,最后再把结果转化为十进制数字返回。

(9)位与运算规则 1&1=1  1&0=0&1=0&0=0  

     位或运算规则1|1=1|0=0|1=1   0|0=0

     位异或运算规则1^1=0^0=0   1^0=0^1=1

(10)左移位时右侧补0,每左移一位相当于乘以二,右移位时左侧补0,每右移位相当于除以二。

>>> 3<<2

12

>>> 3&7

3

>>> 3|8

11

>>> 3^6

5

(11)集合的交集并集对称差集等运算借助于位运算符来实现,而茶几则是永健好运算符实现(注意,并集运算符不是加号)

2.4(1)内置函数bin(),oct(),hex()用来将整数为二进制,八进制和十六进制,这三个函数都要求参数必须为整数。

>>> bin(555)

'0b1000101011'

>>> oct(555)

'0o1053'

>>> hex(555)

'0x22b'

(2)

>>> ord('赵')

36213

>>> ord('睿')

30591

>>> ''.join(map(chr,(36213,30591)))

'赵睿'

 

 

>>> ascii('赵睿')

"'\\u8d75\\u777f'"

>>> eval(_)

'赵睿'

(3)在Python3.x中,reduce()不是内置函数,而是放到了标准库functools中,需要先导入在使用。

(4)函数式编程把问题分解为一系列的函数操作,输入依次流入和流出一系列函数,最终完成预定目标和任务。

(5)range函数返回具有惰性求值特点的range对象,其中包含左闭右开区间【start,end)内以step为步长的整数(参数start默认为0,step默认为1)。

 

 

 

 

 

 

 

2.5精彩案例赏析

2-1

用户输入一个三位自然数,计算并输出其百位、十位和个位上的数字。

解法一:

解法二:

         

解法三:

         

2-2已知三角形的两边及其夹角,求第三边长。

2-3任意输入三个英文单词,按字典顺序输出

  

 

 

习题

2.1  31

2.2  ‘F’

2.3

(1)垃圾回收

(2)引用计数

(3)内存池机制

2.4

单斜杠/和双斜杠//都是除法运算符

区别1.最大的区别就是返回结果不同,单斜杠/保留若干小数。双斜杠//保留最小整数

A//B只有两者都为int型结果才是int型

>>> type(9/8)
<class 'float'>
>>> type(9.0/8)
<class 'float'>
>>> type(9/8.0)
<class 'float'>
>>> type(9.0/8.0)
<class 'float'>
>>> type(9//8)
<class 'int'>
>>> type(9//8.0)
<class 'float'>
>>> type(9.0//8)
<class 'float'>
>>> type(9.0//8.0)
<class 'float'>

2.5可以

2.6是

2.7对

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值