栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python(4)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python(4)

1.打印 9 * 9乘法表:(for循环、while循环、单层循环)
格式:
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

#for循环(嵌套循环)
for i in range(1, 10):
    for j in range(1, i+1):
        print(i, "*", j, "=", i * j, end='t')
    print()

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

#单层循环
i = 1
j = 1
while i < 10:
    if j <= i:
        print(i, "*", j, "=", i * j, end='t')
        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]
# 1)
try:
    list_data = [1, 2, 3]
    list_data[3]
except IndexError:
    print("IndexError")
# 2)
try:
    tuple_data = (1, 2, 3)
    tuple_data[2] = 10
except TypeError:
    print("TypeError")
# 3)
try:
    dict_data = {1:2, 2:3}
    dict_data[3]
except KeyError:
    print("KeyError")

结果:

3.文件操作:
a.写文本文件:
一次写入多行内容
关闭文件
重新打开,往文件追加新的一行内容
b.读文件:
读取前三十字符所在的行

# a.写文本文件
file_obj = open("file1.txt", "w", encoding="utf-8")
file_obj.write("今天太阳好好n好开心nlyzyydsn")
file_obj.close()
# 追加写
file_obj = open("file1.txt", "a", encoding="utf-8")
file_obj.write("yq快快走")
file_obj.close()
# b.读文件
file_obj = open("file1.txt", "r", encoding="utf-8")
data = file_obj.readlines(30)
print(data)

结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/357404.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号