Python基础学习_练习(文件和异常)- 异常

1-6 加法运算

first_number = input("Please enter first number: ")
secound_number = input("Please enter secound number: ")

try:
    result = int(first_number) + int(secound_number)
    print(result)
except ValueError:
    print("Your input number is not number!")

结果:

## 正确执行结果
Please enter first number: 1

Please enter secound number: 2
3
## 异常引发结果

Please enter first number: hmj

Please enter secound number: j
Your input number is not number!

10-7 加法计算器(加上while循环)

flag = True

while flag:
       first_number = input("Please enter first number: ")
       secound_number = input("Please enter secound number: ")

       try:
           result = int(first_number) + int(secound_number)
           print(result)
       except ValueError:
           print("Your input number is not number!")
           flag = False

结果:

Please enter first number: 5

Please enter secound number: 6
11

Please enter first number: 7

Please enter secound number: 88
95

Please enter first number: 6

Please enter secound number: 25
31

Please enter first number: fw

Please enter secound number: fefw
Your input number is not number!

可以看到在无异常情况下,程序能够一直运行,直到异常抛出,结束循环

10-8 猫和狗

another_names = "anothernames.txt"

def display_info(filename):
    """打开文件并显示信息"""
    try:
        with open(filename) as ob_name:
            lines = ob_name.readlines()
            with open(another_names,'w') as obj_names:
                obj_names.writelines(lines)
                print("The " + filename  + " is writing " + " in the " + another_names + ".")
        for line in lines:
            print("This " + filename + " name is " + line.strip())
    except FileNotFoundError:
        print("The " + filename + " is not exist." )
    


filenames = ['cats.txt','dogs.txt','birds.txt']
for filename in filenames:
    display_info(filename)
    print("\n")

结果:


The cats.txt is writing  in the anothernames.txt.
This cats.txt name is 小花
This cats.txt name is 小红
This cats.txt name is 小灰
This cats.txt name is 灰太狼


The dogs.txt is writing  in the anothernames.txt.
This dogs.txt name is 小小
This dogs.txt name is 明明
This dogs.txt name is 乐乐
This dogs.txt name is 洋洋


The birds.txt is not exist.

所需文件如下

dogs.txt

小小
明明
乐乐
洋洋

cats.txt

小花
小红
小灰
灰太狼

birds.txt文件不存在,我们这里是用来测试程序能否抛出异常

10-9 沉默的猫和狗,即文件不存在直接跳过(pass)

another_names = "anothernames.txt"

def display_info(filename):
    """打开文件并显示信息"""
    try:
        with open(filename) as ob_name:
            lines = ob_name.readlines()
            with open(another_names,'w') as obj_names:
                obj_names.writelines(lines)
        for line in lines:
            print("This " + filename + " name is " + line.strip())
    except FileNotFoundError:
        pass
        #print("The " + filename + " is not exist." )
    
filenames = ['cats.txt','dogs.txt','birds.txt']
for filename in filenames:
    display_info(filename)
    print("\n")

结果:

This cats.txt name is 小花
This cats.txt name is 小红
This cats.txt name is 小灰
This cats.txt name is 灰太狼


This dogs.txt name is 小小
This dogs.txt name is 明明
This dogs.txt name is 乐乐
This dogs.txt name is 洋洋

10-10 常见单词

统计文本中的’the’出现的次数

filename = 'E:/python学习/python基础学习/纽伦堡军事法庭对战犯的审判受到控制.txt'

try:
    with open(filename,encoding='gb18030', errors='ignore') as obj_file :
        lines = obj_file.read()
        the_numbers = lines.lower().count('the')
        
except TypeError:
        pass
else:
    print("The number of 'the' is  " +  str(the_numbers) + " in the " + filename)

结果:

The number of 'the' is  52096 in the E:/python学习/python基础学习/纽伦堡军事法庭对战犯的审判受到控制.txt

备注:纽伦堡军事法庭对战犯的审判受到控制.txt文件可以到https://www.gutenberg.org 网站免费下载

TypeError: can only concatenate str (not “int”) to str

错误原因:使用+连接时,只能将字符串与字符串连接,不能和int型连接。

需要将x强制转换成str型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值