1.打印 9 * 9乘法表:
格式:
1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
…
9 * 1 = 9 9 * 2 = 18 … 9 * 9 = 81
# 1. 使用for循环来实现(嵌套循环)
# 2. 使用while循环来实现(嵌套循环)
# 3. 扩展: 使用单层循环(一层循环)
2.异常处理的使用:
- 列表超出索引: list_data = [1, 2, 3] => list_data[3]
- 定义一个元组: tuple_data = (1, 2, 3) => tuple_data[2] = 10
- 定义一个字典:dict_data = {1: 2, 2: 3} => dict_data[3]
3.文件操作:
a.写文本文件:
一次写入多行内容
关闭文件
重新打开,往文件追加新的一行内容
b.读文件:
读取前三十字符所在的行
for循环:
for i in range(1, 10):
for j in range(1, i + 1):
print(i, “", j, “=”, j * i, end=" ")
print()
while循环:
i = 1
while i <= 9:
j = 1
while j <= i:
print(i, "”, j, “=”, j * i, end=" ")
j += 1
i += 1
print()
单循环语句:
i = 1
j = 1
while i <= 9:
if j <= i:
print(i, "*", j, "=", i * j, end=" ")
j += 1
else:
print()
i += 1
j = 1
异常处理的使用:
list_data = [1, 2, 3]
try:
list_data[3]
except IndexError:
print(“a”)
tuple_data = (1, 2, 3)
try:
list_data[4]=10
except IndexError:
print(“b”)
dict_data = {1: 2, 2: 3}
try:
dict_data[3]
except KeyError:
print(“c”)
文件操作:
file_obj = open(“20211028.txt”, “w”, encoding=“utf-8”)
file_obj.write(“今天是10月28号.”)
file_obj.close()
file_obj = open(“20211028.txt”, “a”, encoding=“utf-8”)
file_obj.write(“明天是10月28日.”)
file_obj.close()
file_obj = open(“20211028.txt”, encoding=“utf-8”)
data = file_obj.read(30)
file_obj.close()
print(data)
print(bytes(data, encoding=“utf-8”))
运行结果:
1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81
a
b
c
今天是10月28号.明天是10月28日.
b’\xe4\xbb\x8a\xe5\xa4\xa9\xe6\x98\xaf10\xe6\x9c\x8828\xe5\x8f\xb7.\xe6\x98\x8e\xe5\xa4\xa9\xe6\x98\xaf10\xe6\x9c\x8828\xe6\x97\xa5.’