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

2023-05 Python Level 3 Real Exam Questions

Number of questions: 38

Score: 100

Test duration: 60min

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

1. Please select, what is the result after running the following code? (C) (2 points)

a = '2'
b = '4'
try:
    c = a * b
    print(c)
except:
    print('程序出错!')
else:
    print('程序正确!')

A.  24

B.  8

C. Program error!

D. The procedure is correct!

Answer analysis: Variables a and b are both strings and cannot be multiplied, so after exception handling, "Program error!" will be printed.

   

2. What is the result of executing the following program? (A) (2 points)

a=['春','夏','秋','冬']
c=list(enumerate(a))
print(c)

A. [(0, 'Spring'), (1, 'Summer'), (2, 'Autumn'), (3, 'Winter')]

B. [[0, 'Spring'], [1, 'Summer'], [2, 'Autumn'], [3, 'Winter']]

C. [(1, 'Spring'), (2, 'Summer'), (3, 'Autumn'), (4, 'Winter')]

D. [[1, 'Spring'], [2, 'Summer'], [3, 'Autumn'], [4, 'Winter']]

Answer analysis: The enumerate() function is used to combine traversable data objects into an index sequence. If enumerate(object), the data subscript starts from 0; if enumerate(object, start=1), the data subscript starts from 1.

3. What is the result of executing the following program? (D) (2 points)

s='123456789'
print(min(s)+max(s))

A.  1

B.  9

C.  10

D.  19

Answer analysis: s='123456789', min(s)='1', max(s)='9', so the result is two strings connected, the correct answer is: 19.

4. Open the b.txt file and write "Hello Tom!" into the file. Which of the following statements is correct? (C) (2 points)

A.  f.write(['Hello'],[Tom!])

B.  f.read('Hello',' Tom!')

C.  f.write('Hello Tom!')

D.  f.read('Hello Tom!')

5. Among the following data, what is the largest value? (C) (2 points)

A.  int('16',10)

B.  int('110',2)

C.  int('11',16)

D.  int('1111',2)

Answer analysis: A is 16 decimal, B is 6 decimal, C is 17 decimal, and D is 15 decimal.

6. What is the digit of the hexadecimal number 7E converted into binary number? (A) (2 points)

A.  7

B.  6

C.  4

D.  2

Answer analysis: Hexadecimal to binary, starting from the low digit, each hexadecimal digit can be converted into a 4-digit binary number, and the leftmost "0" is removed after merging.

7. What is the return value of the expression int('13',8)? (B) (2 points)

A.  12

B.  11

C.  10

D.  15

Answer analysis: The function of the int() function here is to parse the octal string into a decimal number. The weighted expansion addition method can be used: 3×80+1×81=11.

8. There is the following code:

res = []
f = open('Python08.txt','r')  #Python08.txt中共4行诗句
p = f.readlines()
for s in p:
    res.append(s)
print(res)
f.close()

Which statement about this code is incorrect? (B) (2 points)

A. The function of the program is to read the contents of the text file line by line and write them one by one into the list res

B. The usage of readlines() here is wrong and should be changed to readline()

C. The text file and the program code file are in the same folder

D. Parameter 'r' does not allow modification of the text file

Answer analysis: readline() only reads one line of the file at a time, while readlines() reads the contents of the entire file line by line each time and returns list type data.

9. The code is as follows:

s=["白日依山尽","黄河入海流","欲穷千里目","更上一层楼"]
f=open('sj.txt','w')
f.write('\n'.join(s))
f.close()

Regarding the above code, which statement is incorrect? (B) (2 points)

A. The steps to write a text file are mainly open - write - close

B. The functions of f.write('\n'.join(s)) and f.write(' '.join(s)+'\n') are the same

C. The parameter of write() is a string, and the parameter of writelines() can be a string or a sequence of characters.

D. The function of this code is to write the poems in the list into a text file line by line.

Answer analysis: f.write('\n'.join(s)) connects the elements in sequence s with newlines and writes them to the file, while f.write(' '.join(s)+'\n' ) is to connect the elements in the sequence with spaces and then write them into the file with newlines, but the results are different.

10. We often make mistakes when writing program code. What is the correct description of Python's exception handling? (C) (2 points)

A. You can use if…elif…else… for exception handling

B. Exception handling can make up for program loopholes so that the program will not terminate under any circumstances.

C. Through exception handling statements, when the program input error is made, the program can still be allowed to continue running.

D. When an error statement is encountered, the try code block statement will be executed

Answer analysis: Python programs have certain requirements for input. When the input does not meet the program requirements, running errors may occur. Such errors can be captured and reasonably controlled. Exception handling is not specific to any errors. When an error occurs, the except code block statement is executed.

11. If scores="9,7,8,9,6,5", what is the result of list(scores)? (C) (2 points)

A.  [9,7,8,9,6,5]

B.  ['9','7','8','9','6','5']

C.  ['9', ',', '7', ',', '8', ',', '9', ',', '6', ',', '5']

D.  9,7,8,9,6,5

Answer analysis: The list() function is a built-in function of python. Its function is to convert the elements in the sequence into the elements in the list. The type of the elements is not changed during the conversion, so the numbers in the result are still string type numbers, and the elements contain commas.

12. Which of the following expressions evaluates to True? (D) (2 points)

A.  len("13"+"4")>14

B.  ord(min("banana"))<65

C.  sum([13,14,16])==53

D.  any(["a","b","","d"])

Answer analysis: The length of len("13"+"4") is 3, ord(min("banana")) is 97, sum([13,14,16]) is 43, any() is used to determine the sequence Whether all elements are False.

13. Which of the following statements about functions is correct? (C) (2 points)

A. The bool() function is a type conversion function, used to convert the given parameters into a Boolean type. If there are no parameters, an error will occur.

B. The functions of the ascii() function and the ord() function both return a numerical type of data.

C. The filter() function is used to filter sequences and elements that do not meet the conditions. It generally consists of two parameters, namely function and sequence.

D. The map() function is mainly used to draw maps

Answer analysis: The bool() function has no parameters and returns False by default. The ascii() function returns a string. The map() function is a mapping function that mainly applies the function in the parameter to each element of the sequence in the parameter.

14. Which of the following expressions has the same result as range(8)? (A) (2 points)

A.  range(0,8)

B.  range(1,8)

C.  range(0,8,2)

D.  range(1,9)

Answer analysis: range(8) means generating an integer object in the range of 0~7. The initial value starts from 0 by default, and the final value cannot be obtained. Omitting the step size means 1.

15. Given that x,y,z=map(int,['20','2','3']), what is the result of the expression x+y+z? (D) (2 points)

A. Program error

B.  2023

C.  21

D.  25

Answer analysis: The map() function means to apply the function functions one by one to the corresponding sequence. Therefore, the strings '20', '2', and '3' are converted into three integers 20, 2, and 3 respectively, and are assigned to Three variables: x, y, z.

16. "Sun Zi Suan Jing" is an important mathematical work in ancient my country. There is a question in it: "There are things today whose number is unknown. When counting threes and threes, there are two left. When counting fives and fives, there are three left. When counting sevens and sevens, there are two left. Questioning things Geometry?" Xiao Wang wrote the following program in Python:

x=1
while x>0:
    if not (   ):
        x+=1
    else:
        print(x)
        x+=1

Regarding the above procedure, which of the following statements is incorrect? (A) (2 points)

A. Change the first x+=1 to break, and the program will output a result

B. The codes that should be filled in the brackets are x%3==2 and x%5==3 and x%7==2

C. This program is an infinite loop

D. The program will have infinitely many outputs

Answer analysis: When x=1, the if condition is satisfied after taking the negation, and if break is executed, the loop will be exited directly, and the program will not output a result. Therefore A is wrong. Since x increases upward, the while condition is always satisfied, so the program will be an infinite loop, and x that meets the condition will continue to be output.

17. Which of the following descriptions of two-dimensional data is correct? (B) (2 points)

A. Two-dimensional data is composed of two one-dimensional data

B. Two-dimensional data consists of multiple one-dimensional data

C. Each one-dimensional data of two-dimensional data can only be separated by commas.

D. Two-dimensional data is not suitable for storage in table form.

Answer analysis: Two-dimensional data consists of multiple one-dimensional data and is suitable for storage in table form.

18. After using the open function to open a CSV format file, if you want to read the contents of the entire file into a list, which function of the following file object needs to be used? (C) (2 points)

A.  read()

B.  readline()

C.  readlines()

D.  flush()

Answer analysis: readlines() supports reading the contents of the entire file into a list.

19. abs() is a built-in function of Python. What is the result returned by executing the abs(-1.00) statement? (C) (2 points)

A.  -1.00

B.  1

C.  1.0

D.  1.00

20. divmod() is a built-in function of Python. Corresponding to variables x and y, what is the result returned by divmod(y,x)? (C) (2 points)

A. (x//y, x%y)

B.  (x%y, x//y)

C.  (y//x, y%x)

D.  (y%x,y//x)

21. After executing the statement a = input("Please enter the test score:") in the interactive programming environment, enter the value 89.5 through the numeric keyboard. After the input is completed, check the data type of variable a. Which one of the following will it be? (C) (2 points)

A.  float

B.  int

C.  str

D.  bool

22. After executing the print(list(range(4))) statement, what is the result displayed? (A) (2 points)

A.  [0,1,2,3]

B.  [1,2,3,4]

C.  [0,0,0,0]

D.  ['' ,'' ,'' ,'' ]

23. Brute force is a common network attack that uses trial and error to try to crack a user's password. This hacking tool is primarily designed using which of the following algorithms? (A) (2 points)

A. Enumeration algorithm

B. Analytical Algorithm

C. Sorting algorithm

D. Bisection search algorithm

Answer analysis: Analytical algorithms use analytical methods to find mathematical expressions that represent the relationship between the prerequisites and results of a problem, and solve the problem through the calculation of the expressions. The basic idea of ​​the enumeration algorithm is to list all the solutions to the problem one by one, and judge each possible solution to determine whether this possible solution is the real solution to the problem.

24. Sort a set of data "6,1,3,2,8" from small to large, and use the bubble algorithm to program. After the first round, what is the result of the sorting? (C) (2 points)

A.  1,6,3,2,8

B.  1,3,6,2,8

C.  1,3,2,6,8

D.  1,2,3,6,8

Answer analysis: The basic idea of ​​the bubble algorithm is: compare adjacent data pairwise, and exchange them if they are in reverse order, until there is no more reversed data.

    Candidate answer: C

25. How is the binary number 11110010 converted to a hexadecimal number? (C) (2 points)

A.  1502

B.  152

C.  F2

D.  F02

Answer analysis: Binary to hexadecimal conversion method: starting from the low-order binary digit, 4 digits are divided into 1 group, and converted separately. If there are insufficient digits on the leftmost side, add 0 to make up. 1111->F,0010->2. So choose C.

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

26. The following code runs normally. Is it right? (right)

while True :
    a = input('请输入一个整数,若不是整数将会让你重新输入:  ' )
    try:
        b = int(a)
    except:
        print('你输入的不是整数!将返回重输。')
    else:
        print('你输入的是整数,程序结束。')
        break

Answer analysis: This code uses the exception handling mechanism to force the user to enter numbers, and the code can run correctly. should be judged as correct.

27. For a set of arrays with n elements, if the sequential search method is used to find an element in the array, the average number of searches is (n+1)/2 times. (right)

Answer analysis: The worst number of times found is n, and the best number of times found is 1. Because of the sequential search, the average number of times found is (n+1)/2.

28. After converting a decimal number to a hexadecimal number, the number of digits must be reduced. ( wrong)

Answer analysis: Decimal 0~9 has the same representation in hexadecimal, so the number of digits does not necessarily become smaller.

29. The binary number 1101011011 converted into a hexadecimal number is 35B. ( right)

Answer analysis: To convert binary to hexadecimal, starting from the low-order bit, convert every 4 binary bits to 1 bit. If there are less than four digits, add 0 to the high bit.

30. When using the open() method, be sure to close the file object, that is, call the close() method. ( right)

Answer analysis: When using the open() method, you must ensure that the file object is closed, that is, the close() method is called.

31.

file=open('fruits.csv','r')
name=file.read().strip('\n').split(',')
file.close()

The function of the above code is to read the data in the file into a list. (right)

Answer analysis: This question tests file reading. The function of the read() function is to read the entire file at once and generate a string. The split() function uses ',' as the delimiter to split the string into a list of strings.


32.

a=['shanghai','beijing','tianjin','chongqing','hangzhou']
with open ('city.csv','w')as f:
f.write(','.join(a)+'\n')

This code is missing an 'f.close()' statement at the end to close the file. (wrong)

Answer analysis: Use the with statement to open the file, and the opened file will be automatically closed after the processing is completed.

33. The difference between the sort() and sorted() functions is that the former defaults to ascending order, and the latter defaults to descending order. (wrong)

Answer analysis: sort() is one of the methods of the list, the usage method is li.sort(), the default is ascending order; sorted() is a built-in function that can sort all iterable objects, the usage method is sorted(li), Default is ascending order.

   

34. The round() function is a mathematical function that can be used to approximately retain the number of decimal places. ( right)

Answer analysis: The round() function is a mathematical function, which can generally round to retain the number of decimal places.

35. The sum() function can not only sum list data, but also sum tuple data. (right)

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

36. The midterm exam results of a certain class are summarized in the file "score.csv", which includes the scores of Chinese, mathematics, and English. The data content is shown in the figure below:

 

Xiao Ming wrote the following program to read the data in the score file and calculate the average scores of Chinese, mathematics, and English. Please complete the code.

import csv
ChineseNum=0
MathNum=0
EnglishNum=0
num=0
with open('/data/score.csv',encoding='utf-8') as csv_file:
    row = csv.reader(csv_file, delimiter=',')
    next(row)  # 读取首行
    for r in row:
        ChineseNum += float(        ①        )
        MathNum += float(        ②        )
        EnglishNum += float(        ③        )
        num +=         ④        
print("语文平均成绩是:%.2f"%(ChineseNum/num))
print("数学平均成绩是:%.2f"%(MathNum/num))
print("英语平均成绩是:%.2f"%(EnglishNum/num))

   

Reference procedure:

import csv
ChineseNum=0
MathNum=0
EnglishNum=0
num=0
with open('/data/score.csv',encoding='utf-8') as csv_file:
    row = csv.reader(csv_file, delimiter=',')
    next(row)  # 读取首行
    for r in row:
        ChineseNum += float(r[0])
        MathNum += float(r[1])
        EnglishNum += float(r[2])
        num += 1
print("语文平均成绩是:%.2f"%(ChineseNum/num))
print("数学平均成绩是:%.2f"%(MathNum/num))
print("英语平均成绩是:%.2f"%(EnglishNum/num))

Grading:

(1) r[0]; (1 point)

(2) r[1]; (1 point)

(3) r[2]; (1 point)

(4)1. (1 point)

37. The new semester is here, and the school received a batch of donated books. Xiao Ming wrote a simple program to manage the books and support the borrowing function. In order to improve the efficiency of searching for books, Xiao Ming used the binary search method to design the book borrowing function. The following is a book borrowing management program written by Xiao Ming. Please complete the code.

library=dict()            #用字典生成一个图书管理数据结构(字典的键为编号,字典的值为['书名',本数])
#书籍入库
nums=len(library)              #先计算图书编号总数
library[nums+1]=['红楼梦',5]     #在编号总数的基础上继续添加新书:library[新编号]=['书名',本数]
library[nums+2]=['西游记',10]
library[nums+3]=['水浒传',5]
library[nums+4]=['三国演义',10]
print(library)

blist=list(library.keys())
#按书名借阅:
bookname=input('请输入借阅图书名称:')

min_v = blist[0]
max_v = blist[-1]
turns=0

while min_v <=         ①        :
    turns += 1
    cur  =  (min_v + max_v)        ②         
    print(cur)
    if library[cur][0] ==         ③        :        
        if library[cur][1]  >  0: 
            library[cur][1]  -=         ④        
            print('《%s》借阅成功!'%bookname)
        else:
            print('抱歉,您选择的书籍已被借完!')
        break
    elif blist[cur-1] > cur:
        min_v =         ⑤           
    else:
        max_v =         ⑥       
print("经过%d轮二分查找,完成图书的搜索。"%turns)

Reference procedure:

#学校图书管理系统
library=dict()            #用字典生成一个图书管理数据结构(字典的键为编号,字典的值为['书名',本数])

#书籍入库
nums=len(library)              #先计算图书编号总数
library[nums+1]=['红楼梦',5]     #在编号总数的基础上继续添加新书:library[新编号]=['书名',本数]
library[nums+2]=['西游记',10]
library[nums+3]=['水浒传',5]
library[nums+4]=['三国演义',10]
print(library)

blist=list(library.keys())
#按书名借阅:
bookname=input('请输入借阅图书名称:')

min_v = blist[0]
max_v = blist[-1]
turns=0

while min_v <= max_v:
    turns += 1
    cur = (min_v + max_v) // 2
    print(cur)
    if library[cur][0]==bookname:        
        if library[cur][1] > 0: 
            library[cur][1] -= 1
            print('《%s》借阅成功!'%bookname)
        else:
            print('抱歉,您选择的书籍已被借完!')
        break
    elif blist[cur -1] > cur:
        min_v = cur +1
    else:
        max_v = cur -1
print("经过%d轮二分查找,完成图书的搜索。"%turns)

Grading:

(1)max_v; (2 points)

(2) // 2; (2 points)

(3) bookname; (3 minutes)

(4)1; (3 points)

(5) cur +1; (3 points)

(6)cur-1. (3 points)

38. There are 6 students in the "Tian Tian Shang Shang" group in a certain class. Their names and height data are stored in list a respectively. Write a program to output the list of students in the group according to their height from high to low. The running results are as shown in the figure:

The program code is as follows, please complete the underlined areas:

a=[["李洪全",135],["王倩倩",154],["吴乐天",148],["周立新",165],["鲁正",158],["杨颖颖",150]]
for i in range(1,len(a)):
    for j in range(0,        ①        ):
        if a[j][1]        ②        a[j+1][1]:
            a[j],a[j+1]=a[j+1],a[j]
print("小组名单是:")
for i in range(len(a)):
print(        ③        )

Reference procedure:

a=[["李洪全",135],["王倩倩",154],["吴乐天",148],["周立新",165],["鲁正",158],["杨颖颖",150]]
for i in range(1,len(a)):
    for j in range(0, len(a)-i):
        if a[j][1] < a[j+1][1]:
            a[j],a[j+1]=a[j+1],a[j]
print("小组名单是:")
for i in range(len(a)):
print(a[i][0])

This question examines the bubble sort algorithm. From the outer loop, if the 6 elements are arranged 5 times, they should all be arranged neatly. Each pass of the inner loop mainly starts from the first element. Comparing adjacent elements two by two, when i=1, j finally gets 4. When i=2, j finally gets 3. When i=3, j finally gets 3. At 2, when i=2, j finally gets 1. When i=1, j finally gets 0. Since the final value of range() cannot be obtained, the first blank should be filled in len(a)-i ;According to the requirements of the question from high to low, if the previous number is smaller than the latter number, it should be moved backward, so the second space should be "<"; It can be seen from the output results that only the sorted list needs to be output The name part, so the third blank should be filled in a[i][0].

Grading:

(1) len(a)-i; (4 minutes)

(2)<; (3 points)

(3) a[i][0]. (3 minutes)

Supongo que te gusta

Origin blog.csdn.net/m0_46227121/article/details/131205620
Recomendado
Clasificación