Python final review

python final review

需要选择题pdf和编程题源码,见文章末尾哦

1. Multiple choice questions

1. Among the following options, the one that is not a function is ()
A 、提高代码执行速度
B. Reduce programming complexity
C. Enhance code readability
D. Reuse code


2. Regarding comments in the Python language, the incorrect description in the following options is ()
A、Python 语言的单行注释以’开头
B. Single-line comments in the Python language begin with # single quotes.
C. Multi-line comments in the Python language begin and end with "" (three single quotes).
D , The Python language has two comment methods: single-line comments and multi-line comments.


3. Regarding Python strings, the following options are incorrectly stated ()
A、可以使用 datatype()测试字符串的类型
B. To output a string with quotes, you can use escape characters
C. A string is a character sequence, and the number in the string is called "index"
D. Strings can be stored in variables or stored separately.


4. Give the following code:

DictColor = {
    
    "seashell":"海贝色","gold":“金色","pink":"粉红色","brown":"棕色","purple":"","tomato":"西红柿色"}

Among the following options, the ones that can output "Sea Shell Color" are
A. print(DictColor. keys)
B. print(DictColor.["Sea Shell Color"])
C. print(DictColor.values()
D、print(DictColr["seashell"])


5. The file book.txt is in the directory where the current program is located. Its content is a piece of text: book. The output result of the following code is

txt = open("book.txt", "r')
print(txt)
txt.close()

A、book.txt
B、txt
C、book
D、以上答案都不对


6 Regarding Python combined data types, the following options are incorrectly described ( )
A. Python’s str, tuple and list types all belong to sequence types
B. Python combined data types can organize multiple data of the same type or different types. Making data operations more orderly and easier through a single representation.
C. Combined data types can be divided into 3 categories: sequence types, set types and mapping types.
D、序列类型是二维元素向量,元素之间存在先后关系,通过序号访问


7 The output result of the following code is ( )

d ={
    
    "大海":"蓝色", "天空":"灰色", "大地":"黑色"}
print(d["大地"], d.get("大地", "黄色"))

A. black yellow
B、黑色 黑色
C. black gray
D. black blue


8 The execution result of the following code is: ( )

d = {
    
    }
for i in range(26):
	d[chr(i+ord("a"))] = chr((i+13) % 26 + ord("a"))
for c in "Python":
 	print(d.get(c, c), end="")

A、Plguba
B、Cabugl
C、Python
D、Pabugl


9 Regarding the floating point number type of the Python language, the incorrect description in the following options is ( )
A. The Python language requires that all floating point numbers must have a decimal part
. B. The floating point number type is consistent with the concept of real numbers in mathematics.
C、小数部分不可以为 0
D. The floating point number type represents a decimal part. Types with decimals


10 Regarding the statements related to "indentation" in Python programs, the correct one of the following options is ()
A. The indentation is unified to 4 spaces
B. The indentation is not mandatory and is only to improve the readability of the code
C、缩进在程序中长度统一且强制使用
D. Indentation can be used after any statement to indicate the inclusion relationship between statements.


11 The output result of the following code is ( )

s = "The python language is a cross platform language."
print(s.find('language',30))

A. 11
B、40
C. 10
D. Error report


12 Regarding the Python loop structure, the wrong description in the following options is ( )
A. Python uses reserved words such as for and while to traverse loops and infinite loop structures.
B. break is used to jump out of the innermost for or while loop and escape from the loop. The program continues execution after the loop code.
C、每个 continue 语句只有能力跳出当前层次的循环
D. The traversal structure in the traversal loop can be strings, files, combined data types, range() functions, etc.


13 The correct description of the following options is ( )
A. Condition 24<=28<25 is illegal
B. Condition 24<=28<25 is legal and the output is True
C. Condition 35<=45<75 Yes Legal, and the output is False
D、条件 24<=28<25 是合法的,且输出为 False


14 In Python, regarding global variables and local variables, which of the following options is incorrectly described ( )
A. Variables in a program include two categories: global variables and local variables
B、全局变量不能和局部变量重名
C. Global variables generally have no indentation
D. Global variables Effective throughout the entire process of program execution


15 Regarding the description of Python file opening mode, the following options are incorrect ()
A. Read-only mode r
B. Append writing mode a
C、创建写模式 n
D. Overwrite writing mode w


16.Which of the following statements is illegal in Python? ()
A, x = y = z = 1
B、x = (y = z + 1)
C, x, y = y, x
D, x += y


17.Regarding Python memory management, which of the following statements is wrong ()
A. Variables do not need to be declared in advance
B、变量无须先创建和赋值而直接使用
C. Variables do not need to be specified in type
D. You can use del to release resources


18.print 100 - 25 * 3 % 4 What should be output? ()
A, 1
B、97
C, 25
D, 0


19. Which of the following is not a legal identifier in Python ()
A. int32
B、40XL
C. self
D. _name


20. Which of the following statements is wrong ()
A、除字典类型外,所有标准对象均可以用于布尔测试
B. The Boolean value of an empty string is False
C. The Boolean value of an empty list object is False
D. The Boolean value of any numerical object with a value of 0 is False


21. The value of the following expression is True ()
A. 5+4j > 2-3j
B. 3>2>2
C、1==1 and 2!=1
D. not (1==1and 0!=1)


22. The data types that Python does not support are ( )
A、char
B, int
C, float
D, list


23. The following statements that cannot create a dictionary are (
A. dict1 = {}
B. dict2 = { 3 : 5 }
C、dict3 = dict( [2 , 5] ,[ 3 , 4 ] )
D. dict4 = dict( ( [1,2],[3,4] ) )


24. The following statements that cannot create a set are ()
A. s1 = set ()
B. s2 = set (“abcd”)
C、s3 = (1, 2, 3, 4)
D. s4 = frozenset( (3,2,1) )


25. The following Python statements are correct ()
A. min = x if x < y else y
B. max = x > y and?x : y
C. if (x > y) print x
D、while True : pass


26. Which of the following statements is correct? ()
A. The function of the continue statement is to end the execution of the entire loop.
B. 只能在循环体内使用 break 语句
C. The use of the break statement or the continue statement within the loop body has the same effect.
D. When exiting from a multi-level loop nest, only the goto statement can be used.


27. Regarding Python's lambda function, which of the following options describes the error? ()
A. The lambda function returns the function name as the function result
B. f = lambda x,y:x+y 执行后,f 的类型为数字类型
C. Lambda is used to define simple functions that can be expressed in one line
D. You can use lambda Sorting principles for function definition lists


28.What is the result of print(“ab” + “c”*2)?
A. abc2
B. abcabc
C. abcc
D. ababcc


29.The program code is as follows

try:
number = int(input(“请输入数字:”))
print(“number:,number)
print(=hello”)
except Exception as e: # 报错错误日志
print("打印异常详情信息: ",e)
else: print(“没有异常”)
finally:#关闭资源
print(finally) print(“end”)

The input is 1a. What is the result? ()
A. number: 1 打印异常详情信息: invalid literal for int() with base 10:‘1a’ finally end
B. Print exception details: invalid literal for int() with base 10:'1a' finally end
C. hello=== Print exception details: invalid literal for int() with base 10:'1a' finally end
D. None of the above is correct


30.What are the mapping types in Python? ()
A. List, dictionary
B. List
C. List, tuple
D. 字典


31. Regarding the exception handling of the program, which of the following options describes the error?
A. The program exception can continue to execute after being properly handled
B. Exception statements can be used with else and finally reserved words
C. 编程语言中的异常和错误是完全相同的概念
D. Python uses reserved words such as try and except ᨀProvides exception handling function


32. What is used for information processing and information storage in computers? ()
A. 二进制代码
B. Decimal code
C. Hexadecimal code
D. ASCII code


33. What is the wrong way to import modules? ()
A. import numpy
B. from numpy import *
C. import numpy as np
D. import numpy from xxx


34. Regarding complex numbers in Python, which of the following statements is wrong?
A. The syntax for expressing complex numbers is real + image j
B. The real part and the imaginary part are both floating point numbers
C. 虚部必须后缀 j,且必须是小写
D. The method conjugate returns the conjugate complex number of a complex number


35. Which of the following statements about modules is wrong?
A. An xx.py is a module
. B. Any ordinary xx.py file can be imported as a module.
C. 模块文件的扩展名不一定是 .py
D. The imported module will be searched from the specified directory during runtime. If not, Will report an error exception


36. Among the following options, which one is not Python's file opening mode?
A. r'
B. +'
C. 'w'
D. c’


37. Regarding object-oriented inheritance, which of the following options is correct? ()
A. Inheritance refers to the similar properties of a group of objects
B. 继承是指类之间共享属性和操作的机制
C. Inheritance refers to the common properties between objects
D. Inheritance refers to an object Have the properties of another object


38. Which of the following statements about strings is incorrect? (B)
A. Characters should be treated as strings of length 1
B. 字符串以\0 标志字符串的结束
C. You can use either single quotes or double quotes to create strings
D. Special characters such as line feeds and carriage returns can be included in triple quote strings


39. What is the result of running the following code? kvps = { '1' :1, '2' : 2 } theCopy =kvps.copy() kvps['1']
= 5 sum = kvps['1']+ theCopy['1'] print(sum)
A . 2
B. 11
C. 15
D. 6


40.Which of the following errors will occur? ()
A. 'Tianchi'.encode()
B. ‘天池’.decode()
C. 'Tianchi'.encode().decode()
D. None of the above will go wrong

Programming questions

1. Sum and product of a sequence of numbers

# 简单数列和积求解
def sum_and_product(n):
    sum_n = sum(range(1, n+1))
    product_n = 1
    for i in range(1, n+1):
        product_n *= i
    print(f"和与积分别是{
      
      sum_n},{
      
      product_n}")


sum_and_product(10)

# 亦或是实验中的 计算表达式 a+aa+aaa+aaaa 的值
n = eval(input())
args = 0
num = 0

for i in range(1, 5):
    args = args * 10 + n
    num += args

print(num)

2. How to find the greatest common divisor and least common multiple (euclidean division method)

def gcd(a, b):
    while b: # 因 b = a % b ,a % b最终都会等于0,故可以作为循环退出条件
        a, b = b, a % b # 辗转相除法
    return a

def lcm(a, b):
    return a * b // gcd(a, b)

# 示例:求60和48的最大公约数和最小公倍数
# a,b = map(int, input().split(",")) 
gcd_result = gcd(60, 48)  # 最大公约数
lcm_result = lcm(60, 48)  # 最小公倍数
print(f"最大公约数:{
      
      gcd_result}")
print(f"最小公倍数:{
      
      lcm_result}")

3. Representation and solution of piecewise functions

import math

def piecewise_function(x):
    if x < 0:
        return x**2
    else:
        return math.sqrt(x)

# 示例:计算x为-2和2时的函数值
piecewise_result_negative = piecewise_function(-2)  # x为负数的情况
piecewise_result_positive = piecewise_function(4)   # x为正数的情况

print(piecewise_result_positive)
print(piecewise_result_negative)


Or maybe this question in the experiment

Insert image description here

x = eval(input())
#请在这行下面补上代码
if x < 0:
	y = x * x + 1
else:
	y = x - 10
print (y)

4. How to find perfect numbers

"""
完备数(完美数)是它所有真因子(即除了自身以外的约数)的和等于它本身的数
例如,6的真因子为1, 2, 3,且1+2+3=6,所以6是一个完备数
"""
# 简便式函数式编程
def is_perfect_number(n):
    # sum_of_divisors = sum([i for i in range(1, n) if n % i == 0])
    sum_of_divisors = sum(i for i in range(1, n) if n % i == 0)
    return sum_of_divisors == n

# 测试代码
is_perfect_number_6 = is_perfect_number(6)  # 测试6是否是完备数
is_perfect_number_28 = is_perfect_number(28)  # 测试28是否是完备数

print(is_perfect_number_6)
print(is_perfect_number_28)

# -------------------------------------------
# 复盘式写法 
input_num = eval(input())
# 1、简便式写法
sum_of_division = sum(i for i in range(1,input_num) if input_num % i == 0)
# 2、传统式写法
sum = 0
for i in range(1, input_num):
    if input_num % i == 0:
        sum += i

if sum_of_division == input_num:
    print("True")
else:
    print("False")

5. Method of generating dictionary using numbers

def create_dict_from_numbers(numbers):
    return {
    
    num: num ** 2 for num in numbers}


# 测试代码
print(create_dict_from_numbers([1, 2, 3, 4, 5]))  # 以1到5的数字创建字典


# -------------------------------------------------
#亦或是实验中的
#使用给定的正整数 n,编写一个程序生成一个包含(i, i*i)的字典,该字典包含 1 到 n 之间的整数(两者都包含)。然后程序应该打印字典
n = int(input())
d = {
    
    }
for i in range(1,n+1):
	d[i] = i*i
print(d)

6. Remove duplicate words from the text (use sets) and sort them

def unique_sorted_words(text):
    words = text.split()
    unique_words = sorted(set(words))
    return unique_words

# 测试代码
text = "apple banana apple orange banana grape"
print(unique_sorted_words(text))

7. Caesar Cipher (number shift transformation in the character table)

# 通过定义一个函数进行判断,函数的参数是文本和加密偏移数
def caesar_cipher(text, shift):
    result = ""
    for i in range(len(text)):
        char = text[i]
        if char.isupper():
            result += chr((ord(char) + shift - 65) % 26 + 65)  # 大写'A' -> 65
        else:
            result += chr((ord(char) + shift - 97) % 26 + 97)  # 小写'a' -> 97
    return result

input_text = input()
print(caesar_cipher(input_text, 3))

# 亦或是实验中
"""
思路:
1.输入
2.准备一个空的字符串接收转换后的每个字符拼接
3.通过遍历的方式取得每一个字符
4.通过 (x-97+n)%26+97   /    (x - 65 + n)%26+65分成两类
5.拼接
"""
input_str = input()
out_str = ""
for char in input_str:
    input_chr = ord(char)
    if char.islower():
        out_chr = chr((input_chr - ord('a') + 3) % 26 + ord('a'))
    else:
        out_chr = chr((input_chr - ord('A') + 3) % 26 + ord('A'))
    out_str += out_chr
print(out_str)

8. Scoring questions (scoring according to rules)

"""
输入n个评委的成绩,去掉一个最高分,一个最低分,然后求平均值(保留两位小数)
100,95,60,80     ->    87.50
"""

num = input().split(",")  # 输入的是一个字符串
list = [int(x) for x in num]  # 将num中的每个数字拿出来,并且转换成数字型,将其放在一个列表中
list.remove(min(list))  # 去除最小值
list.remove(max(list))  # 去除最大值
# 对list的各个数字进行求和,再求平均
sum = 0
for k in list:
    sum += k
avr = sum / len(list)
print('{:.2f}'.format(avr))


# ----------------------------------------------------------------------------
# 亦或是实验中的
def c_a_s(s):
    if len(s) < 3:
        return 0
    s.sort()
    s = s[1:-1]

    a_s = sum(s) / len(s)

    return a_s
s_s = input()
s = [float(s) for s in s_s.split(',')]

a = c_a_s(s)
print("{:.2f}".format(a))

9. Judgment of palindrome number

# 通用型判断回文
def is_palindrome(num):
    return str(num) == str(num)[::-1]

print(is_palindrome("aba"))
print(is_palindrome(123456))
print(is_palindrome(1221))

# -------------------------------------
#亦或是实验中的
str_1 = input()
str_2 = str_1.replace(" ", "").lower()
# 对输入的字符串进行格式处理
# 1、去掉多余的空格
# 2、将全部转成小写以便判断
# 3、通过切片中--> [::-1]表示列表倒叙
is_palindrome = str_2 == str_2[::-1]

print(is_palindrome)

10. Prime number judgment and solution

"""素数是只有1和它本身两个因数的自然数"""
def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(num**0.5) + 1):
    # for i in range(2,num):
        if num % i == 0:
            return False
    return True

print(is_prime(17))
print(is_prime(28))

# ----------------------------------------------------------
#亦或是实验中的
"""
思路:
1、准备输入的接收
2、确保输入的数字是左小右大
3、定义函数来判断每个数是否是素数
4、判断依据是若这个数可以被这个范围的任意(不含1和本身)数整除既不是
5、用一个变量来接收遍历的字符串,得到素数字符串
6、将素数字符串用空格隔开输出
"""
m, n = map(int, input().split(","))
# 确保左小右大
if m > n:
    m, n = n, m


# 定义分函数来判断每个数是否是素数
def is_prime(num):
    if num < 2:
        return False
    # 利用一个数若存在除了1和其本身外还有因子
    # 这对因子一定在这个数一半的位置两侧的性质优化时间
    for i in range(2, int(num * 0.5) + 1):
        if num % i == 0:
            return False
    return True


# 准备一个str字符串来接收遍历整个范围中满足是素数的数,放到K中
k = [str(x) for x in range(m, n + 1) if is_prime(x)]

if len(k) == 0:
    print(-1)
else:
    print(" ".join(k))

11. Search specific numbers (according to certain requirements)

"""
类似于实验中的这题
编写一个程序。输入2个3位的正整数m,n 求他们之间的所有这些数字(均包括在内),这样数字的每个数字都是偶数。
"""

num_1, num_2 = map(int, input().split())
list = []
if num_1 > num_2:
    num_1, num_2 = num_2, num_1

for i in range(num_1, num_2 + 1):
    if (i // 100) % 2 == 0 and (i // 10) % 2 == 0 and (i % 2) == 0:
        list.append(i)
print(list)
list_2 = [str(item) for item in list] # 将list列表转换成字符串str,通过join进行拼接
print(",".join(list_2))

12. Can three line segments form a triangle?

def can_form_triangle(a, b, c):
    return a + b > c and a + c > b and b + c > a


# 通过用户自己输入
a, c, b = map(float, input().split(","))

print(can_form_triangle(a, b, c))

# 示例测试
print(can_form_triangle(1, 2, 3))
print(can_form_triangle(3, 4, 5))
print(can_form_triangle(1, 2, 2))

13. Solving the automagic numbers

# 自冥数应该是指一个n为数的各个位的位数次方之和等于其本身--简单说就是类似于水仙花数
# 水仙花数只是自幂数的一种,严格来说3位数的3次幂数才称为水仙花数。
def is_narcissistic_number(num):
    num_str = str(num)
    n = len(num_str)
    total = 0
    for digit in num_str:
        total += int(digit) ** n
    return total == num

narcissistic_numbers = []

for num in range(100, 1000):
    if is_narcissistic_number(num):
        narcissistic_numbers.append(num)

for number in narcissistic_numbers:
    print(number)
# ----------------------------------------------------------------------
# 简便式实现水仙花数
for i in range(100, 1000):
    (a, x) = divmod(i, 100)
    (b, y) = divmod(x, 10)
    c = y
    if a ** 3 + b ** 3 + c ** 3 == i:
        print(i)
    else:
        continue
# 解释 divmod(i,100) 商余函数等价于 i // 100 和 i % 100,(a,x)a为商,x为余
# -----------------------------------------------------------------------
# 简便式实现四叶玫瑰数
# for i in range(1000,10000):
#     (a,x) = divmod(i,1000)    #比如设i=5431 a=5,x=431
#     (b,y) = divmod(x,100)     #431  b=4,y=31
#     (c,z) = divmod(y,10)      #31   c=3,z=1
#     d = z
#     if a**4+b**4+c**4+d**4==i :
#         print(i)
#     else:
#         continue


Self-pickup of information (if it has expired, please leave a message. The self-pickup number in the information is wrong, see the above code for details)

Link: https://pan.baidu.com/s/1cL-twWWXOo0hL7yY_5NWaQ?pwd=tnay
Extraction code: tnay

Guess you like

Origin blog.csdn.net/qq_52495761/article/details/134637787