20230328Python final exam - short answer questions

Table of contents

1.

2.

3.


1.

# Implement a closure, implement mysum(1) = 1, mysum(2) = 3, mysum(3) = 6
def outer():
    def mysum(arg):
        if arg < 1:
            print("数值错误")
        elif arg < 2:
            print(1)
        elif arg < 3:
            print(3)
        elif arg < 4:
            print(6)
        elif arg >= 4:
            print("数值错误")
    return mysum


mysum = outer()
mysum(1)
mysum(2)
mysum(3)
'''
运行结果
1
3
6
'''

2.

Use list comprehension to realize the list, (the elements in the list are, if it is an even number between 1-10, it is the cube of the even number, if it is an odd number, it is an odd number and take the remainder of three)
result = [i*i*i if i % 2 != 1 else i % 3 for i in range(1, 11)]
print(result)


"""
运算结果
# 1  2  3  4  5  6  7  8  9  10
# [1, 8, 0, 64, 2, 216, 1, 512, 0, 1000]
"""

3.

# Use generator expression: generate 1-10 even numbers are unchanged, odd numbers are 0
def number(num):
    for i in range(1, num + 1):
        if i % 2 == 0:
            yield i
        else:
            yield 0

mun = number(10)
for i in mun:
    print(i)

operation result

"""
0
2
0
4
0
6
0
8
0
10
"""

Guess you like

Origin blog.csdn.net/2302_77035737/article/details/130870709