Python 测试题(覆盖了大多数的基础知识和进阶)

如果有不一样的答案 可以评论 答案不唯一
好的答案我会写到文章里面

1.变量如何定义?(5分)

定义int, float, complex, tuple, list, dict类型变量
输出变量的值,以及类型
int=1
float=1.1
complex={1,2,3,4}
tuple=(1,2,3,4)
list=[1,2]
dict={1:2,3:4}
print(int,type(int))
print(float,type(float))
print(complex,type(complex))
print(tuple,type(tuple))
print(list,type(list))
print(dict,type(dict))

结果

1 <class 'int'>
1.1 <class 'float'>
{1, 2, 3, 4} <class 'set'>
(1, 2, 3, 4) <class 'tuple'>
[1, 2] <class 'list'>
{1: 2, 3: 4} <class 'dict'>

2.list, dict的使用(10分)

list的使用
ori_list = [1, 2, 3]
append: 使用append为列表增加1个元素4
输出增加元素之后的列表
extend: 给定列表[8, 7, 6],将ori_list和给定的列表进行合并
输出合并后的列表
sort: 将合并后的列表进行排序: 并输出排序后的列表
reverse:将排序后的列表倒序并输出
dict的使用:
ori_dict = {“张三”: 18, “李四”: 40, “王五”: 34}
keys: 获取ori_dict中所有元素的key, 并输出
values: 获取ori_dict中所有元素的value 并输出
items: 获取ori_dict中所有的元素 并输出
增加元素: 给ori_dict增加元素: “赵六”: 20
,输出增加元素后的字典
update: 给定{“孙悟空”: 500, “猪八戒”: 200},
将ori_dict和跟定字典合并,并输出合并的结果

ori_list = [1, 2, 3]
ori_list.append(4)
print(ori_list)
ori_list1=[8, 7, 6]
ori_list.extend(ori_list1)
print(ori_list)
ori_list.sort()
print(ori_list)
ori_list.reverse()
print(ori_list)
ori_dict = {"张三": 18, "李四": 40, "王五": 34}
print(ori_dict.keys())
print(ori_dict.values())
print(ori_dict.items())
ori_dict["赵六"]=20
print(ori_dict)
ori_dict1 ={"孙悟空": 500, "猪八戒": 200}
ori_dict.update(ori_dict1)
print(ori_dict)

结果

[1, 2, 3, 4]
[1, 2, 3, 4, 8, 7, 6]
[1, 2, 3, 4, 6, 7, 8]
[8, 7, 6, 4, 3, 2, 1]
dict_keys(['张三', '李四', '王五'])
dict_values([18, 40, 34])
dict_items([('张三', 18), ('李四', 40), ('王五', 34)])
{'张三': 18, '李四': 40, '王五': 34, '赵六': 20}
{'张三': 18, '李四': 40, '王五': 34, '赵六': 20, '孙悟空': 500, '猪八戒': 200}

3.if-else: 定义一个成绩列表[50,75, 86,81] (5分)

       ->输出对应等级列表[A, B, C, A]

[85,100] ->等级A
[60, 85) ->等级B
[0, 60) ->等级C

l=[50,75,86,81]
def CJ(i):
 if i>=85:
     return 'A'
 elif i>=60:
     return 'B'
 else:
     return 'C'
for i in range(0, len(l)):
 l[i]=CJ(l[i])
print(l)

结果

['C', 'B', 'A', 'B']

4. for循环: (10分)

1)构建一个1-10的列表 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2)9*9:乘法表(for循环,while循环两种实现)
1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81

for i in range(1,10):
    for j in range(1, i+1):
        print(i,'*',j,'=',i*j,end="  ")
    print()

结果

1 * 1 = 1  
2 * 1 = 2  2 * 2 = 4  
3 * 1 = 3  3 * 2 = 6  3 * 3 = 9  
4 * 1 = 4  4 * 2 = 8  4 * 3 = 12  4 * 4 = 16  
5 * 1 = 5  5 * 2 = 10  5 * 3 = 15  5 * 4 = 20  5 * 5 = 25  
6 * 1 = 6  6 * 2 = 12  6 * 3 = 18  6 * 4 = 24  6 * 5 = 30  6 * 6 = 36  
7 * 1 = 7  7 * 2 = 14  7 * 3 = 21  7 * 4 = 28  7 * 5 = 35  7 * 6 = 42  7 * 7 = 49  
8 * 1 = 8  8 * 2 = 16  8 * 3 = 24  8 * 4 = 32  8 * 5 = 40  8 * 6 = 48  8 * 7 = 56  8 * 8 = 64  
9 * 1 = 9  9 * 2 = 18  9 * 3 = 27  9 * 4 = 36  9 * 5 = 45  9 * 6 = 54  9 * 7 = 63  9 * 8 = 72  9 * 9 = 81  

5. 异常处理: 处理1 / 0的异常, 处理 “123” + 4的异常(5分)

try:
    i = 1 / 0
except ZeroDivisionError:
    print('异常1')
try:
    j = "123" + 4
except TypeError:
    print('异常2')

结果

异常1
异常2

6. 读写文件: (10分)

写文本文件: 在zhujiang.txt中写入 华南农业大学珠江学院-你的姓名-学号
读取文件:读取zhujiang.txt中的内容,并输出
拿到一张照片 1.jpg,然后用二进制进行读写:对图片进行复制 2.jpg

f = open("zhujiang.txt", "w+", encoding="Utf-8")
f.write("华南农业大学珠江学院-你的姓名-学号")
f.close()
f1 = open("zhujiang.txt", "r+", encoding="Utf-8")
print(f1.read())
f2 = open("1.png", "rb")
F1=f2.read()
f3=open("2.png","wb")
f3.write(F1)

结果

华南农业大学珠江学院-你的姓名-学号

在这里插入图片描述

7. 字符串格式化: 定义列表(5分)

[{"姓名": "张三", "年龄": 18, "性别": "男"}, {"姓名": "里斯李四李斯", "年龄": 18, "性别": "男"}, {"姓名": "斯托夫斯基-玲", "年龄": 18, "性别": "女"}]	
格式化输出: 列表中的元素:每个元素一行
			 姓名(宽度12) 年龄(宽度6)   性别(4)
    左对齐   张三         18            男	
    右对齐      
    居中
list=  [{"姓名": "张三", "年龄": 18, "性别": "男"}, {"姓名": "里斯李四李斯", "年龄": 18, "性别": "男"}, {"姓名": "斯托夫斯基-玲", "年龄": 18, "性别": "女"}]
print(f"{list[0].get('姓名'):<16},{list[0].get('年龄'):5},{list[0].get('性别')}")
print(f"{list[1].get('姓名'):<16},{list[1].get('年龄'):5},{list[1].get('性别')}")
print(f"{list[2].get('姓名'):<16},{list[2].get('年龄'):5},{list[2].get('性别')}")

结果

张三              ,   18,男
里斯李四李斯          ,   18,男
斯托夫斯基-玲         ,   18,女

8. lambda表达式: 定义一个lambda表达式: 获取字符串中的第二个字符(5分)

s='SDSDS'
n=lambda x:x[1]
print(n(s))

结果

D

9. 定义一个Book类:(20分)

    定义类属性: count
    定义对象属性或变量: title(书名), author(作者), publish(出版社), price(价格)
    定义对象相加操作: book1 + book2 = book1.title + book2.title
	            举例: book1 + book2 = Java程序设计Python程序设计
    定义打印对象的输出: 使用print打印 book1 => 书的名字-作者-出版社-价格
               举例: print(book1) => Python程序设计-吉米勒-机械出版社-35	
    定义调用对象的方法:__call__(): 并让其返回书的名字
	定义静态方法: static_print_obj: 执行输出print("This is Static Method of class Book")
	定义类方法: class_print_obj: 执行输出print("This is class Method of class Book ")
    定义获取title的的getter和setter方法:(使用python自带装饰器, property, xxx.setter)
按要求执行底下的操作:   
实例化对象book1: Python程序设计, 王铮, 机械教育出版社, 22
实例化对象book2:  Java程序设计, 李刚, 清华大学出版社, 34
    执行book1 + book2: 并输出相加的结果
    执行print(book1)
    执行 book1()
    调用类变量,进行复制100, 输出类变量
    调用book1对象,并修改书名: Python程序设计修改为流畅的Python
    调用静态方法 static_print_obj
    调用类方法 class_print_obj
    调用setter对属性title进行赋值,调用getter方法获取赋值后的结果并输出
class count:
    def __init__(self,title,author,publish,price):
        self.title=title
        self.author=author
        self.public=publish
        self.price=price

    def __add__(self, other):
        return self.title+self.title
    def __str__(self):
        return '书的名字:%s 作者:%s 出版社:%s 价格:%s'%(self.title,self.author,self.public,self.price)
    def call(self):
        return self.title
    def  static_print_obj(self):
        print("This is Static Method of class Book")

    def class_print_obj():
        print("This is class Method of class Book ")
    def gattitle(self):
        return  self.title
    def settitle(self,title):
        self.title=title
book1=count('Python程序设计',' 王铮', '机械教育出版社', 22)
book2=count('Java程序设计', '李刚', '清华大学出版社', 34)
print(book1+book2)
print(book1)
print(book1.call())
print(book1.gattitle())
book1.settitle("Python程序设计修改为流畅的Python")
book1.static_print_obj()
count.class_print_obj()
book1.settitle("123")
print(book1.gattitle())

结果

Python程序设计Python程序设计
书的名字:Python程序设计 作者: 王铮 出版社:机械教育出版社 价格:22
Python程序设计
Python程序设计
This is Static Method of class Book
This is class Method of class Book 
123

10. 继承:(5分)

父类: Transport: 对象属性有: name, solution
包含一个方法:
transfer(): 执行print(f"Our Transport is {self.solution} by{self.name}")
子类: 定义子类Plane: 空类
定义子类Truck: 空类
定义子类Ship: 空类
执行: 实例化Plane, 初始化name, solution => 飞机, 空运
实例化Truck, 初始化name, solution => 卡车, 路运
实例化Ship, 初始化name, solution => 轮船, 海运
调用plane.transfer()
调用truck.transfer()
调用ship.transfer()

下面这个是肖同学写的代码

class Transport:
    def __init__(self, name, solution):
        self.name = name
        self.solution = solution

    def transfer(self):
        print(f"Our Transport is {self.solution} by{self.name}")


class Plane(Transport):
    pass


class Truck(Transport):
    pass

11. 闭包:(10分)

     利用闭包实现一个求平均值的函数:
	     功能: avg(10) -> 10
		       avg(11) -> 10.5
			   avg(15) -> 12
			   avg(16) -> 13

下面这个也是肖同学写的代码

def average():
    nums = []

    def avg_arithmetic(num):
        nums.append(num)
        s = sum(nums)
        print(s / len(nums))

    return avg_arithmetic


avg = average()
avg(10)
avg(11)
avg(15)
avg(16)

结果


10.0
10.5
12.0
13.0

12. 定义一个装饰器: 功能是用来查看执行被装饰函数前后的时间(5分)

from time import time
def decorate(text):
    def innter():
        start = time()
        text()
        print('time costing:', time() - start)
    return innter
@decorate
def fund():
    print("阿吧")

fund()

结果

阿吧
time costing: 0.0

13. 定义一个迭代器: iter, next(10分)

        初始化传入两个列表: 
		          列表1: ["red", "black", "green"]
				  列表2:  ["S", "M", "L"]
		使用循环去访问时:
		          输出结果:
				  (red, S)
				  (red, M)
				  (red, L)
				  ........
				  (green, L)
class DDQ:
    i = 0
    J = 0
    def __init__(self,S,N):
        self.S=S
        self.N=N

    def __iter__(self):
        return self
    def __next__(self):
        self.J = self.J + 1
        if self.J == 4:
            self.J=1
            self.i = self.i + 1
        if self.i!=3:
            return self.S[self.i],self.N[self.J-1]
        else:
            raise StopIteration
for i,J in DDQ( ["red", "black", "green"],["S", "M", "L"]):
    print(i,J)

结果

red S
red M
red L
black S
black M
black L
green S
green M
green L

14. 定义一个生成器函数:(10分)

        传入两个列表:
			列表1: ["red", "black", "green"]
			列表2:  ["S", "M", "L"]
		1.调用next返回结果: 调用9次next()
		    输出结果:
				  (red, S)
				  (red, M)
				  (red, L)
				  ........
				  (green, L)
		2.使用循环去访问生成器:
			输出结果:
				  (red, S)
				  (red, M)
				  (red, L)
				  ........
				  (green, L)
			注意循环终止的条件

下面这个还是肖同学写的代码

def func1(list1, list2):
    for i in list1:
        for j in list2:
            yield i, j


list1 = ["red", "black", "green"]
list2 = ["S", "M", "L"]
clothe1 = func1(list1, list2)
print(next(clothe1))
print(next(clothe1))
print(next(clothe1))
print(next(clothe1))
print(next(clothe1))
print(next(clothe1))
print(next(clothe1))
print(next(clothe1))
print(next(clothe1))
print("=" * 80)

def func(list1, list2):
    for i in list1:
        for j in list2:
            yield i, j

clothe2 = func(list1, list2)
for i in list1:
    for j in list2:
        value = next(clothe2)
        print(value)

结果

('red', 'S')
('red', 'M')
('red', 'L')
('black', 'S')
('black', 'M')
('black', 'L')
('green', 'S')
('green', 'M')
('green', 'L')
================================================================================
('red', 'S')
('red', 'M')
('red', 'L')
('black', 'S')
('black', 'M')
('black', 'L')
('green', 'S')
('green', 'M')
('green', 'L')

15. 正则表达式匹配学号:11位学号,匹配所有计科1802的学生(5分)

计科18的学号为 04101802001 - 04101802043

暂无 蹲一个同学写


结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

zzsaixuexi

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值