China Electronics Society May 2023 Youth Software Programming Python Level Examination Paper Level 6 Real Questions (Including Answers)

2023-05 Python Level 6 Real Exam Questions

Score: 100

Number of questions: 38

Test duration: 60min

1. Multiple-choice questions (25 questions in total, 50 points in total)

1. Mingming insists on memorizing English words every day, so he creates an English word mistake book file "mistakes.txt" and adds the words he misstakes every day to the file. Which of the following statements is the most appropriate to open the file? (C) (2 points)

A.  f = open("mistakes.txt")

B.  f = open("mistakes.txt","r")

C.  f = open("mistakes.txt","a")

D.  f = open("mistakes.txt","w")

Answer analysis: The first parameter of the open function is the file name, including the path; the second parameter is the open mode mode

'r': read-only (default. If the file does not exist, throw an error), 'w': write-only (if the file does not exist, the file is automatically created), 'a': append to the end of the file.

2. The English words that Xiao Zhang needs to learn in the near future are stored in the "data.txt" file, with the format as shown in the figure.

 

The Python program segment that processes English words in the "data.txt" file is as follows:

file = open("data.txt")
for word in file:
    if word[0:1] == "c":
        continue
    else:
        print(word)
file.close()

Which of the following statements about the function of this program segment is correct? (D) (2 points)

A. Output words containing "c" (case sensitive)

B. Output words starting with "c" (case sensitive)

C. Output words starting with "c" (case-insensitive)

D. Output words that do not start with "c" (case sensitive)

Answer analysis: After reading the file, word stores the content of each line of the file. word[0:1] represents the first letter of the line. If it starts with a lowercase letter "c", skip it. Otherwise, print the word, so the program function is to output not Words starting with "c" (case sensitive).

3. The file "score.csv" contains the score data of three students. Xiao Li wrote a program to read the data content. The file content and program successfully read the interface as shown in the figure.

import csv
csv_reader = csv.reader(open(______))
for row in csv_reader:
     print(______)

Should the underlined areas in the above procedure be filled in? (D) (2 points)

A.  score row

B.  score.csv "row"

C.  "score" "row"

D.  "score.csv" row

Answer analysis: When reading a file, the parameter of the open function is a string. It should be the complete file name plus a string identifier. row represents the content of each line, and no string identifier should be added.

   

4. There is the following program code:

import csv                          #  ①       
headers = ['学号','姓名','分数']
rows = [['202001','张三','98'],
        ['202002','李四','95'],
        ['202003','王五','92']]
with open('score.csv','w',encoding='utf8',newline='') as f : #  ② 
    writer = csv.writer(f)          #  ③
writer.writerow(headers)      
writer.writerows(rows)          #  ④      

Regarding the explanation of the above statement, which one is incorrect? (D) (2 points)

A. The function ① is to import the csv library

B. Open the file in writing mode at ②

C. Create a csv.writer instance at ③

D. Only one line can be written at ④ at a time

Answer analysis: writer.writerows(rows) will write multiple rows of data

5. Regarding the functions of the functions in the matplotlib module, which of the following descriptions is correct? (D) (2 points)

A. The bar() function is used to draw a line chart

B. The plot() function is used to draw horizontal column charts

C. The barh() function is used to draw vertical column charts

D. The scatter() function is used to draw scatter plots

Answer analysis: The bar() function is used to draw vertical column charts, the plot() function is used to draw line charts, and the barh() function is used to draw horizontal column charts. Therefore, the ABC options are all wrong; the scatter() function uses To draw a scatter plot, therefore, the answer is D.

6. Draw the graph of sin(x) as shown in the figure. What is the statement at the drawn line? (C) (2 points)

 

import matplotlib.pyplot  as plt
import numpy  as  np
x = np.linspace(0, 10, 30) 
___________
plt.show()

A.  plt.bar(x)

B.  plt.scatter(x)

C.  plt.plot(x, np.sin(x))

D.  plt.scatter(x, np.sin(x))

Answer analysis: The function for drawing a line chart is plot, which must have two parameters. The first parameter is x, and the second parameter is np.sin(x).

7. Which of the following statements about classes and objects is correct? (D) (2 points)

A. Define a class through the def keyword

B. Create an instance through class

C. The data of each object is the same

D. Each object has the same method

Answer analysis: Python defines a class through the class keyword and creates an instance through the class name + (). The data of each object may be different, and each object has the same method.

8. There is the following program segment:

class Student:
    count = 0
    def __init__(self, name):
        self.name = name
        Student.count += 1
    def study(self):
        print(f'{self.name}在学习')
student1 = Student("小明")
student2 = Student("小红")
student2.study()

After executing the code, which of the following statements is incorrect? (B) (2 points)

A. The program creates 2 instances

B. The value of Student.count is 0

C. study is a method of this class

D. The output result is "Xiaohong is studying"

Answer analysis: The program creates 2 instances, and the value of Student.count is 2.

9. There are the following statement commands:

import sqlite3                   
conn = sqlite3.connect("test.db") # ①
cursor = conn.cursor()            # ②
cursor.close()                    # ③
conn.close()                      # ④

Which of the following explanations about statement functions is correct? (A) (2 points)

A. ①Create and connect to the database

B. ②Submit transaction

C. ③Close the database connection

D. ④Close the cursor

Answer analysis: Import the database module first. The connect() function is used to create and connect to the database. ② is to create a cursor, ③ is to close the cursor, and ④ is to close the database connection.

10. The commit() function is a command function to submit database operations. Which of the following database operations does not require execution of this function? (A) (2 points)

A. Query operation

B. Add operations

C. Modification operation

D. Delete operation

Answer analysis: The commit() function is used to commit the current transaction. If you do not call this method, any actions taken since your last call to commit() will not be visible to other database connections.

11. Part of the code to perform database operations is as follows:

import sqlite3
db = sqlite3.connect("test.db")
cur=db.cursor()
cur.execute("create table Student(Sname char(20),Sage SMALLINT);")
db.close()

Which of the following descriptions is correct? (D) (2 points)

A. The name of the database currently being operated is Student.

B. The function of the create table statement is database query

C. 2 new records will be inserted into the data table

D. There are 2 fields in the current table

Answer analysis: The name of the currently operated database is "test.db". The function of the create table statement is used to create a data table. The data table contains two fields: Sname and Sage.

12. Xiaomeng wants to use tkinter to create a click-button greeting program that outputs "Hello World!" with the following statement:

import tkinter as tk       
window = tk.Tk()
window.title("Python GUI") # ①
window.geometry("600x100") 
window.mainloop()        

What is the function of statement ① in the program? (B) (2 points) (2 points)

A. Create a window object

B. Set window title

C. Set window size

D. Use window objects

Answer analysis: window = tk.Tk() is to create a window object, window.geometry("600x100") is to set the window size, and window.mainloop() is to use a window object.

13. Xiao Li designs a radio button interface that displays addition, subtraction, multiplication, and division. The code is as follows:

import tkinter
from tkinter import *
root = Tk()
v = IntVar()
calcs = [ ('+', 1),    ('-', 2),    ("*", 3),    ("/", 4),]
for calc, num in calcs:
    # 设置单选框,用来显示运算符
Radiobutton(text = calc,variable =v,value=num).grid(row=num-1, column=1)
root.mainloop()

What is the interface after running? (B) (2 points)

A. 

B. 

C. 

D. 

Answer analysis: text = calc indicates that the symbols are displayed in the interface, row=num-1, column=1 indicates that the number of rows is different but the number of columns is the same.

14. There is the following Python program segment:

n=4
a=[[i*n+j+1 for j in range(n)]for i in range(n)]
for i in range(n//2):
    for j in range(1,n,2):
        a[i][j],a[n-i-1][n-j-1]=a[n-i-1][n-j-1],a[i][j]

After the program is executed, what are the values ​​of a[1][1] and a[2][0] respectively? (D)

A. 6 and 9

B. 8 and 9

C. 11 and 9

D. 11 and 8

Answer analysis:

a=[[i*n+j+1 for j in range(n)]for i in range(n)]

Create a 4*4 two-dimensional array

a=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]。

The loop range of variable i is 0 to 1, and the loop range of variable j is 1 to 3 steps 2. The available results are:

a=[[1,15,3,13],[5,11,7,9],[8,10,6,12],[4,14,2,16]]

To sum up, a[1][1]=11, a[2][0]=8, choose D.

15. Which of the following statements about data visualization is the most accurate? (C) (2 points)

A. Data visualization refers to the visualization of static data

B. What determines the form of data visualization is the data structure

C. Scatter plots can be used to visually explore the distribution relationship of relevant data.

D. Radar charts can be used to visually display time trend data.

Answer analysis: Using visualization technology, the changing data can be used to generate real-time changing visual charts; different data types determine the form of visual expression; column charts and line charts can be used to display time trend data.

16. The file exam.txt is in the same directory as the following code, and its content is a piece of text: bigBen. What is the output of the following code? (C) (2 points)

f = open("exam.txt")
print(f)
f.close()

A.  exam.txt

B.  exam

C.  <_ io.TextlOWrapper ..>

D. bigBen

Answer analysis: The open() function opens a file and returns the variable f that can operate on the file. The open() function has two parameters: file name and opening mode. This question only opens the file and does not operate the file, so the contents of the file will not be output. The print() statement outputs relevant information about the file represented by variable f: <_ io.TextlOWrapper name='exam.txt' mode='r encoding='cp936'>. If you want to output the content of the file, you need to The content is read in, such as f1 = f.read(). Choose option C for this question.

17. There is the following python program:

import numpy as np
from matplotlib import pyplot as plt
x=np.arange(-5,5,0.1)
y=np.sin(x)
plt.show()

No error is reported after running but the running results cannot be seen. What could be the possible reason? (C) (2 points)

A. Missing plt.plot() statement

B. Missing plt.scatter() statement

C. Third-party libraries are not installed correctly

D. Computer freezes

Answer analysis: If the third-party library is not installed correctly, an error similar to No module named 'numpy' will be reported. Since no error is reported, the third-party library has been installed.

18. Which of the following is not a component of the object? (D) (2 points)

A. Logo

B. Properties

C. Method (or operation)

D. Rules

Answer analysis: An object is a unity that is encapsulated by data describing the properties of the object and all operations that can be performed on these data. An object usually consists of three parts: object name (identity), attributes and operations. The answer to this question is option D.

19. Assume that the content in "data.txt" is: Fungus + Tremella + Beef + Egg + Mushroom. Run the following program and the content will be modified to: Fungus * Tremella * Beef * Egg * Mushroom. What should be filled in the blank parts of the code? (A) (2 points)

f = open("数据.txt","r")
s= f.read() .split("+")
f =open("数据. txt", "w") 
f.write(______) 
f.close( )

A.  "*".join(s)

B.  s.split(*)

C.  s

D.  s.join(*)

Answer analysis: By reading the data, use the join function to join the read data together, and write it back to Notepad.

20. Use Python statements to create a sQLite database. The code is as follows:

import sqlite3
conn= sqlite3.connec("test2.db")
c=conn.cursor()
c.execute("CREATE TABLE STUDENTS(ID INT,AGE INT,NAME TEXT)")
c.execute("INSERT INTO STUDENTS(ID, AGE,NAME) VALUES(2,16,'LISA')")
c.execute("UPDATE STUDENTS set AGE=18 where it,ID=2")
conn.commit()
c.close()
conn.close()

After the program is run, what is the value of the AGE column? (D) (2 points)

A.  2

B.  16

C.  LISA

D.  18

Answer analysis: After the program connected to the database, it created the table "STUDENTS", set three fields, and inserted the data ID=2, AGE=16, NAME="LISA"; later, the AGE was changed to 18.

21. Use the tkinter module to design an interface for finding "circle area". Several functions and buttons are customized in the program. It is required to click the "Exit" button to close the interface window, and click the "Reset" button to reset the input box. The data, part of the program code is as follows:

def cancel():
    var_r.set('')
def tc_quit():
    win.quit()
    win.destroy()

Which of the following options correctly calls the function function in the "Exit" button? (C) (2 points)

A. btn_Cancel=tk.Button(win,text='Reset',command=tc_quit)

B. btn_quit=tk.Button(win,text='Exit',command=cancel)

C. btn_quit=tk.Button(win,text='Exit',command=tc_quit)

D. tc_quit=tk.Button(win,text='Exit')

Answer analysis: Select the button that displays "Exit" among several buttons, and call the statement of the function tc_quit.

22. Which of the following options can create a text box? (A) (2 points)

A.  tkinter.Text()

B.  tkinter.Tk()

C.  tkinter.Button()

D.  tkinter.Label()

Answer analysis: Text(): text box TK(): interface, Button(): button, Label(): label

23. There is the following program segment:

class xcal:
    def __init__(self,numx,numy):
        self.numx=numx
        self.numy=numy
    def xadd(self,another):
        numx=self.numx*another.numx
        numy=self.numy*another.numy
        return xcal(numx,numy)
    def print(self):
        print(str(self.numx)+"/"+str(self.numy))
x=xcal(2,3)
y=x.xadd(xcal(4,5))
y.print()

After the program is run, what is the output result? (D) (2 points)

A.  6/20

B.  15/8

C.  10/12

D.  8/15

Answer analysis: According to the meaning of the question, the output result is str(self.numx)+"/"+str(self.numy), self.numx=2*4, self.numy=3*5.

24. The Python program is as follows:

from random import random
a=[0]*7
flag=[False]*10
i=1
while i<=6:
    a[i]=int(random()*5)*2+1
    if flag[a[i]]==False or a[i]>a[i-1]:
        flag[a[i]]=True
        i=i+1

After this program segment is run, the value of list a may be? (D) (2 points)

A.  [0, 7, 5, 9, 7, 1, 7]

B.  [0, 1, 3, 5, 7, 9, 1]

C.  [0, 9, 2, 3, 5, 7, 5]

D.  [0, 9, 5, 9, 7, 9, 1]

Answer analysis: This question tests the operation of one-dimensional arrays. The value generated by a[i] can only be an odd number. Only the currently generated value has not appeared before or is larger than the previous value. It can be stored. So choose D

25. In China, people with Chinese nationality who are over 18 years old have the right to vote. The school wants to compile a list of students who are over 18 years old as of December 31, 2022.

Student related information is stored in the "stu_info.txt" file, and the storage format is as follows:

High School 1|Xie Le|340421200606155914

High School 1|Cen Xinqi|330282200407301529

Write the code in python as follows:

f=open("stu_info.txt","r",encoding="utf8")
namelist=[ ] #存放年满18周岁的学生名单
for line in f.readlines():
        stu=line.split("|")
        birth=        ①        
        if birth<="20041231":
            namelist.append(        ②        )
print(namelist)

①②The codes in the two places should be filled in as? (A) (2 points)

A. ① this[2][6:14] ② this[1]

B. ① this[2][6:13] ② this[1]

C. ① this[3][6:14] ② this[2]

D. ① this[2][-12:-1] ② this[1]

Answer analysis: After cutting through the split() function, the ID card is in the third field. The index in the list is 2, and then the date of birth is retrieved from the ID card field. The right endpoint of the main slice cannot be retrieved. Therefore, the ① position is stu[2][6:14], and the satisfied name is retained, so the ② position is stu[1].

2. True or False Questions (10 questions in total, 20 points in total)

26. Use the readlines() function to read the contents of the text file. What is returned is a list, in which the data of each line is an element. (right)

Answer analysis: The readlines() function returns a list.

27. The difference between JSON’s loads and load methods is that loads operates on strings and load operates on file streams. ( right)

Answer analysis: The difference between JSON's loads and load methods is that loads operates on strings and load operates on file streams.

28. numpy.linspace(1,10,10) is used to generate a one-dimensional array from 1 to 9. (wrong)

Answer analysis: The result produced by numpy.linspace(1,10,10) is [1. 2. 3. 4. 5. 6. 7. 8. 9. 10.], including 10.

29. A class consists of three parts: class name, attributes and methods. ( right)

Answer analysis: A class consists of three parts: class name, attributes and methods.

30. When using tkinter to design a form, the properties of the Text control include bg, font, bd and command. (wrong)

Answer analysis: Text control bg is to set the background color, font is to set the font type and size, bd is the border width; command is the button attribute.

31. If a public method is implemented in a subclass, the method can also call the private methods and private properties in the inherited parent class. (wrong)

Answer analysis: In the inheritance of Python classes, if you call the public method that inherits the parent class, you can access the private properties and private methods in the parent class in the public method; but if a public method is implemented in the subclass, then this The method cannot call the private methods and private properties in the inherited parent class, so it is wrong.

32. If the file is not closed using close(), the file will not be closed automatically when the Python program exits. (wrong)

Answer analysis: If the file is not closed using close(), the program will generally close automatically when exiting, but this may result in data loss.

33. CSV files generally use commas to separate elements. (right)

Answer analysis: CSV files generally use commas to separate elements.

34. The following program can extract all elements between 5 and 10. (right)

import numpy as np 
a = np. arange(15) 
print(a[(a<=10) & (a>=5)])

Answer analysis: (a<=10) & (a>=5) means that both conditions must be met, that is, 5<=a<=10

35. Use Python language to operate the SQLite database to open and close the database file named test.db. There are the following statement commands:

①conn = sqlite3.connect("test.db")

②cur = conn.cursor( )

③import sqlite3

④conn.close( )

⑤cur.close( )

To realize the above function, the correct order of execution of the above statements is ③①②⑤④. (right)

Answer analysis: First import the sqlite3 module, then establish a connection, create a cursor, and finally close it.

3. Programming questions (3 questions in total, 30 points in total)

36. Open a text file 'old.txt' composed of lowercase English, encrypt each letter in the file and write it to a new file 'new.txt'. The encryption method is: a becomes b, b It becomes c..., z becomes a, and other characters remain unchanged (regardless of the file path)

file=open("old.txt","r")
line=file.         ①        

list=[]
while line:
    for i in range(        ②        ):
        if line[i].islower():
           jm=        ③        
           list.append(chr(jm))
        else:
            list.append(line[i])
    line=file.readline()
s=''.join(list)
file=open("new.txt","w+")
        ④        
file.close()

Reference procedure:

file=open("old.txt","r")

line=file.readline()
list=[]
while line:
    for i in range(len(line)):
        if line[i].islower():
           jm=(ord(line[i])-97+1)%26+97
           list.append(chr(jm))
        else:
            list.append(line[i])
    line=file.readline()
s=''.join(list)
file=open("new.txt","w+")
file.write(s)
file.close()

Grading:

(1) readline(); (2 minutes)

(2) len(line); (3 minutes)

(3)(ord(line[i])-97+1)%26+97; (3 minutes)

(4)file.write(s)。(2分)

37. Use Python’s sqlite3 library to complete the following operations:

1. Create a database file named cpu and create a Rate table (the table has three fields: ID, Rate, updatetime)

2. Record ten seconds of CPU-related data and delete the data with ID 1.

import sqlite3
import datetime
import psutil   #获取cpu当前占比
conn = sqlite3.connect("        ①        ")
creatsql = "create table Rate(ID integer primary key, Rate float,updatetime time)"
        ②        
cur.execute(creatsql)
conn.commit()
insertsql = "insert into Rate(ID,Rate,updatetime) values(%d,%f,'%s')"
checksql = "select * from Rate"
for x in range(0,10):
    nowtime = datetime.datetime.now()
    nowtime = nowtime.strftime('%Y-%m-%d %H:%M:%S')
    cpu_per = float(psutil.cpu_percent(1))
    cur.        ③        (insertsql  % (x,cpu_per,nowtime))
    conn.commit()
cur.execute(checksql)
data = cur.fetchall()
delsql="delete from Rate where ID=%d"
cur.execute(delsql %1)
conn.commit()
        ④        
conn.close()

Reference procedure:

import sqlite3
import datetime
import psutil
conn = sqlite3.connect("cpu.db")
creatsql = "create table Rate(ID integer primary key, Rate float,updatetime time)"
cur = conn.cursor()
cur.execute(creatsql)
conn.commit()
insertsql = "insert into Rate(ID,Rate,updatetime) values(%d,%f,'%s')"
checksql = "select * from Rate"
for x in range(0,10):
    nowtime = datetime.datetime.now()
    nowtime = nowtime.strftime('%Y-%m-%d %H:%M:%S')
    cpu_per = float(psutil.cpu_percent(1))
    cur.execute(insertsql % (x,cpu_per,nowtime))
    conn.commit()
cur.execute(checksql)
data = cur.fetchall()
delsql="delete from Rate where ID=%d"
cur.execute(delsql %1)
conn.commit()
cur.close()
conn.close()

Grading:

(1) cpu.db; (2 points)

(2)cur = conn.cursor();(3分)

(3) execute; (2 points)

(4) cur.close(). (3 minutes)

38. Create a student class to store the student's name, Chinese score, English score and math score, and calculate the corresponding grade based on the score. Score ≥ 90 is 'A', score ∈ [80,90] is 'B', score ∈ [60,80] is a 'C', and a score ≤60 is a 'D'. Create a class class, which has two attributes: class name and student, and displays the names and corresponding grades of all students in the class. The running effect of the program is shown in the figure below.

 

The program code is as follows:

class stu:
    def __init__(self,name,chinese,english,math):
        self.name=name
        self.c= chinese
        self.e= english
                ①        
        lis=[self.c,self.e,self.m]
        self.lis=lis
    def level(self):
        for i in range(3):
            if         ②        :
                self.lis[i]='A'
            elif  self.lis[i]>80:
                self.lis[i]='B'
            elif  self.lis[i]>60:
                self.lis[i]='C'
            else:
                self.lis[i]='D'
        return self.lis
    def show(self):
        print(f'姓名:{self.name},等级:{        ③        }')
class lesson:
    def __init__(self, name, students=[]):
        self.students = students
        self.class_name = name
    def show_student(self):
        for stu in self.students:
                    ④        
students = [ stu('jack',90,80,90),
             stu('candy',95,88,69),
             stu('cindy',66,76,39),
             stu('frank',61,87,44),
             stu('tony',20,65,49)]
class1 = lesson("高一(1)班",students)
        ⑤      

Please fill in the correct code where underlined.

Reference procedure:

class stu:
    def __init__(self,name,chinese,english,math):  # 定义类,类名为Student
        self.name=name              # 姓名属性
        self.c= chinese             # 语文成绩属性
        self.e= english             # 英语成绩属性
        self.m = math               # 数学成绩属性
        lis=[self.c,self.e,self.m]  # 成绩存入列表
        self.lis=lis
    def level(self):
        for i in range(3):   
            if self.lis[i] >=90:    # 等级判断
                self.lis[i]='A'
            elif  self.lis[i]>80:
                self.lis[i]='B'
            elif  self.lis[i]>60:
                self.lis[i]='C'
            else:
                self.lis[i]='D'
        return self.lis
    def show(self):         # 定义show方法,用于显示信息
        print(f'姓名:{self.name},等级:{self.level()}')
     
class lesson:              # 定义 lesson类
    def __init__(self, name, students=[]):     # 定义2个属性
        self.students = students               # 定义学生属性
        self.class_name = name                 # 定义姓名属性
    def show_student(self):   # 定义show_student方法,用于显示学生列表
        for stu in self.students:              # 遍历学生列表
            stu.show()                         # 显示学生信息
students = [ stu('jack',90,80,90),
                   stu('candy',95,88,69),
                   stu('cindy',66,76,39),
                   stu('frank',61,87,44),
                   stu('tony',20,65,49)]
class1 = lesson("高一(1)班",students)
class1.show_student()

Grading:

(1) self.m = math; (2 minutes)

(2)self.lis[i] >=90;(2分)

(3) self.level(); (2 minutes)

(4) stu.show(); (2 minutes)

(5) class1.show_student(). (2 minutes)

Guess you like

Origin blog.csdn.net/m0_46227121/article/details/131225874