简体   繁体   English

从另一个文件调用数学 Function 的问题

[英]Issue With Math Function Called From Another File

I'm currently working on a unit conversion calculator, and wanted to make it smoother by calling the math functions from a different file.我目前正在研究单位转换计算器,并希望通过从不同的文件调用数学函数来使其更流畅。 Currently, Celsius -> Fahrenheit (CF) is put in 'func.py', like this:目前,摄氏度 -> 华氏度 (CF) 放在“func.py”中,如下所示:

# This file has all the math functions that get called by main.py when needed.
# Also, VARIABLES!
num = 0
typ = 0

def CF():
  tota = (num * 9/5) + 32
  print("Answer: " + str(tota) + " degrees Fahrenheit")

And the code to call it in main.py looks like this:在 main.py 中调用它的代码如下所示:

if (typ == str('C-F')):
  num = int(input("Enter the temperature in Celcius: "))
  num = num
  CF()

I figure that I imported something wrong, but I've edited the import function several times now.我认为我导入了错误的内容,但我已经多次编辑导入 function。 I'm not looking for some type of complete correction, I wish for somebody to tell me what I did wrong, so that I can fix it.我不是在寻找某种类型的完全纠正,我希望有人告诉我我做错了什么,以便可以修复它。 I used repl.it, if it helps.如果有帮助,我使用了 repl.it。 Even if someone can tell me that it's possible, it'll help.即使有人可以告诉我这是可能的,它也会有所帮助。

I couldn't find anything on websites like GeeksforGeeks, which is my main source on research.我在像 GeeksforGeeks 这样的网站上找不到任何东西,这是我研究的主要来源。

You need to work with function parameters and returns (see this for a tutorial).您需要使用 function 参数并返回(请参阅教程)。

# func.py
def CF(num):
  return (num * 9/5) + 32
# main.py
if (typ == str('C-F')):
  num = int(input("Enter the temperature in Celcius: "))
  tota = CF(num)
  print("Answer: " + str(tota) + " degrees Fahrenheit")

This is very odd:这很奇怪:

def CF():

You're relying on num being defined at module scope within its module.您依赖于在其模块内的模块 scope 中定义的num Much better to spell it this way, so you're passing in an argument:这样拼写更好,所以你传递了一个论点:

def cf(num):

Over in main.py you're doing this, which isn't helpful:main.py中,您正在执行此操作,但没有帮助:

num = num

Much better to pass it in:更好地传递它:

cf(num)

The big concept you've been missing is you have two different modules, and each one has a num variable.你一直缺少的大概念是你有两个不同的模块,每个模块都有一个num变量。 They are different.它们是不同的。 Changing one won't automatically affect the other.改变一个不会自动影响另一个。

Use function parameters instead.请改用 function 参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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