By now, you have written some pretty big programs with lots of lines of code.
This can get pretty cumbersome to deal with. Lots of scrolling to find the right bit...
One of the ways to overcome this is to split the code into multiple files.
That's right. Your programs can consist of more than one Python file. The main file will always run first, but you can put parts of your code into other files and bring them into main.py by importing.
You've already done this whenever you've used import random
, import time
, import os
and so on. It's just that on those occasions, you were importing code written by someone else.
Today, you'll create your own code file and import it into your main program.
๐ Let's start with a basic 'count to 10' program in the main.py
file.
def count_10():
for i in range(10):
print(i+1)
Now, let's move the above code to a new file named 'test.py' and clear the main.py file.
Make sure that both the main and test files are in the same folder, then write the following lines of code in the main.py file.
import test as t
t.count_10()
this will print out the numbers 1 to 10 while we hit run in the main file, in this way, you can handle multiple files in Python. What you did now is create your library in Python and use functions stored in them.