Jospeh.MCS Jospeh.MCS - 3 months ago 13
Python Question

multiply a number from a list and a number from a text file?

I am currently trying to multiply a number from a list with a number from a text file however I get the error=

Can't multiply sequence by non-int of type 'NonType'
,

Does anyone have a better method for doing this ?

text_file =open("read_it.txt", "r")
pricetxt=print(text_file.readlines()[2])
price1 = pricetxt*(items2[1])
print(price1)

Answer

The print() returns None and you are preserving it in pricetxt(). Also you need to convert the result which is a string to int (if it's a correct data). Also note that you better to use a with statement for opening the file, because it will close the file automatically at the end of the block.

with open("read_it.txt") as text_file:
    try:
        price = int(text_file.readlines()[2])
    except ValueError:
        # do something else
    else:
        new_price = price * items2[1]

Note that also items2[1] needs to be integer. If it's not you have to convert it to integer, which you can do it in try block after pricetxt.