I'm quite new to python and I'm struggling to solve a problem, I have a text file with the name of the items and the price beside it, I'm tasked to multiply the price in the text file to a number in a variable or user input, for example, the user input 3, I need to multiply it to the price of the water and print it. how to do it? please help me.
this is the content of the text file
this is what I've done so far I've managed to print all the numbers but I don't know to choose only one number
with open("prac.txt") as r:
for line in r:
if line:
print(line.split(' ')[1])
this prints out 3 4 2 6 7
CodePudding user response:
You can do something like:
price=[]
item=[]
with open("textfile.txt") as r:
for line in r:
if line:
price.extend(line.split(' $')[1])
item.append(line.split(' $')[0])
price=list(filter(lambda x: x != '\n', price))
a=dict(zip(item,price))
now you have a dictionary with key as item names and you can access and multiply whatever prices you want, eg- for multiplying water price by 3 you can do:
print(int(a.get('water'))*3)