简体   繁体   中英

Why can't I import my module into my main code?

I wrote some code (named exercise 2) where I define a function (named is_divisible) and it has worked perfectly.

Afterwards to learn how to import functions, I wrote the same code but without the defined function, and created a second module (named is_divisible). But whenever I import this module into the original "exercise 2" I get

No module named 'is_divisible'

I have checked that both python files are in the same folder, the name of the file is correct, and I know the code is well written because it has worked before and it is from a lecturer's of mine. I have also attempted to name the module and the function differently and to instead write:

from divis import is_divisible

but this was also unsuccessful.

Where am I going wrong? I will leave the code below:

import random
import math
import numpy as np

random_list=[]

for i in range (0,5):
    r=random.randint(0,10)
    random_list.append(r)

print(random_list) #five numbers from 0 to 10 are chosen and appended to a list


new_result=[print('right' for x in random_list if round(np.cosh(x)**2 - np.sinh(x)**2,2) == 1] 
#checking the numbers following a maths rule

import is_divisible  #trying to import the function is_divisible

divisor=3 
idx = is_divisible(random_list, divisor)
for i in idx:
    print(f'Value {random_list[i]} (at index {i}) is divisible by {divisor}')

the code for the function is_divisible is:

def is_divisible(x, n):
""" Find the indices of x where the element is exactly divisible by n.

Arguments:
x - list of numbers to test
n - single divisor

Returns a list of the indices of x for which the value of the element is
divisible by n (to a precision of 1e-6 in the case of floats).

Example:
>>> is_divisible([3, 1, 3.1415, 6, 7.5], 3)
[0, 3]

"""

r = []
small = 1e-6
for i, m in enumerate(x):
    if m % n < small:
        r.append(i)
return r

I know this question has been answered multiple times, but none of the answers seem to work for me or maybe I am not doing it correctly.

Generally, when you type import <Module> the module is the name of the file. So, if you had the function is_divisible inside a Python file named a.py , then to import it you will write from a import is_divisible . If instead, you would like to import the whole file, then you'd write import a.py , then to use the function you would use a.is_divisible(random_list, divisor) .

You should also make sure that both files are in the same folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM