Search code examples
pythonfile-handlingnonetype

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. i.e for a set of values temperatures = [10,-20,-289,100] the desire output should be :

 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()

Solution

  • By default Python returns None from functions if there is no return statement.

    You can check to see if the value is None before writing the output to the file with a conditional. Also note that using file handles not in a with block is usually bad practice (see the docs).

    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")