# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:命令行参数解析计算正方形周长、面积
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--length', default = 10, type = float, help = '正方形边长')
args = parser.parse_args()
area = args.length * args.length
girth = 4 * args.length
print('面积 = ',area, '周长 = ', girth)
测试结果:
PS D:\CodeProject\PyCharm\work1\lab6> python 6-1.py --length 3.2
面积 = 10.240000000000002 周长 = 12.8
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:命令行参数确认文件,读取并输出
import sys
filename = sys.argv[1]
f = open(filename, 'r', encoding = 'utf-8')
line_no = 0
while True:
line_no += 1
line = f.readline()
if line:
print(line_no, ":", line)
else:
break
f.close()
测试结果:
PS D:\CodeProject\PyCharm\work1\lab6> python 6-1.py C:\\Users\\JohnRothan\\Desktop\\test.txt
1 : Hello,World!
2 : Today is Friday.
3 : Let's do amazing things!
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:命令行参数确认文件,with语句读取并输出
import sys
filename = sys.argv[1]
line_no = 0
with open(filename, 'r', encoding = 'utf-8') as f:
for line in f:
line_no += 1
print(line_no, ":", line)
f.close()
测试结果:
PS D:\CodeProject\PyCharm\work1\lab6> python 6-1.py C:\\Users\\JohnRothan\\Desktop\\test.txt
1 : Hello,World!
2 : Today is Friday.
3 : Let's do amazing things!
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:利用with语句读取并输出文本文件,由命令行确认文件名
import sys
n = int(sys.argv[1])
power = 1
i = 0
f = open('D:\\CodeProject\\flex\\log.txt', 'w')
sys.stdout = f
while i <= n:
double = i * 2
print(str(i), '', str(double), '', str(power))
power = 2 * power
i = i + 1
sys.stdout = sys.__stdout__
print('done!')
测试结果:
0 0 1
1 2 2
2 4 4
3 6 8
4 8 16
5 10 32
#7.7 上机实践-错误和异常
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:语法错误
print("Good Luck!"
print("幸运数:",random.choice(range(10)))
测试结果:
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 6
print("幸运数:",random.choice(range(10)))
^
SyntaxError: invalid syntax
错误处理:
print("Good Luck!")
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:运行时错误
print("Good Luck!")
print("幸运数:",random.choice(range(10)))
测试结果:
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 6, in <module>
print("幸运数:",random.choice(range(10)))
NameError: name 'random' is not defined
错误处理:
import random
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:零除错误
a = 1
b = 0
c = a / b
测试结果:
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 7, in <module>
c = a / b
ZeroDivisionError: division by zero
错误处理:
除数不能为0
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:逻辑错误
import math
a = 1; b = 2; c = 1
x1 = -b + math.sqrt(b*b - 4*a*c) / 2 * a
x2 = -b - math.sqrt(b*b - 4*a*c) / 2 * a
print(x1,x2)
测试结果:
-2.0 -2.0
错误处理:
一元二次方程计算公式错误,应修改为:
x1 = (-b + math.sqrt(b*b - 4*a*c)) / (2 * a)
x2 = (-b - math.sqrt(b*b - 4*a*c)) / (2 * a)
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:常见异常
noname
测试结果:变量未声明
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 5, in <module>
noname
NameError: name 'noname' is not defined
int a
测试结果:语法错误
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 5
int a
^
SyntaxError: invalid syntax
a = 1
a.show()
测试结果:show()函数未定义
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 6, in <module>
a.show()
AttributeError: 'int' object has no attribute 'show'
11 + 'abc'
测试结果:类型错误
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 5, in <module>
11 + 'abc'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
int('abc')
测试结果:数值错误
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 5, in <module>
int('abc')
ValueError: invalid literal for int() with base 10: 'abc'
1 / 0
测试结果:零除错误
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 5, in <module>
1 / 0
ZeroDivisionError: division by zero
a = [10,11,12]
a[3]
测试结果:索引越界
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 6, in <module>
a[3]
IndexError: list index out of range
m = {'1' : 'yes', '2' : 'no'}
m['3']
测试结果:字典关键字不存在
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 6, in <module>
m['3']
KeyError: '3'
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:引发异常
a = input()
if a < 0: raise ValueError("不能为负!")
测试结果:
-2
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 5, in <module>
if a < 0: raise ValueError("不能为负!")
TypeError: '<' not supported between instances of 'str' and 'int'
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:try-except-else-finally处理捕获异常
try:
f = open("test.txt", 'w')
f.write("测试文件")
f1 = open('test1.txt', 'r')
except IOError:
print("没有找到文件")
else:
print("写入成功")
finally:
f.close()
测试结果:
没有找到文件
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:处理异常
try:
f = open('mytxt.txt', 'w')
while True:
s = input("请输入字符串(Q键结束):")
if s.upper() == 'Q' : break
f.write(s + '\n')
except KeyboardInterrupt:
print('程序中断!(Ctrl-C)')
finally:
f.close()
测试结果:
请输入字符串(Q键结束):cava
请输入字符串(Q键结束):dcav
请输入字符串(Q键结束):fe
请输入字符串(Q键结束):4
请输入字符串(Q键结束):Q
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:自定义异常类
class NumberError(Exception): #自定义异常类,继承于Exception
def __init__(self,data):
Exception.__init__(self, data)
self.data = data
def __str__(self): #重载__str__方法
return self.data + ': 非法数值(< 0)'
def total(data):
total = 0
for i in data:
if i < 0: raise NumberError(str(i))
total += i
return total
#测试代码
data1 = (44, 78, 90, 80, 55)
print('总计=', total(data1))
data2 = (44, 78, 90, -80, 55)
print('总计=', total(data2))
测试结果:
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 21, in <module>
print('总计=', total(data2))
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 14, in total
if i < 0: raise NumberError(str(i))
__main__.NumberError: -80: 非法数值(< 0)
总计= 347
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:断言
a = int(input("请输入整数a:"))
b = int(input("请输入整数b:"))
assert b != 0, '除数不能为0'
c = a / b
print(a, '/', b, '=', c)
测试结果:
请输入整数a:1
请输入整数b:0
Traceback (most recent call last):
File "D:\CodeProject\PyCharm\work1\lab6\6-1.py", line 7, in <module>
assert b != 0, '除数不能为0'
AssertionError: 除数不能为0
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:输出信息跟踪逻辑错误调试:命令行参数分解为素数之积
import sys
n = int(sys.argv[1])
result=[]
factor = 2
while factor*factor <= n:
while (n % factor) == 0:
n //= factor
result.append(factor)
print(n, factor)
factor += 1
if n > 1:
result.append(n)
print(result)
测试结果:
PS D:\CodeProject\PyCharm\work1\lab6> python 6-1.py 1364
682 2
341 2
31 11
[2, 2, 11, 31]
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:默认配置直接输出
import logging
logging.debug("调试信息") #不会输出
logging.info("一般信息")
logging.warning("警告信息")
logging.error("错误信息")
logging.critical("严重错误")
测试结果:
WARNING:root:警告信息
ERROR:root:错误信息
CRITICAL:root:严重错误
# 作者:JohnRothan
# 时间:2022-4-22
# 题目信息:basicConfig配置输出日志到控制台
import logging
#配置logging
logging.basicConfig(level = logging.INFO
,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#输出日志信息
logging.debug("调试信息") #不会输出
logging.info("一般信息")
logging.warning("警告信息")
logging.error("错误信息")
logging.critical("严重错误")
测试结果:
2022-04-22 10:16:14,345 - root - INFO - 一般信息
2022-04-22 10:16:14,345 - root - WARNING - 警告信息
2022-04-22 10:16:14,345 - root - ERROR - 错误信息
2022-04-22 10:16:14,345 - root - CRITICAL - 严重错误
# 作者:JohnRothan
# 时间:2022-4-21
# 题目信息:basicConfig配置输出日志到文件和控制台
import logging
#配置logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)
handler = logging.FileHandler("logging_console_file.txt")
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
logger.addHandler(handler)
logger.addHandler(console)
#输出日志信息
logger.debug("调试信息")
logger.info("一般信息")
logger.warning("警告信息")
logger.error("错误信息")
logger.critical("严重错误")
测试结果:
控制台:
错误信息
严重错误
文件:
2022-04-22 10:18:41,783 - __main__ - DEBUG - 调试信息
2022-04-22 10:18:41,783 - __main__ - INFO - 一般信息
2022-04-22 10:18:41,783 - __main__ - WARNING - 警告信息
2022-04-22 10:18:41,783 - __main__ - ERROR - 错误信息
2022-04-22 10:18:41,783 - __main__ - CRITICAL - 严重错误