1.
#建立一个module.py的模块
def c_to_f(celsius):
fa=celsius*9.0/5+32
return fa
#新建文件开始调用模块函数:
import my_module
celsius=float(input("enter a temperature in celsius:"))
fa=my_module.c_to_f(celsius)#这里的调用模块函数时候必须具体到文件名字。函数名字
print("that is",fa,"degree")
或者:
from my_module import c_to_f
celsius=float(input("enter a temperature in celsius:"))
print("that is",fa,"degree")
#导入模块的含义与导入一个命名空间是一样的。 导入模块时, 就导入了命名空间。
#如何把其他模块中的名字包含到你的命名空间,两种方法:
#第一种:导入空间名字,但是还要把要找的信息带上
import stephenleacock
call_to_office(stephenleacock.Fred)
#第二种:
from StephenLeacock import Fred
call_to_office(Fred)
#就不用带空间名字了。
#导入time模块中的函数部分
import time
time.sleep()
#导入time模块的sleep函数
或者另外一种方法:
from time import sleep
sleep()
#导入random模块:
import random
random.randint(1,100)#随机导入1-100的任意整数
random.random()#随机导入0-1的小数
random.random()*10#随机导入0-10的小数
#导入模块的全部:
from time import*
或者import time
2.编写一个小程序, 生成 1 到 20 之间的 5 个随机整数的列表, 并打印出来
import random
for i in range(5):
randomint=random.randint(1,20)
print(randomint)
3.4. 编写一个小程序, 要求它工作 30 秒, 每 3 秒打印一个随机小数。
import random
import time
for i in range(0,10):
random1=random.random()
time.sleep(3)
print(random1)
#课后答案:
import random,time
for i in range(0,10):
print(random.random())
time.sleep(3)