Python practice example

Keywords: Python less

43. Imitate another case of static variable.

Program analysis: demonstrates a python scope usage method.

#python3.7

class Num:
    nNum = 1
    def inc(self):
        self.nNum += 1
        print('nNum = %d' % self.nNum)

if __name__ == '__main__':
    nNum = 2
    inst = Num()
    for i in range(3):
        nNum += 1
        print('The num = %d' % nNum)
        inst.inc()

 

44. Two 3-row and 3-column matrices to add the data of their corresponding positions and return a new matrix:

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]

Program analysis: create a new matrix of three rows and three columns, use for to iterate and take out the values of corresponding positions in the X and Y matrices, add them and put them in the corresponding positions of the new matrix.

#python3.7

X = [[12, 7, 3],
     [4, 5, 6],
     [7, 8, 9]]

Y = [[5, 8, 1],
     [6, 7, 3],
     [4, 5, 9]]

result = [[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]

#Iterative output line
for i in range(len(X)):
    #Iterative output column
    for j in range(len(X[0])):
        result[i][j] = X[i][j] + Y[i][j]

for r in result:
    print(r)

 

45. Count the sum of 1 to 100.

#python3.7

tmp = 0
for i in range(1, 101):
    tmp += i
print('The sum is %d' % tmp)

 

46. Find the square of the input number. If the square is less than 50, exit.

#python3.7

TRUE = 1
FALSE = 0
def SQ(x):
    return x * x
print('If the number entered is less than 50, the program will stop.')
again = 1
while again:
    num = int(input('Please enter a number:'))
    print('The operation result is:%d' % (SQ(num)))
    if SQ(num) >= 50:
        again = TRUE
    else:
        again = FALSE

 

47. The values of the two variables are interchanged.

#python3.7

def exchange(a, b):
    a, b = b, a
    return(a, b)

if __name__ == '__main__':
    x = 10
    y = 20
    print('x = %d, y = %d' % (x, y))
    x, y = exchange(x, y)
    print('x = %d, y = %d' % (x, y))

 

48. Numerical comparison.

#python3.7

if __name__ == '__main__':
    i = 10
    j = 20
    if i > j:
        print('%d greater than%d' % (i, j))
    elif i == j:
        print('%d Be equal to%d' % (i, j))
    elif i < j:
        print('%d less than%d' % (i, j))
    else:
        print('Unknown')

 

 

reference material:

Python 100 cases

Posted by Pascal P. on Mon, 09 Dec 2019 15:59:09 -0800