Python函数仅在“print”功能下返回答案。

huangapple go评论65阅读模式
英文:

Python function returns answer only under "print" feature

问题

我正在尝试运行以下代码,但除非我添加"print",否则它不会返回任何内容。我在这里看到了一个类似的问题,并尝试检查是否与答案中描述的情况相同,但不幸的是我无法修复它。任何帮助都将不胜感激。

def compute_reference_eig(Neigen, exact=True, ref_solver=None):
    if exact:
        eigenvalues = []
        for i in range(Neigen+1):
            if (i%2)==0:
                eig = (i**2)*math.pi**2
            else: 
                eig = ((i-1)**2)*math.pi**2
            eigenvalues.append(eig)
        return eigenvalues[1::] # 返回 print('Exact Eigenvalues:\n', eigenvalues[1::])                             
    else: # 添加用于参考求解器的代码,当精确解不可用时。尚未实现。
        return None
    
compute_reference_eig(3, exact=True, ref_solver=None)
英文:

I am trying to run the below code but it doesn't return anything unless I add "print". I saw a similar issue question here and tried to check if it's the same as described in the answers but unfortunately I couldn't fix it. Any help is appreciated.


def compute_reference_eig(Neigen, exact=True, ref_solver=None):
    if exact:
        eigenvalues = []
        for i in range(Neigen+1):
            if (i%2)==0:
                eig = (i**2)*math.pi**2
            else: 
                eig = ((i-1)**2)*math.pi**2
            eigenvalues.append(eig)
        return eigenvalues[1::] #return  print('Exact Eigenvalues:\n', eigenvalues[1::])                             
    else: # add for reference solver when exact is unavailable. Yet to implement.
        return None
    
compute_reference_eig(3, exact=True, ref_solver=None)

答案1

得分: 1

以下是翻译好的部分:

似乎它返回了所需的结果,但您没有将结果存储在任何变量中。在最后一行中,您只是调用函数,如果没有任何打印语句,它将不会打印任何内容。您可能希望更改此行

compute_reference_eig(3, exact=True, ref_solver=None)

eigen_values = compute_reference_eig(3, exact=True, ref_solver=None)
print(eigen_values)
英文:

It seems that it returns the desired thing, but you are not storing the result in any variable. In the last line, you just call the function, which without any print statements won't print anything. You may want do change this line

compute_reference_eig(3, exact=True, ref_solver=None)

to

eigen_values = compute_reference_eig(3, exact=True, ref_solver=None)
print(eigen_values)

huangapple
  • 本文由 发表于 2023年6月29日 16:54:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定