2021-11-04py4

本文通过具体实例介绍了Python中for循环和while循环的应用,演示了如何打印9*9乘法表;探讨了异常处理的方法,展示了针对不同数据类型可能出现的错误及处理方式;最后,讲解了文件操作的基本方法,包括如何写入文本文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Py4
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循环来实现(嵌套循环)
    代码

for

for i in range(1, 10):
for j in range(1, i+1):
print(i, “*”, j ,"=", i * j, end=’ ')
print()

while

i = 1
while i <= 9:
j = 1
while(j <= i): # j的大小是由i来控制的
print(i, “*”, j, “=”, i * j , end=’\t’)
j += 1
print(’’)
i += 1

while i<=9:
if j<= i:
print(i, “*”, j, “=”, i * j,end=" ")
j+=1
else:
print()
i+=1
在这里插入图片描述

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]

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.写文本文件:
一次写入多行内容
关闭文件
重新打开,往文件追加新的一行内容
file_obj = open(“file1.txt”, “w”, encoding=“utf-8”)
str_data = file_obj.writelines(([“111111\n”, “2222222\n”, “3333333\n”, “444444\n”]))
file_obj.close()

file_obj = open(“file1.txt”, “a”, encoding=“utf-8”)
file_obj.write(“今天是星期六\n”)
file_obj.close()
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值