Importing functions from another file

Welcome to the lesson on importing functions from another file in Python. This is a powerful tool that allows you to organize and reuse your code more efficiently.

To import a function from another file, you first need to create a separate Python file that contains the function you want to import. Let's say you have a file called "my_functions.py" that contains a function called "add_numbers" and "subtract_numbers":

# my_functions.py

def add_numbers(num1, num2):
    print(num1 + num2)

def subtract_numbers(num1, num2):
    print(num1 - num2)

To import this function into the main.py Python file, you can use the following syntax:

from my_functions import add_numbers

This will import the add_numbers function from the my_functions.py file and allow you to use it in your current file.

You can also import multiple functions from the same file by separating them with a comma:

from my_functions import add_numbers, subtract_numbers

Once you have imported the function, you can use it just like any other function in your main.py file. For example, you could call the two functions like this:

add_numbers(5, 10)
subtract_numbers(5, 10)

Remember to always include the file path if your Python files are not in the same directory.

That's it for this lesson on importing functions from another file in Python. Practice using this technique to organize and reuse your code more efficiently.

Server Academy Members Only

Want to access this lesson? Just sign up for a free Server Academy account and you'll be on your way. Already have an account? Click the Sign Up Free button to get started..

0 0 votes
Lesson Rating
Subscribe
Notify of
profile avatar
0 Comments
Inline Feedbacks
View all comments

Saving Progress...

Sign up for free!

Sign up for free and get instant access to this course!.

Python 3 for Beginners

0%

0/1 Lessons

Installing Python on Windows

• 1hr 17min

0 / 4 lessons complete

Python Basics

• 28min

0 / 7 lessons complete

Python Variables

• 41min

0 / 8 lessons complete

Even more Python Variables!

• 41min

0 / 6 lessons complete

Conditional Statements

• 15min

0 / 3 lessons complete

Writing Functions

• 30min

0 / 5 lessons complete

Python Loops

• 23min

0 / 5 lessons complete

Python PIP and Modules

• 18min

0 / 4 lessons complete

RegEx

• 26min

0 / 4 lessons complete

Working with APIs

• 12min

0 / 3 lessons complete

Course Conclusion

• 2min

0 / 1 lessons complete