Record#
Today I learned about splitting files and importing files.
When the code becomes too long, we should consider splitting it into different files. Different files can be called by each other using import filename
for importing, and there is no need to include the .py
extension here. To facilitate calling, you can also assign aliases to the imported files using the syntax import filename as alias
.
After importing the file, you can call the functions using either filename.functionname
or alias.functionname
.
Today's exercise is to split the previous code into separate files, and then import and call them.
When calling between different files, there is also the issue of passing parameters. This part may not be well understood yet and needs more attention in future studies.
CODE#
## main.py
import os, time, myLibary as lib
try:
f=open("gamelist.txt","r")
gamelist=eval(f.read())
f.close
except:
gamelist = []
while True:
time.sleep(1)
os.system("clear")
print("🌟RPG Inventory🌟")
menu=input("1: Add\n2: Remove\n3: View\n")
if menu == "1":
lib.gameadd(gamelist)
elif menu == "2":
lib.gameremove(gamelist)
elif menu == "3":
lib.gameview(gamelist)
else:
print("input error")
f=open("gamelist.txt","w")
f.write(str(gamelist))
f.close()
### myLibaty.py
def gameadd(gamelist):
gname = input("Input the item to add: > ").capitalize()
gamelist.append(gname)
print(f"{gname} has been added to your inventory.")
def gameremove(gamelist):
if gamelist:
gname=input("Input the item to remove: > ").capitalize()
if gname in gamelist:
gamelist.remove(gname)
print(f"{gname} has been removed from your inventory.")
else:
print(f"{gname} is not in the list.")
else:
print("The list is empty")
def gameview(gamelist):
if gamelist:
gname=input("Input the item to view: > ").capitalize()
if gname in gamelist:
gamenum = gamelist.count(gname)
print(f"You have {gamenum} {gname}.")
else:
print(f"{gname} is not in the list.")
else:
print("The list is empty")