import you own function in python

I’m not a good coder, so every time I need some new script for automation I just copy old code from the old script. It occurs to me that I should write my script in a more reusable way to avoid constantly copy and paste . This post will give a simple example for writing reusable code and import self-written function in python.

#! /usr/bin/python3

def hello(username="Anonymous"):
    print(f"Hello {username}")

def main():
    hello("Harry")
    hello()

if __name__ == "__main__":
    main()

This script simple say hello to user and give default username “Anonymous”. Below is the execution result.

#! /usr/bin/python

from sayhi import hello

def main():
    username = input("What's you name? ")
    if username == "":
        hello()
    else:
        hello(username)

if __name__ == "__main__":
    main()

Now we have another prog that ask user to provide their name. By import the hello function, we can greet user with their name. Below is the execution result.

The syntax for importing self-written function as below.

from <python_srcipt_name> import <function_name>

Leave a comment

Your email address will not be published. Required fields are marked *