Discuss / Python / 答案

答案

Topic source
def get_score_in(low, high):
    """ 返回指定分数区间的名字,按分数从低到高排序 """
    if low > high:
        print('错误的分数段, high 必须高于 low')
        return

    if low < 0:
        print('错误的分数段, low 必须高于 0 ')
        return

    if high > 100:
        print('错误的分数段, high 必须小于 100')
        return

    try:
        conn = sqlite3.connect(db_file)
        cursor = conn.cursor()
        cursor.execute('select * from USER WHERE score BETWEEN ? and ?', (low, high))
        values = cursor.fetchall()
        print('查询结果为: ', values)
        cursor.close()
        conn.close()
    except Exception as e:
        print('数据库出错了: [%s]' % e)
        cursor.close()
        conn.close()
    finally:
        print('get_score_in  END.....')

get_score_in(-5, 88)
get_score_in(95, 88)
get_score_in(56, 199)
get_score_in(70, 99)

输出

错误的分数段, low 必须高于 0 错误的分数段, high 必须高于 low 错误的分数段, high 必须小于 100 查询结果为: [('A-001', 'Adam', 95), ('A-003', 'Lisa', 78)] get_score_in END.....

上面写错了,没注意到下面要求返回的是名字,重新贴下

def get_score_in(low, high):
    """ 返回指定分数区间的名字,按分数从低到高排序 """
    if low > high:
        print('错误的分数段, high 必须高于 low')
        return

    if low < 0:
        print('错误的分数段, low 必须高于 0 ')
        return

    if high > 100:
        print('错误的分数段, high 必须小于 100')
        return

    try:
        conn1 = sqlite3.connect(db_file)
        cursor1 = conn1.cursor()
        cursor1.execute('select name from USER WHERE score BETWEEN ? and ? ORDER BY name', (low, high))
        values = cursor1.fetchall()
        r_list = []
        for v in values:
            r_list.append(v[0])
        cursor1.close()
        conn1.close()
        print('low[%s] high[%s] r_list is [%s]' % (low, high, r_list))
        return r_list
    except Exception as e:
        print('数据库出错了: [%s]' % e)
        cursor1.close()
        conn1.close()

晕,finally被删了,正常打开的情况下,没关闭


  • 1

Reply