【问题标题】:Saving output of a function as a variable and using it in another function将函数的输出保存为变量并在另一个函数中使用
【发布时间】:2016-06-11 19:50:37
【问题描述】:

我是编程新手,所以这个问题可能很愚蠢。

我需要将Tr1 的值引入Bzero1 函数。当我运行模块时,我得到以下结果:

程序没有运行Bzero1 函数,我不知道为什么。是因为我没有正确引入Tr1 值还是其他原因?我希望Bzero1 执行0.083-(0.422/Tr1**1.6) 操作,Tr1T/Tc1 的结果中获得。

非常感谢您的帮助。

T = float(input("Introduce system temperature in Kelvin: ")) 
print("System temperature is: ", T)

Tc1 = float(input("Introduce critical temperature of component 1: ")) 
print("Critical temperature of component 1 is: ", Tc1)

def Tr1(T, Tc1):
  print("Relative temperature 1: ", T/Tc1)

Tr1 = Tr1(T, Tc1)

def Bzero1(Tr1):
  print("Bzero 1: ", 0.083-(0.422/Tr1**1.6))

【问题讨论】:

  • 你永远不会调用Bzero1函数。
  • 您还将名称 Tr1(一个函数)` 替换为该函数的返回值。但是您的函数从不显式返回任何内容,因此您最终会将Tr1 设置为Noneprint() 写入您的控制台或终端,它不会返回任何内容供您分配给变量。
  • 请不要链接到重要信息的截图。将信息作为文本包含在您的问题中。
  • 无论是文本还是文本的 .jpg 都是不敬的;感谢您提供一些东西来显示您得到的输出......
  • 你将不得不解释更多你想要发生的事情,因为你的代码中有几个逻辑错误。您希望函数Tr1 返回结果吗?如果是这样,这个结果应该是什么? T/Tc1?

标签: python function parameter-passing


【解决方案1】:
  1. 不要替换Tr1函数值,避免这样的替换变化:

    Tr1_value = Tr1(T, Tc1)
    
  2. 使用代码调用Bzero1函数:

    Bzero1(Tr1_value)
    
  3. 修改Tr1为返回值:

    def Tr1(T, Tc1):
        result = T/Tc1
        print("Relative temperature 1: ", result)
        return result
    

另外,我建议你看看python official tutorial - 在那里你可以学到很多关于 python 的知识......

祝你好运!

【讨论】:

  • 目前 OP 的 Tr1 函数不返回任何内容,因此您的 Tr1_value 始终是 None,这可能不是 OP 想要的。
  • 非常感谢。我会看看那个教程,因为我刚刚开始。
【解决方案2】:

def 只是定义一个函数,而不是调用它。例如

def foo(a):
    print a * 2

表示现在有一个函数foo 接受参数afoo(a) 中的 a 是函数内部的变量名称。

所以你的情况

def Bzero1(Tr1):
  print("Bzero 1: ", 0.083-(0.422/Tr1**1.6))

将函数 Bzero1 定义为接受参数 Tr1,但不调用它。你需要调用函数,就像你调用Tr1

Bzero1(Tr1)

您可以看到,通过这种方式,您很快就会混淆哪些是函数外部的变量,哪些是函数内部的变量。因此,最好在外部程序 vs. 中为变量使用不同的名称。那些内部函数。

以下是一些您可能会觉得有用的最佳实践:

  • 通常最好先定义所有函数,然后执行程序的主代码,而不是混合函数定义和主程序。

  • 另一个最佳实践是让函数只计算输入的输出,并在其他地方处理输出。这样,您就可以在程序的其他部分重用您的函数,同时始终控制向用户输出的时间和内容。

  • 最后,您通常不应该重新分配名称,例如Tr1 = Tr1(...) 表示 Tr1 现在不再是函数的名称,而是 Tr1 返回的结果的名称。简而言之,为不同的事物使用不同的名称。

应用这些提示,您的代码可能如下所示:

# function definitions first
def Tr1(vt, vtc1):
  return vt/vtc1

def Bzero1(vtr1):
  return 0.083-(0.422 / vtr1 ** 1.6)

# get user input
T = float(input("Introduce system temperature in Kelvin: ")) 
print("System temperature is: ", T)

vTc1 = float(input("Introduce critical temperature of component 1: ")) 
print("Critical temperature of component 1 is: ", vTc1)

# run calculations
vTr1 = Tr1(T, vTc1)
vBz1 = Bzero1(vTr1)

# print output
print("Relative temperature 1: ", vTr1)
print("Bzero 1: ", vBz1)

注意

由于我不知道变量的语义含义,我只是使用小写字母 v 作为前缀 - 通常最好使用有意义的名称,如 temperaturetemp1temp2 等. 程序不是数学论文。

【讨论】:

  • Tr1 函数需要返回一些值,否则vTr1 将永远是None
猜你喜欢
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 2018-01-08
  • 2022-01-01
  • 2017-05-17
相关资源
最近更新 更多