Håller på med ett program där jag skall hämta data från en fil, bilmodell, förbrukning, kostnad osv. Jag har dock stött på ett problem jag inte lyckas lösa.
Kod: Markera allt
# Bilkostnad
# coding: utf-8
def openFile(fileName, mode):
''' Försöker öppna fil '''
try:
theFile = open(fileName, mode)
except:
print 'Det gick inte att öppna filen, avslutar programmet.\n'
sys.exit()
else:
return theFile
def nextLine(theFile):
''' Returnerar nästa rad från filen bilar '''
line = theFile.readline()
line = line.replace("\n", "")
return line
def nextBlock(theFile):
''' Returnerar nästa block, eller nästa "bil" och dess egenskaper '''
carmodel = str(nextLine(theFile))
price = int(nextLine(theFile))
gasconsumption = float(nextLine(theFile))
service = int(nextLine(theFile))
return carmodel, price, gasconsumption, service
def main():
use = int(raw_input('Hur mycket kommer bilen användas? (Km / år): '))
years = int(raw_input('Hur länge kommer den användas? (år): '))
gasPrice = float(raw_input('Vad är bränslepriset? (kr / liter): '))
carsFile = openFile("bilar.txt", 'r')
carmodel, price, gasconsumption, service = nextBlock(carsFile)
while carmodel:
print 'Totala kostnaden för en', carmodel, 'är: ', price + (use * gasPrice * gasconsumption) + (years * service)
carmodel, price, gasconsumption, service = nextBlock(carsFile)
carsFile.close()
main()
Kod: Markera allt
Volvo S60
200000
0.7
2000
BMW Z3
400000
1.2
3000
Mercedez Benz
500000
1.0
1000
Tack så mycket för hjälp