zoukankan      html  css  js  c++  java
  • python入门-异常

    1 报错的例子

    print(5/0)

    2跳过报错的例子

    try:
        print(5/0)
    except ZeroDivisionError:
        print("You can't divide by zero")
    print("Give me two numbers , and I'll divide them.")
    print("Eneter 'q' to quit.")
    while True:
        first_number = input("
    First number")
        if first_number  == 'q':
            break
        second_number = input("Second number")
        if second_number == 'q':
            break
        try:
            answer = int(first_number) / int(second_number)
        except ZeroDivisionError:
            print("You can't divide by 0!")
        else:
            print(answer)

    3 文件不存在的异常

    filename = '55.txt'
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        msg = "sorry,the file " + filename + "does not exist."
        print(msg)
    else:
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + "has about" + str(num_words) + "words")

    4 跳过的异常的函数

    def count_words(filename):
        """计算一个文件包含多少个单词"""
        try:
            with open(filename) as f_obj:
                contents = f_obj.read()
        except FileNotFoundError:
            pass
        else:
            words = contents.split()
            num_words = len(words)
            print("The file " + filename + "has about" + str(num_words) + "words")
  • 相关阅读:
    Python的七大数据类型整理
    Linux下获取线程ID tid的方法
    字符串逆序操作
    ftp的两种模式
    exec函数族
    代码行数统计(指定目录下所有文件的Line)
    windows 命令行操作
    C语言时间打印
    Anaconda下载安装说明
    python 使用request进行get post请求
  • 原文地址:https://www.cnblogs.com/baker95935/p/9437884.html
Copyright © 2011-2022 走看看