How to make a python or fuction module and use it when writing other programs?

Where there are many cases where I have to write a large line of code again and again in several programs. so I was wondering if I could write only one program, save it, and then call it in different programs, such as a function or module.

Elementary example: - I am writing a program to check if a number is palindromic or not. Then I want to write a program to check if the number is palindromic prime, can I just call the first program and do the rest of the code to check if it is simple or not.

PS I'm just a beginner in python or in computer science, and I use IDLE to run all my python programs.

+4
source share
4 answers

It's about writing reusable code. I can suggest you write reusable code in a specific function in a separate python file and import this file and function too. For example, you need a function called sum in another function called "bodmas", then write the sum function in one python file, suppose that "allimports.py":

    def sum(a,b):
      return a+b

Now suppose your "bodmas" named function is some other python file, and then just import all the necessary functions, and you can usually call it by calling it.

    from allimports import sum
    def bodmas:
       print(sum(1,1))

, , . , , :

    import allimports
    print(allimports.sum(1,1))

    from allimports import *
    print(sum(1,1))

:

    from allimports import sum
    print(sum(1,1))
+2

. , palindrome.py. python .

import palindrome

, . , palindrome.py,

palindrome.is_palindrome('abba')

, palindrome.py . , , Python: https://docs.python.org/3/tutorial/index.html

+1
source

easy to write function in python.

first define the is_palindromic function,

def is_palindromic(num):
    #some code here
    return True

then define the is_prime function,

def is_prime(num):
    #some code here
    return True

finally, suppose you have number 123321, you can call the function above,

num = 123321
if is_palindromic(num):
    if is_prime(num):
        print 'this number is a prime!'

ps, maybe you could try using some editors like vscode or sublime.

+1
source

Source: https://habr.com/ru/post/1657389/


All Articles