不得不说的python (time ,random, os) 模块巧用

1、time模块(import time)
1、time.sleep(n)

让程序休眠 n秒 再继续执行

 

2、time.time() # 返回一个数字
返回当前时间戳 -- 自计算机元年1970年1月1日0时0分0秒到当前时间的秒数
3、time.mktime((年,月,日,时,分,秒,0,0,0))
返回给定时间的时间戳
time1 = time.mktime((1980,5,20,10,10,10,0,0,0))
4、练习
1、现有一首歌曲信息要在大屏幕上缓慢显示,每隔2秒显示一条信息
歌曲信息:《绿光》
作词: 凡
作曲: 亮
演唱: 强

歌曲描述: 谨以此歌献给一同被绿的同志们

# import time


# print("歌曲信息:《绿光》")
# time.sleep(2)
# print("作词:凡")
# time.sleep(2)
# print("作曲:亮")
# time.sleep(2)
# print("演唱:强")
# time.sleep(2)
# print("歌曲描述:谨以此歌献给们")

2、输入打印次数n,在终端每隔1秒打印一次 hello world,共打印n次(也可用函数实现  for  while)

#方法1:for循环
# import time as t


# n = input("请输入打印次数:")
# if n.isdigit():
#     n = int(n)
#     for i in range(n):
#         print("hello world")
#         t.sleep(1)
# else:
#     print("输入不合法")


# while循环
# import time as t 
# n = input("请输入打印次数:")
# if n.isdigit():
#     n = int(n)
#     while True:
#         if n == 0:
#             break
#         print("hello world")
#         t.sleep(1)
#         n = n - 1
# 函数方法
# import time


# def p(n):
#     while True:
#         if n == 0:
#             return
#         print("hello world")
#         time.sleep(1)
#         n = n - 1


# p(4)

3、输入你的出生年月日,计算你的年龄

(time.time()、time.mktime((... ...)))

# 方法一
# import time


# year = input("请输入出生年份:")
# month = input("请输入出生月份:")
# day = input("请输入出生日期:")


# if year.isdigit() and month.isdigit() and day.isdigit():
#     year = int(year)
#     month = int(month)
#     day = int(day)
#     t1 = time.time()
#     t2 = time.mktime((year,month,day,0,0,0,0,0,0))
#     t3 = t1 - t2
#     age = t3 // (3600*24*365)
#     print("您的年龄为:%d岁" % age)
# else:
#     print("输入不合法")


# 方法二
# import time


# def age(year,month,day):
#     t1 = time.time()
#     t2 = time.mktime((year,month,day,0,0,0,0,0,0))
#     t3 = t1 - t2
#     ages = t3 // (3600*24*365)
#     print(ages)


# age(2017,1,1)

2、os模块(operator system)
1、常用方法
1、os.getcwd()
获取当前所在路径
2、os.chdir("路径")
切换路径/目录
3、os.listdir("目录名")
1、以列表形式显示目录中的内容
2、每一个文件/目录都是以字符串的方式存放于列表中
4、os.mkdir("目录名")
创建一个目录
5、os.system("Linux命令")
执行Linux命令
6、os.path.exists("文件名/目录名")
判断一个 文件/目录 是否存在,返回值 True / False


2、练习
1、写一个程序,输入一个文件夹名称,在用户主目录下创建它,并在此文件夹内创建如下目录树
if not os.path.exists("/home/tarena/music"):
输入文件夹名称(假如说输入的是:music)
|
+------------------+-------------------+
|                  |                   |
top500(文件夹)   流行歌曲(文件夹)    经典怀旧(文件夹)
|
+----------+
|          |
绿光.mp3   差不多先生.mp3

 

最后以列表形式列出 music 目录下的所有内容

# import os


# dname = input("请输入目录名:")
# s = "/home/tarena/" + dname
# if not os.path.exists(s):
#     os.mkdir(s)
#     os.chdir(s)
#     os.mkdir("top500")
#     os.mkdir("流行歌曲")
#     os.mkdir("经典怀旧")
#     os.chdir(s + "/流行歌曲")
#     os.system("touch 绿光.mp3 差不多先生.mp3")
#     print(os.listdir(s))
# else:
#     print("目录已存在")

3、random模块
1、random.choice(序列)
2、random.randint(m,n)
3、random.sample(序列,n)
从 序列 中随机抽取n个字符或元素
4、示例
1、字符串
chars = "AACDEF"
pwd = random.sample(chars,3)
2、列表
L = ["红桃A","黑桃2","梅花9","方片10","黑桃Q"]
pkp = random.sample(L,3)
"连接符".join(L)
"".join(L)


3、练习
1、用random模块和string模块来完善随机生成n位密码的程序

"密码"

# import random
# import string


# def randpass(n):
#     all_chars = string.ascii_letters + \
#                 string.digits + "_"
#     lpwd = random.sample(all_chars,n)
#     spwd = "".join(lpwd)


#     return spwd


# print(randpass(8))
# print(randpass(6))


# 方法二
# import random
# import string


# def randpass(n):
#     all_chars = string.ascii_letters + \
#                 string.digits + "_"
#     lpwd = random.sample(all_chars,n)
#     spwd = ""
#     for i in lpwd:
#         spwd += i


#     return spwd


# print(randpass(8))
# print(randpass(6))

4、练习1
给你的孩子写一个随机生成50以内的加减法的程序,共n道题,
如果答对了提示正确
如果答错了提示错误,正确答案是?
测试完成后告知一共做了?道题,错了?道
1、用到的模块
1、import random
2、import operator
operator.add(3,8) # 11
operator.sub(5,2) # 3
2、思路
1、利用random.ranint(1,50)随机生成2个数字
2、利用random.choice("+-")随机选择运算符
3、将随机生成的两个数放到列表里,排序方法
L.sort(reverse=True)
4、利用operator.add(..)或者operator.sub(..)算出正确答案
5、和正确答案比较
6、添加计数功能       ### L = [15,30]  L[0]=15 L[1]=30 
3、用函数实现
def test(n):
correct = 0
wrong = 0
while (correct + wrong) < n:
......
......
5 + 3 = 8
正确
15 - 5 = 5

错误,正确答案是10

import random
import operator


def test(n):
    correct = 0
    wrong = 0
    L = []
    # 随机生成2个数字
    while (correct+wrong) < n:
        for i in range(2):
            num = random.randint(1,50)
            L.append(num)
        L.sort(reverse=True)
        # 随机生成运算符
        op = random.choice("+-")
        # 算正确答案
        if op == "+":
            answer = operator.add(L[0],L[1])
        elif op == "-":
            answer = operator.sub(L[0],L[1])
        # 和正确答案比较
        result = input("%d %s %d = " % (L[0],op,L[1]))
        if result.isdigit():
            result = int(result)
            if result == answer:
                print("正确")
                correct += 1
            else:
                print("错误,正确答案为:%d" % answer)
                wrong += 1
        else:
            print("错误,正确答案为:%d" % answer)
            wrong += 1
    print("共%d道题,答错%d道" % (n,wrong))


test(3)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值