Speaking of modules, there was an image that the processing contents were complicated such as numpy, datetime, pandas, but in fact it turned out to be quite easy to make.
A file (.py) in which multiple functions are written is divided into separate files and called.
** ① Cut and paste the function you want to move to another file (.py) **
** ② Call with the original file ** ʻImport filename` └ * File name does not require extension └ No need for () or (''). Not a method
** ③ Use of module **
Module name. Function name ()
└ Prefix the module name to the function name
└ No extension (.py) required
The file created in this ** ① is a module **. The file name (excluding .py) becomes the module name. Only this.
As an example, define the following function in the file before modularization. ① Greeting function konchiwa ② Function to find dog year birthdayDog
Move these two functions to another file and load them as a module.
main.py
def konchiwa(name):
print(f'{name}Hello!')
def birthdayDog(name, age="24"):
print(f'{name}Mr.{age}Happy birthday to you.')
dogyear = age*7
print(f'{name}Is dog year{dogyear}I'm old')
def validate(age):
if age<10:
return False
return True
print('It is a program to say hello and ask for a dog year.')
name = input('Please tell me your name:')
print('---------------------------')
konchiwa(name)
age = int(input('\n Please tell me your age:'))
if validate(age):
birthdayDog(name, age)
else:
print('Please enter the correct age')
** ▼ Split the greeting function **
hello.py
def konchiwa(name):
print(f'{name}Hello!')
** ▼ Split the function to find the dog year **
dog.py
def birthdayDog(name, age="24"):
print(f'{name}Mr.{age}Happy birthday to you.')
dogyear = age*7
print(f'{name}Is dog year{dogyear}I'm old')
def validate(age):
if age<10:
return False
return True
main.py
#Load the created module
import hello
import dog
print('It is a program to say hello and ask for a dog year.')
name = input('Please tell me your name:')
print('---------------------------')
hello.konchiwa(name)
age = int(input('\n Please tell me your age:'))
if dog.validate(age):
dog.birthdayDog(name, age)
else:
print('Please enter the correct age')
-Load: ʻimport module name -Use:
module name.function name ()`
Recommended Posts