[英]How do I Import a function from a different directory to my main code without getting a NameError?
I'm using Python 3.8.5.我正在使用 Python 3.8.5。 I was aiming at creating a simple addition function (and yes, I'm aware Python has an in-built one).
我的目标是创建一个简单的加法函数(是的,我知道 Python 有一个内置函数)。 I created the function satisfactorily, but wasn't able to import it to the program of my choice.
我令人满意地创建了该函数,但无法将其导入到我选择的程序中。 I keep getting NameErrors, saying that the name of my function has not been defined.
我不断收到 NameErrors,说我的函数名称尚未定义。 Here's the code to the function:
这是函数的代码:
def add_func(x, y):
sum = x + y
sum_str = str(sum)
print("The sum is " + sum_str)
And here's where the issues begin:这就是问题开始的地方:
import sys
import os
sys.path.append('C:\\Users\\User_name\\Desktop\\Folder\\PYTHON\\Functions')
import addition
x = (input("Enter no. 1: "))
y = (input("Enter no. 2: "))
add_func(x,y)
I have an init file in the folder named Functions.我在名为 Functions 的文件夹中有一个init文件。 I've scoured the web for hours searching for a solution to my problem, but have been unable to find one that: a) I can understand (still learning Python) b) Has worked
我已经在网上搜索了几个小时来寻找解决我的问题的方法,但一直找不到:a) 我能理解(仍在学习 Python)b) 已经奏效了
I'd really appreciate it if somebody could guide me on how to fix this issue, and explain to me what I've done wrong (dumb it down as much as possible)如果有人能指导我如何解决这个问题,并向我解释我做错了什么(尽可能把它写下来),我将不胜感激
If addition is the name of your .py file, and it has been successfully imported, then to use your add_func function you would need to write:如果 add 是您的 .py 文件的名称,并且已成功导入,则要使用 add_func 函数,您需要编写:
addition.add_func(x, y)
If you wanted to be able to use it without the addition., you can change the import statement to:如果您希望能够在不添加.的情况下使用它,您可以将导入语句更改为:
from addition import add_func
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.