莫烦python基础教程(九)

模块

import 模块


import 的各种方法

  • import time 指 import time 模块,这个模块可以python自带,也可以是自己安装的,比如numpy这些模块需要自己安装。
import time
print(time.localtime())     # 这样就可以直接输出当地时间了

>>> 
time.struct_time(tm_year=2018, tm_mon=8, tm_mday=22, tm_hour=7, tm_min=32, tm_sec=13, tm_wday=2, tm_yday=234, tm_isdst=0)
  • 方法二:import time as 下划线缩写部分可以自己定义,在代码中把time 定义成 t。
import time as t
print(t.localtime())    # 需要前面加t前缀来引出功能

>>> 
time.struct_time(tm_year=2018, tm_mon=8, tm_mday=22, tm_hour=7, tm_min=34, tm_sec=54, tm_wday=2, tm_yday=234, tm_isdst=0)
  • 方法三:from time import time, localtime,只import自己想要的功能。
from time import time, localtime
print(localtime())
print(time())

>>> 
time.struct_time(tm_year=2018, tm_mon=8, tm_mday=22, tm_hour=7, tm_min=37, tm_sec=22, tm_wday=2, tm_yday=234, tm_isdst=0)
1534894642.8454053
  • 方法四:from time import * 输入模块的所有功能。
from time import *
print(localtime())

>>> 
time.struct_time(tm_year=2018, tm_mon=8, tm_mday=22, tm_hour=7, tm_min=39, tm_sec=1, tm_wday=2, tm_yday=234, tm_isdst=0)

自定义模块


自建一个模块

  • 自定义一个计算五年复利本息的模块,模块写好后保存在默认文件夹:balance.py。
d = float(input('Please enter what is your initial balance:\n'))
p = float(input('Please input what is interest rate(as a number):\n'))
d = float(d + d * (p / 100))
year = 1
while year <= 5:
    d = float(d + d * (p / 100))
    print("Your new balance agter year:", year, "is", d)
    year = year + 1
print('your final year is', d)

调用自己的模块

  • 新开一个脚本并import balance。
import balance

>>> 
Please enter what is your initial balance:
50000
Please input what is interest rate(as a number):
2.3
Your new balance agter year: 1 is 52326.45
Your new balance agter year: 2 is 53529.95834999999
Your new balance agter year: 3 is 54761.14739204999
Your new balance agter year: 4 is 56020.653782067144
Your new balance agter year: 5 is 57309.12881905469
your final year is 57309.12881905469

猜你喜欢

转载自blog.csdn.net/faker1895/article/details/81937329
今日推荐