Python教程

Python4

本文主要是介绍Python4,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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.异常处理的使用:

1) 列表超出索引: list_data = [1, 2, 3] => list_data[3]

2) 定义一个元组: tuple_data = (1, 2, 3) => tuple_data[2] = 10

3) 定义一个字典: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(j, "*", i, "=", i * j, end=" ")
    print()

# while嵌套循环
i = 1
while i <= 9:
    j = 1
    while j <= i:
        if i * j < 10:
            print(i, "*", j, "=", i * j, end=" ")
        else:
            print(i, "*", j, "=", i * j, end=" ")
        j += 1
    i += 1
    print()

# 单层循环
i = 1
j = 1
while i <= 9:
    if j <= i:
        print(j, "*", i, "=", i * j, end=" ")
        j += 1
    else:
        print()
        i += 1
        j = 1

# 2.异常处理的使用:
# 1) 列表超出索引: list_data = [1, 2, 3] => list_data[3]
# 2) 定义一个元组: tuple_data = (1, 2, 3) => tuple_data[2] = 10
# 3) 定义一个字典: dict_data = {1: 2, 2: 3} => dict_data[3]

try:
    list_data = [1, 2, 3]
    list_data[3]
except IndexError:
    print("IndexError")
try:
    tuple_data = (1, 2, 3)
    tuple_data[2] = 10
except TypeError:
    print("TypeError")
try:
    dict_data = {1: 2, 2: 3}
    dict_data[3]
except KeyError:
    print("KeyError")
# 3.文件操作:
# a.写文本文件:一次写入多行内容,关闭文件,重新打开,往文件追加新的一行内容
# b.读文件:读取前三十字符所在的行
file_obj = open("file1.txt", "w", encoding="utf-8")
str_data = file_obj.writelines((["周一\n", "周二\n", "周三\n", "周四\n", "周五\n", "周六\n", "周日\n"]))
file_obj.close()

file_obj = open("file1.txt", "a", encoding="utf-8")
file_obj.write("今天是星期三\n")
file_obj.close()

file_obj = open("file1.txt", "r", encoding="utf-8")
data = file_obj.readlines(30)
print(data)

运行结果

这篇关于Python4的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!