Python基础复习---重点知识笔记(一)

本文是Python基础知识的复习笔记,重点介绍了函数的局部与全局作用域、异常处理,以及列表的切片、连接、复制、方法等操作。还探讨了字符串、元组的特性和字典的常用方法,包括错误处理、嵌套结构。最后讨论了参数传递的技巧和递归函数的概念。
摘要由CSDN通过智能技术生成

该篇文章是针对自己在学习python基础知识的时候,对于不易理解或者重点需要掌握知识的总结性概括。后续遇到的问题会不断加入进来!

文章目录


一、函数

1.1 局部作用域不能使用其他局部作用域内的变量

在这里插入图片描述
在这里插入图片描述

>>> def spam():
...     egg=0
...     bacon()
...     print(egg)
...
>>> def bacon():
...     haf=9
...     egg=33
...
>>> spam()
0

1.2 全局变量可以在局部作用域中读取

变元:变量

  • 如下: name 称为变元
def hello(name):
	print('Hello'+name)

在这里插入图片描述

1.3 名称相同的局部变量和全局变量

在这里插入图片描述
在这里插入图片描述

1.4 global语句

  • 如果需要在一个函数内修改全局变量,就使用global 语句。
  • 如果想在一个函数中修改全局变量中存储的值,就必须对该变量使用global语句。
def spam():
	global eggs
	eggs = 'spam'

eggs = 'global' #定义全局变量eggs
spam()
print(eggs)

输出:spam

因为eggs 在spam()的顶部被声明为global,所以当eggs 被赋值为’spam’时,赋值发生在全局作用域的spam 上。

def spam():
	eggs = 'spam'

eggs = 'global' #定义全局变量eggs
spam()
print(eggs)

输出:global

区分一个变量是处于局部作用域还是全局作用域:

  1. 如果变量在全局作用域中使用(即在所有函数之外),它就总是全局变量。
  2. 如果在一个函数中,有针对该变量的global 语句,它就是全局变量。否则,如果该变量用于函数中的赋值语句,它就是局部变量。
  3. 但是,如果该变量没有用在赋值语句中,它就是全局变量。

在这里插入图片描述

1.5 异常处理、错误总结 ⭐

异常对象未被处理(或捕获)时,程序将终止并显示一条错误消息(traceback)
但事实上,每个异常都是某个类的实例
那些可能出错的语句被放在try 子句中。如果错误发生,程序执行就转到接下来的except 子句开始处。

  • ZeroDivisionError错误
def spam(divideBy):
	return 42 / divideBy
	
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))

输出:

21.0
3.5
Traceback (most recent call last):
File "C:/zeroDivide.py", line 6, in <module>
print(spam(0))
File "C:/zeroDivide.py", line 2, in spam
return 42 / divideBy
ZeroDivisionError: division by zero

加入try except语句进行错误处理:

def spam(divideBy):
	try:
		return 42 / divideBy
	except ZeroDivisionError:
		print('Error: Invalid argument.')

print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))

输出:

21.0
3.5
Error: Invalid argument.
None
42.0

如果在try 子句中的代码导致一个错误,程序执行就立即转到except 子句的代码。在运行那些代码之后,执行照常继续

try/except 是顺序执行不会发生回溯
即若try包含的代码块中某一句发生错误转而执行except中的错误处理,则不会返回try中执行错误语句的下一句

  • 示例
def spam(divideBy):
	return 42 / divideBy
	
try:
	print(spam(2))
	print(spam(12))
	print(spam(0))
	print(spam(1))
except ZeroDivisionError:
	print('Error: Invalid argument.')

输出:

21.0
3.5
Error: Invalid argument.

print(spam(1))从未被执行是因为,一旦执行跳到except 子句的代码,就不会回到try 子句。它会继续照常向下执行。

  • ValueError错误

正常情况下,int()函数在传入一个非整数字符串时,会产生ValueError 错误,
比如int(‘puppy’)。在except 子句中,向用户输出一条信息,告诉他们必须输入一个
整数。

>>> int(input())
cdc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'cdc'
  • IndexError错误

下标超出了列表中值的个数(不仅限于列表)

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[10000]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
spam[10000]
IndexError: list index out of range
  • AttributeError错误

对应方法只能在对应数据类型上调用
append()和insert()方法是列表方法,只能在列表上调
用,不能在其他值上调用,例如字符串和整型。

>>> eggs = 'hello'
>>> eggs.append('world')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
eggs.append('world')
AttributeError: 'str' object has no attribute 'append'

>>> bacon = 42
>>> bacon.insert(1, 'world')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
bacon.insert(1, 'world')
AttributeError: 'int' object has no attribute 'insert'
  • 一些内置的异常类
    在这里插入图片描述
  • 不提供参数

捕获异常后,如果要重新引发它(即继续向上传播),可调用raise且不提供任何参数(也可显式地提供捕获到的异常)
在程序内部使用时,引发异常是更佳的选择(此时应关闭“抑制”功能)。

class MuffledCalculator:
	muffled = False
	def calc(self, expr):
		try:
			return eval(expr)
		except ZeroDivisionError:
			if self.muffled:
				print('Division by zero is illegal')
			else:
				raise
>>> calculator = MuffledCalculator()
>>> calculator.calc('10 / 2')
5.0
>>> calculator.calc('10 / 0') # 关闭了抑制功能
Traceback (most recent call last): File "<stdin>", line 1, in ?
File "MuffledCalculator.py", line 6, in calc
return eval(expr)
File "<string>", line 0, in ?
ZeroDivisionError: integer division or modulo by zero
-----------------------------------------------
>>> calculator.muffled = True
>>> calculator.calc('10 / 0')
Division by zero is illegal

关闭抑制功能时,捕获了异常ZeroDivisionError但继续向上传播它。(虚线上半部分代码)

如果无法处理异常,在except子句中使用不带参数的raise通常是不错的选择,但有时你可能想引发别的异常。在这种情况下,导致进入except子句的异常将被作为异常上下文存储起来,并出现在最终的错误消息中,如下所示:

>>> try:
...     1/0
... except ZeroDivisionError:
...     raise ValueError
...

输出:
在这里插入图片描述

注意到异常处理并不会导致代码混乱,而添加大量的if语句来检查各种可能的错误状态将导致代码的可读性极差。

  • 使用元组进行异常捕获 --一个except字句捕获多种异常
try:
	x = int(input('Enter the first number: '))
	y = int(input('Enter the second number: '))
	print(x / y)
except (ZeroDivisionError, TypeError, NameError):
	print('Your numbers were bogus ...')
  • try - except - else
while True:
	try:
		x = int(input('Enter the first number: '))
		y = int(input('Enter the second number: '))
		value = x / y
		print('x / y is', value)
	except:
		print('Invalid input. Please try again.')
	else:
		break

在这里,仅当没有引发异常时,才会跳出循环(这是由else子句中的break语句实现的)

  • 使用except Exception as e
while True:
	try:
		x = int(input('Enter the first number: '))
		y = int(input('Enter the second number: '))
		value = x / y
		print('x / y is', value)
	except Exception as e:
		print('Invalid input:', e)
		print('Please try again')
	else:
		break
Enter the first number: 1
Enter the second number: 0
Invalid input: integer division or modulo by zero
Please try again

Enter the first number: 'x' Enter the second number: 'y'
Invalid input: unsupported operand type(s) for /: 'str' and 'str'
Please try again

Enter the first number: quuux
Invalid input: name 'quuux' is not defined
Please try again

Enter the first number: 10
Enter the second number: 2
x / y is 5
  • finally 用于异常发生时的清理工作

  • 检查对象是否包含特定的属性时,try/except也很有用

# 同一个问题 两种不同的解决方法

# 方案一
def describe_person(person):
	print('Description of', person['name'])
	print('Age:', person['age'])
	if 'occupation' in person:
		print('Occupation:', person['occupation'])
	
# 方案二
def describe_person(person):
	print('Description of', person['name'])
	print('Age:', person['age'])
	try:
		print('Occupation:', person['occupation'])
	except KeyError: pass
'''
在这里,函数直接假设存在'occupation'键。如果这种假设正确,就能省点事:直接获取并
打印值,而无需检查这个键是否存在。如果这个键不存在,将引发KeyError异常,而except子句
将捕获这个异常
'''

检查对象是否包含特定的属性时,try/except也很有用

# 假设你要检查一个对象是否包含属性write,可使用类似于下面的代码:
try:
	obj.write
except AttributeError:
	print('The object is not writeable')
else:
	print('The object is writeable')

二、列表

  • 基础概念

术语:“列表值”指的是列表本身(它作为一个值,可以保存在变量中,或传递给函数,像所有其他值一样)
列表中的值也称为“表项”(列表可以包含多个同样的项
列表中的值是可以改变的,元组和字符串是不可变的,不能被修改

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
'''
spam 变量仍然只被赋予一个值:列表值。但列表值本身包含多个值。
[]是一个空列表,不包含任何值,类似于空字符串’’。
'''

2.1 负数下标

下标从0 开始并向上增长,但也可以用负整数作为下标。整数值−1 指的是列表中的最后一个下标−2 指的是列表中倒数第二个下标,以此类推。

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.'

2.2 ⭐切片

下标可以从列表中取得单个值一样,“切片”可以从列表中取得多个值结果是一个新列表.
一个切片中,第一个整数切片开始处的下标。第二个整数切片结束处的下标。切片向上增长,直至第二个下标的值,但不包括它

spam = ['cat', 'bat', 'rat', 'elephant']

spam[2]是一个值:‘rat’
spam[1:4]是一个列表:[‘bat’, ‘rat’, ‘elephant’]
spam[0:-1]是一个列表:[‘cat’, ‘bat’, ‘rat’](-1代表最后,但不包括

  • 高级用法

省略切片中冒号两边的一个下标或两个下标:

  • 省略第一个下标相当于使用0,或列表的开始。
  • 省略第二个下标相当于使用列表的长度,意味着分片直至列表的末尾。
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]  # 不包括下标为2位置的元素
['cat', 'bat']
>>> spam[1:] 
['bat', 'rat', 'elephant']
>>> spam[:]  # 所有元素
['cat', 'bat', 'rat', 'elephant']

2.3 列表的连接与复制

+操作符可以连接两个列表,得到一个新列表
*操作符可以用于一个列表和一个整数,实现列表的复制。
+=操作符也可以完成字符串和列表的连接
*=操作符可以完成字符串和列表的
复制。

# +操作符  *操作符
>>> [1, 2, 3] + ['A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胜天半月子

打不打商的无所谓,能帮到你就好

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值