[英]python shows none instead of empty space
I was trying a file handling exercise which converts temperature and writes it to a file.我正在尝试一个文件处理练习,它转换温度并将其写入文件。 The function part of my program is:
我的程序的功能部分是:
def c_to_f(c):
if c< -273.15:
pass #"That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
In the exercise instructions, is asked me to not write any message in the text file when input is lower than -273.15.在练习说明中,当输入低于-273.15 时,要求我不要在文本文件中写入任何消息。 ie for a set of values temperatures = [10,-20,-289,100] the desire output should be :
即对于一组值温度 = [10,-20,-289,100] 期望输出应该是:
50.0
-4.0
212.0
but I keep getting但我不断得到
50.0
-4.0
None
212.0
why is pass returning the "None" value instead of passing (doing nothing).为什么传递返回“无”值而不是传递(什么都不做)。
This is my main method:这是我的主要方法:
file = open("temp_file.txt", "w+")
for i in temperatures:
k = c_to_f(i)
file.write(str(k) + "\n")
file.close()
By default Python returns None
from functions if there is no return
statement.默认情况下,如果没有
return
语句,Python 从函数返回None
。
You can check to see if the value is None
before writing the output to the file with a conditional.在使用条件将输出写入文件之前,您可以检查该值是否为
None
。 Also note that using file handles not in a with
block is usually bad practice (see the docs ).另请注意,使用不在
with
块中的文件句柄通常是不好的做法(请参阅文档)。
with open("temp_file.txt", "w+") as file:
for i in temperatures:
k = c_to_f(i)
if k is not None:
file.write(str(k) + "\n")
When you assign k = c_to_f(i)
, what would you expect k
to be when the c_to_f
passes?当您分配
k = c_to_f(i)
,当c_to_f
通过时,您期望k
是多少? It's None
since you're not returning anything.它是
None
因为你没有返回任何东西。
You can just skip writing the line if it is None
.如果它是
None
您可以跳过编写该行。
for i in temperatures:
k = c_to_f(i)
if k:
file.write(str(k) + "\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.