计算机二级Python编程题记录(中)

简介: 计算机二级Python编程题记录

第六章


1




line = "After fresh rain in mountains bare "
print(line.title())


2




a = float(input("输入三角形第一条直角边长:"))
b = float(input("输入三角形第二条直角边长:"))
area = a*b*0.5
print("直角三角形的面积为:{:.1f}".format(area))


3



num = eval(input("输入数字:"))
print("对应的二进制数:{0:b}\n八进制数:{0:o}\n十六进制数:{0:X}".format(num))


4




import turtle
turtle.color('black','yellow')
turtle.begin_fill()
turtle.circle(50)
turtle.end_fill()


5




def judge_year(year):
    if (year%4==0 and year%100!=0) or year%400==0:
        print(year,"年是闰年")
    else:
        print(year, "年不是闰年")
year = eval(input("请输入年份:"))
judge_year(year)


6



fi = open("score.csv", "r")
fo = open("avg-score.txt", "w")
ls = []
x = []
sum = 0
for row in fi:
    ls.append(row.strip("\n").split(","))
for line in ls[1:]:
    for i in line[1:]:
        sum = int(i) + sum
        avg = sum / 3
    x.append(avg)
    sum = 0
fo.write("语文:{:.2f}\n数学:{:.2f}\n英语:{:.2f}\n物理:{:.2f}\n科学:{:.2f}".format(x[0], x[1], x[2], x[3], x[4]))
fi.close()
fo.close()


第七套


1




lis = [2,8,3,6,5,3,8]
new_lis = list(set(lis))
print(new_lis)


2




fruit = input('输入水果:')
lis = ['苹果','哈密瓜','橘子','猕猴桃','杨梅','西瓜']
if fruit in lis:
    print(fruit+"在列表lis中")
else:
    print(fruit+"不在列表lis中")


3




def str_change(str) :
    return str[::-1]
str = input("输入字符串:")
print(str_change(str))


4




import turtle
turtle.color("black","yellow")
turtle.begin_fill()
for i in range(5):
    turtle.fd(200)
    turtle.right(144)
turtle.end_fill()


5




lower = int(input('输入区间最小值:'))
upper = int(input('输入区间最大值:'))
for num in range(lower+1,upper):
    if num>1:
        for i in range(2,num):
            if(num%i)==0:
                break
        else:
            print(num)


6



fo = open("PY301-1.txt","w")
class Horse():
    def __init__(self, category, gender, age):
        self.category = category
        self.gender = gender
        self.age = age
    def get_descriptive(self):
        self.info = "一匹" + self.category + str(self.age) + "岁的" + self.gender + "马"
    def write_speed(self, new_speed):
        self.speed = new_speed
        addr = "在草原上奔跑的速度为"
        fo.write(self.info + "," + addr + str(self.speed) + "km/h。")
horse = Horse("阿拉伯","公",12)
horse.get_descriptive()
horse.write_speed(50)
fo.close()


fo = open("PY301-2.txt","w")
class Horse():
    def __init__(self, category, gender, age):
        self.category = category
        self.gender = gender
        self.age = age
    def get_descriptive(self):
        self.info = "一匹" + self.category + str(self.age) + "岁的" + self.gender + "马"
    def write_speed(self, new_speed):
        self.speed = new_speed
        addr = "在草原上奔跑的速度为"
        fo.write(self.info + "," + addr + str(self.speed) + "km/h。")
class Camel(Horse):
    def __init__(self, category, gender, age):
        super().__init__(category, gender, age)
    def write_speed(self,new_speed):
        self.speed = new_speed
        addr = "在沙漠上奔跑的速度为"
        fo.write(self.info.replace("马","骆驼") + "," + addr + str(self.speed) + "km/h。")
camel = Camel("双峰驼","母",20)
camel.get_descriptive()
camel.write_speed(40)
fo.close()


第八套


1




animals = ['cow', 'duck', 'cat', 'dog']
animals.reverse()   # animals = animals[::-1]
print(animals)


2




word = "   窗前明月光,疑是地上霜。   "
print(word.strip())


3




count = 0
while count < 50:
    count+=1
    if count % 2 == 0:
        continue
    print(count,end=",")


4




import turtle
for i in range(4):
    turtle.seth(90*(i+1))
    turtle.circle(50,90)
    turtle.seth(90*(i-1))
    turtle.circle(50,90)
turtle.hideturtle()


5



import math
try:
    a = eval(input('请输入底数:'))
    b = eval(input('请输入真数:'))
    c = math.log(b, a)
except ValueError:
    if a<=0 and b>0:
        print("底数不能小于等于0")
    elif b<=0 and a>0:
        print("真数不能小于等于0")
    elif a<=0 and b<=0:
        print('真数和低数都不能小于等于0')
except ZeroDivisionError:
    print('底数不能为1')
except NameError:
    print('输入必须为实数')
else:
    print(c)


6



intxt = input("请输入明文:")
for p in intxt:
    if "a" <= p <= "z":
        print(chr(ord("a") + (ord(p) - ord("a") + 3)%26), end="")
    elif "A" <= p <= "Z":
        print(chr(ord("A") + (ord(p) - ord("A") + 3)%26), end="")
    else:
        print(p,end="")


第九套


1




while True:
    s = input("请输入信息:")
    if s=="Y" or s=="y":
        break


2




import calendar
year = int(input("请输入年份:"))
table = calendar.calendar(year)
print(table)


3




s = input("请输入绕口令:")
print(s.replace("兵","将"))


4




5




fo = open("PY202.txt","w")
for i in range(1,10):
    for j in range(1,i+1):
        fo.write("{}*{}={}\t".format(j,i,i*j))
    fo.write("\n")
fo.close()


6



fi = open("关山月.txt","r")
fo = open("关山月-诗歌.txt","w")
for i in fi.read():
    if i == "。":
        fo.write("。\n")
    else:
        fo.write(i)
fi.close()
fo.close()


fi = open("关山月-诗歌.txt","r")
fo = open("关山月-反转.txt","w")
txt = fi.readlines()
txt.reverse()
for line in txt:
    fo.write(line)
fi.close()
fo.close()


第十套


1




data = eval(input("请输入一组数据,以逗号分隔:"))
print(max(data))


2




import jieba
s = "一件事情没有做过,就没有资格对此事发表看法"
ls = jieba.lcut(s)
print(ls)


3




这题不会


import time
t = time.localtime()
print(time.strftime("%Y年%m月%d日%H时%M分%S秒",t))


4




for i in range(0, 4):
    for y in range(0, 4 - i):
        print(" ", end="")
    print("* " * i)
for i in range(0, 4):
    for x in range(0, i):
        print(" ", end="")
    print("* " * (4 - i))


5




from turtle import *
pensize(5)
for i in range(6):
    fd(100)
    right(60)
color("red")
circle(60,steps=6)


6



import random
letter_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g',
               'h', 'i', 'j', 'k', 'l', 'm', 'n',
               'o', 'p', 'q', 'r', 's', 't',
               'u', 'v', 'w', 'x', 'y', 'z']
letter = letter_list[random.randint(0, 25)]
count = 0
while True:
    a = input("请输入猜测的字母:")
    count += 1
    if a not in letter_list:
        print("请重新输入字母:")
    else:
        if count >= 5:
            print("你答错了5次,结束游戏!")
            break
        elif a > letter:
            print("输入的字母在答案之后")
            continue
        elif a < letter:
            print("输入的字母在答案之前")
            continue
        elif a == letter:
            print("恭喜你答对了!共回答了{}次".format(count))
            break


第十一套


1




f = open("poem.txt","r")
result = []
for line in f.readlines():
    line = line.strip("\n")
    if len(line) != 0 and line[0] != "#":
        result.append(line)
result.sort()
for line in result:
    print(line)
f.close()


2




a = []
for i in range(8):
    a.append([])
    for j in range(8):
        a[i].append(0)
for i in range(8):
    a[i][0] = 1
    a[i][i] = 1
for i in range(2,8):
    for j in range(1,i):
        a[i][j] = a[i-1][j-1]+a[i-1][j]
for i in range(8):
    for j in range(i+1):
        print("{:3d}".format(a[i][j]),end=" ")
    print()


3




def proc(strings):                     
    m = 0
    lst = []
    for i in range(len(strings)):
        if len(strings[i]) > m:
            m = len(strings[i])
    for i in range(len(strings)):
        if len(strings[i]) == m:
            lst.append(strings[i])
    return lst
strings = ['cad' ,'VB', 'Python', 'MATLAB', 'hello', 'world']
result = proc(strings)
print("the longest words are:")
for item in result:
    print("{: >25}".format(item))


4




strings = {'cad', 'PE ', 'Window', 'FM', 'hello', 'world','flowers'}
n=0
for word in strings:
    if word.islower():
        n += 1
print(n) 


5




def proc(stu_list):
    d = {}
    for item in stu_list:
        r = item.split("_")
        a,b = r[0],r[1].strip()
        if a in d:
            d[a] += [b]
        else:
            d[a] = [b]
    lst = sorted(d.items(), key = lambda d:len(d[1]), reverse = True)
    return lst
f = open("signup.txt","r")        
stu_list = f.readlines()
result = proc(stu_list)
for item in result:
    print(item[0], '->', item[1])
f.close()


6



d = {"lili": 80, "xiaoqiang": 75, "yunyun": 89, "yuanyuan": 90, "wanghao": 85}
d_sort = sorted(d.items(), key=lambda x: x[1], reverse=True)
for i in range(3):
    print(d_sort[i][0] + " " + str(d_sort[i][1]))


第十二套


1




num = input().split(",")
for i in num:
    print("{:>10}".format(i),end='')


2




scale = 0.0001  # 成就值增量
def calv(base, day):
    val = base * pow(1+scale,day*11)
    return val
print('5年后的成就值是{}'.format(int(calv(1, 5*365))))
year = 1
while calv(1, year*365) < 100:
    year += 1
print('{}年后成就值是100'.format(year))


3




while True:
    try:
        a = eval(input('请输入一个正整数: '))    
        if a > 0 and type(a)==int:
            print(a)
            break
        else:
            print("请输入正整数")
    except:
        print("请输入正整数")


4



import turtle as t
ls = [69, 292, 33, 131, 61, 254]
X_len = 400
Y_len = 300
x0 = -200
y0 = -100
t.penup()
t.goto(x0, y0)
t.pendown()
t.fd(X_len)
t.fd(-X_len)
t.seth(90)
t.fd(Y_len)
t.pencolor('red')
t.pensize(5)
for i in range(len(ls)):
    t.penup()
    t.goto(x0 + (i+1)*50, -100)
    t.seth(90)
    t.pendown()
    t.fd(ls[i])
t.done()


5




import random
random.seed(2)
pdict = {'Alice': ['123456789'],
         'Bob': ['234567891'],
         'Lily': ['345678912'],
         'Jane': ['456789123']}
name = input('请输入一个人名:')
plist = list(pdict)
if name in plist:
    print(name, pdict.get(name)[0], random.randint(1000,9999))
else:
    print("对不起,您输入的用户信息不存在。")


6



import jieba
def fenci(txt):
    f = open(txt, "r")
    datas = f.read()
    f.close()
    data = jieba.lcut(datas)
    d = {}
    for i in data:
        if len(i) >= 2:
            d[i] = d.get(i, 0) + 1
    lt = list(d.items())
    lt.sort(key=lambda x: x[1], reverse=True)
    return lt
def show(lt):
    for i in lt[:9]:
        print(i[0], ":", i[1], end=',',sep="")
    print(lt[9][0], ":", lt[9][1],sep="")
l1 = fenci("data2018.txt")
l2 = fenci("data2019.txt")
print(2019, end=':')
show(l2)
print(2018, end=':')
show(l1)


import jieba
def fenci(txt):
    f = open(txt, "r")
    datas = f.read()
    f.close()
    data = jieba.lcut(datas)
    d = {}
    for i in data:
        if len(i) >= 2:
            d[i] = d.get(i, 0) + 1
    lt = list(d.items())
    lt.sort(key=lambda x: x[1], reverse=True)
    ls = [x[0] for x in lt[:10]]
    return ls
def show(lt):
    print(','.join(lt))
l1 = fenci("data2018.txt")
l2 = fenci("data2019.txt")
l3 = []
for i in l1:
    if i in l2:
        l3.append(i)
for i in l3:
    l1.remove(i)
    l2.remove(i)
print("共有词语:", end='')
show(l3)
print('2019特有:', end='')
show(l2)
print('2018特有:', end='')
show(l1)



相关文章
|
7天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
7天前
|
程序员 开发者 Python
Python网络编程基础(Socket编程) 错误处理和异常处理的最佳实践
【4月更文挑战第11天】在网络编程中,错误处理和异常管理不仅是为了程序的健壮性,也是为了提供清晰的用户反馈以及优雅的故障恢复。在前面的章节中,我们讨论了如何使用`try-except`语句来处理网络错误。现在,我们将深入探讨错误处理和异常处理的最佳实践。
|
11天前
|
算法 Python
1193: 最简单的计算机(python)
1193: 最简单的计算机(python)
|
11天前
|
缓存 监控 Python
解密Python中的装饰器:优雅而强大的编程利器
Python中的装饰器是一种强大而又优雅的编程工具,它能够在不改变原有代码结构的情况下,为函数或类添加新的功能和行为。本文将深入解析Python装饰器的原理、用法和实际应用,帮助读者更好地理解和利用这一技术,提升代码的可维护性和可扩展性。
|
28天前
|
编译器 测试技术 C++
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
157 0
|
1天前
|
API Python
Python模块化编程:面试题深度解析
【4月更文挑战第14天】了解Python模块化编程对于构建大型项目至关重要,它涉及代码组织、复用和维护。本文深入探讨了模块、包、导入机制、命名空间和作用域等基础概念,并列举了面试中常见的模块导入混乱、不适当星号导入等问题,强调了避免循环依赖、合理使用`__init__.py`以及理解模块作用域的重要性。掌握这些知识将有助于在面试中自信应对模块化编程的相关挑战。
12 0
|
2天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
22 0
|
21天前
|
程序员 C语言 Python
Python列表推导式:简洁与高效的编程利器
在Python编程中,列表推导式(List Comprehension)是一种强大且优雅的工具,它允许我们以简洁的方式创建新的列表。列表推导式在Python程序员中广受欢迎,因为它能够将复杂的循环和条件语句简化为一行代码,提高代码的可读性和执行效率。
|
28天前
|
Java 编译器 Shell
【Python 基础教程 04】超详细Python编程教程:初学者入门至全面了解Python 解析器( CPython、IPython、Jython和PyPy)
【Python 基础教程 04】超详细Python编程教程:初学者入门至全面了解Python 解析器( CPython、IPython、Jython和PyPy)
43 0
|
28天前
|
缓存 分布式计算 自然语言处理
Python语言的函数编程模块
Python语言的函数编程模块

热门文章

最新文章