Python - 入门简单案例

这篇博客介绍了Python的基础应用,包括每隔3秒执行一次任务的实现,检查并写入文件内容的操作,以及如何打印出经典的九九乘法表。适合Python入门者学习。

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

  • 每3秒打印一次任务

'''
使用pip安装schedule包,并指定安装源
pip install -i http://mirrors.aliyun.com/pypi/simple/ schedule --trusted-host mirrors.aliyun.com
'''
#每3秒执行一次打印
import schedule
import time
a = 1
def djob(a):
    print("这是第{0}次执行".format(a))

schedule.every(1).seconds.do(djob,a)
while a<10:
    djob(a)
    time.sleep(3)
    a+=1
  • 判断文件是否存在,并写入内容

def mkdir(path):
    # 引入模块
    import os
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        print(path + ' 创建成功')
        return True
    else:
        # 如果目录存在则不创建,并提示目录已存在
        print(path + ' 目录已存在')
        return False

#Print text into the file
def print_to_file():
    fp = open('D:/test.txt','a+')
    print('Good~',file=fp)
    fp.close()

if __name__ == '__main__':
    mkdir('D:/test')
    print_to_file()

  • 打印九九乘法表

for i in range(1,10,1):
    for j in range(1,i+1,1):
        print(i,'*',j,'=',i*j,end='\t')
    print()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值