此Python版本为2.7,其他例子如下:
Python学习100例之1-10
Python学习100例之11-20
Python学习100例之21-30
Python学习100例之31-40
Python学习100例之51-60
Python学习100例之61-70
Python学习100例之71-80
Python学习100例之81-90
Python学习100例之91-100
41.模仿静态变量的用法
def varfunc():
var = 0
print('var = %d' % var)
var += 1
if __name__ == '__main__':
for _ in range(3):
varfunc()
class Static:
StaticVar = 5
def varfunc(self):
self.StaticVar += 1
print(self.StaticVar)
print(Static.StaticVar)
a = Static()
for _ in range(3):
a.varfunc()
print('\n')
42.学习使用auto定义变量的用法
num = 2
def autofunc():
num = 1
print('internal block num = %d' % num)
num += 1
for _ in range(3):
print('The num = %d' % num)
num += 1
autofunc()
print('\n')
43.模仿静态变量(static)另一案例
class Num:
nNum = 1
def inc(self):
self.nNum += 1
print('nNum = %d' % self.nNum)
if __name__ == '__main__':
nNum = 2
inst = Num()
for _ in range(3):
nNum += 1
print('The num = %d' % nNum)
inst.inc()
print('\n')
44.两个 3 行 3 列的矩阵,实现其对应位置的数据相加,并返回一个新矩阵
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
X = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
Y = [[5, 8, 1],
[6, 7, 3],
[4, 5, 9]]
Z = []
for i in range(len(X)):
Z.append([])
for j in range(len(X[i])):
Z[i].append(X[i][j] + Y[i][j])
print(Z, '\n')
45.统计 1 到 100 之和。
total = 0
for i in range(1, 100 + 1):
total += i
print("1 + 2 + 3 + ... + 99 + 100 = %d\n" % total)
46.求输入数字的平方,如果平方运算后小于 50 则退出
while True:
num = int(input("请输入一个数字:"))
square = num ** 2
print("%d² = %d" % (num, square))
if square < 50:
break
print('\n')
47.两个变量值互换
def exchange(number1, number2):
number1, number2 = number2, number1
return number1, number2
num1 = int(input("请输入一个数:"))
num2 = int(input("请输入一个数:"))
print("%d %d" % (num1, num2))
print("%d %d\n" % exchange(num1, num2))
48.数字比较
def compare(number1, number2):
if number1 > number2:
print("%d > %d\n" % (number1, number2))
elif number1 == number2:
print("%d = %d\n" % (number1, number2))
else:
print("%d < %d\n" % (number1, number2))
num1 = int(input("请输入第一个数:"))
num2 = int(input("请输入第二个数:"))
compare(num1, num2)
49.使用lambda来创建匿名函数
s = lambda x, y: x + y
print(s(1, 2), '\n')
50.输出一个随机数
import random
print(random.random()) 输入0-1之间的随机数
print(random.uniform(1, 20)) 输出1-20之间的随机数
print(random.randint(1, 20)) 输出1-20之间的随机整数
网友评论