简体   繁体   English

Function 正确定义并正常工作,但未在终端中打印结果

[英]Function properly defined and working but not printing results in terminal

I recently wrote a simple function that gets the present value of an asset, the function PV works properly and I have tested it.我最近写了一个简单的 function 来获取资产的现值,function PV 工作正常,我已经对其进行了测试。 The function prints well in my pv file. function 在我的 pv 文件中打印效果很好。 However, when I run this code in the main file it does not print the output to the terminal and just closes after taking the inputs.但是,当我在主文件中运行此代码时,它不会将 output 打印到终端,而是在输入后关闭。 Is there a reason for this?是否有一个原因? For reference the functions just perform some simple mathematics problems.作为参考,这些函数只执行一些简单的数学问题。

Below is a minimal reproduction, both files are in the same folder.下面是一个最小的复制,两个文件都在同一个文件夹中。 in file_x you have a function that works like this:在 file_x 你有一个 function 像这样工作:

def func(w,x,y,z):
    z1 = w/(1 + (x/100))**(y*z)
    print(z1)
    return 0

this function is then imported into another file which is written like so然后将此 function 导入到另一个文件中,如下所示

from file_x import func

w = int(input("Future Value: "))
x = float(input("ROR: "))
y = float(input("# of periods: "))
z = float(input("# of payment per anum: "))

func(w,x,y,z)

My problem is that when I run the 2nd file it takes the inputs properly but does not print the result from the function.我的问题是,当我运行第二个文件时,它会正确输入输入,但不会打印 function 的结果。 Hope it was explained properly希望解释得当

In interactive mode an unused expression (here PV(w,x,y,z) which does returns a value and that value is not used) is printed to the terminal, because it is a common way to just display expression values.在交互模式下,未使用的表达式(此处为PV(w,x,y,z) ,它返回一个值但未使用该值)将打印到终端,因为这是仅显示表达式值的常用方法。

But when you run a script in a non interactive mode ( python script.py ) then those unused expression are just discarded.但是,当您以非交互模式( python script.py )运行脚本时,那些未使用的表达式将被丢弃。 As a general rule, you should never have such an unused expression in a script, because the behaviour will depend on the interactive mode of the interpretor.作为一般规则,您永远不应该在脚本中使用这种未使用的表达式,因为其行为将取决于解释器的交互模式。

So you should be explicit:所以你应该明确:

_ = PV(w,x,y,z)     # value will be discarded even in interactive mode

or或者

print(PV(w,x,y,z))  # value will be printed even in non interactive mode

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

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