2018-08-06(模块,中)
2018-08-07 本文已影响0人
Liar_f95f
模块卡住了,不会把创建的文件放到根目录下,可能也是没找到根目录,明明放了,还是不行。
def hi():
print("回顾书本学习巩固,加油")
>>> hello.hi()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
hello.hi()
NameError: name 'hello' is not defined
2018-08-07(正确使用模块)
先在安装python的根目录下添加一个文件名为init.py,就算该文件为空也关系。
然后创建命名为hello模块并保存同一根目录下
def hi():
print("回顾书本学习巩固,加油")
再import这个这个命名模块,最后是(hello.hi)运行模块,出结果
>>> import hello
>>> hello.hi()
回顾书本学习巩固,加油
import 语句
想使用 Python 源文件,只需在另一个源文件里执行 import 语句,例如
>>> import sys
>>> sys.path
['C:/Users/ning/AppData/Local/Programs/Python/Python37', 'C:\\Users\\ning\\AppData\\Local\\Programs\\Python\\Python37\\Lib\\idlelib', 'C:\\Users\\ning\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\ning\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\ning\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\ning\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\ning\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages']
from…import
要导入模块 hello中的 hi 函数,使用如下语句:
.>>from hello import hi
这个声明不会把整个 hello 模块导入到当前的命名空间中,它只会将 hello 里的 hi单个引入到执行这个声明的模块的全局符号表。
加餐:一个函数练习
#计算帅气度
def handsome(IQ, Height ):
return IQ * Height
def who(name):
print("嘿", name)
who("宁爷")
I = 100
H = 170
print("IQ =", I, "Height =", H, "handsome =", handsome(I,H))
=== RESTART: C:/Users/ning/AppData/Local/Programs/Python/Python37/函数练习.py ===
嘿 宁爷
IQ = 100 Height = 170 handsome = 17000
>>>