This is my first Python program (before that I've been just poking around with the interpreter itself). I took this opportunity to do some user input and play around with pickle
.
I tried to made a system that reads input from the user (a car's name, year of launch and price), and then gives the power of exporting or importing it to an external file.
Is there any way to make this looks better (something that bothered me was my printing function and my super simple regex)? Is there any way that I can make this more pythonic? I've read many articles with this "pythonic" idea, and as I'm moving from Java, I'm afraid I might be losing something.
Made with python 3 in mind.
Example of input is:
add
Mitsubishi Eclipse
1999
1300.00
Here is the code.
import re
import pickle
class Car():
def __init__(self, carName = None, year = None, cost = None):
self.carName = carName if carName is not None else "undefined"
self.year = year if year is not None else "undefined"
self.cost = cost if cost is not None else "undefined"
cars = []
canImport = True #can only import if has already exported before or at program start
def addNewCar():
""" Reads input from user and adds a new car to the current collection of cars.
Year/Cost numeric validation are deliberately ommited """
usr_input = input("Enter the car's name : (protip: if can enter the whole object by typing name/year/cost)\n-> ")
match = re.search(r"\w+/\w+/\w+", usr_input)
if match:
name, year, cost = splitCarAttributes(match)
else:
name = usr_input
year, cost = getCarAttributes()
cars.append(Car(name, year, cost))
def splitCarAttributes(attributes):
return attributes.group(0).split("/")
def getCarAttributes():
year = input("Enter the car's launching year:\n-> ")
cost = input("Enter the car's cost:\n-> ")
return year, cost
def printCars():
for i, car in enumerate(cars):
print("Car #{:d}\n{{\n\tname:{:s}\n\tyear:{:s}\n\tcost:{:s}\n}}\n---\n".format(i+1, car.carName, car.year, car.cost))
def importCars():
if not canImport
print("You don't have anything to import.\n\n")
return
fileObject = open('cars', 'rb')
importedCars = pickle.load(fileObject)
for car in importedCars:
cars.append(car)
canImport = False
printSuccess()
def exportCars():
fileObject = open('cars', 'wb')
pickle.dump(cars, fileObject)
cars = [] # clears cars
canImport = True
printSuccess()
def printSuccess():
print("\n\n--- Great success!\n\n")
def main():
opt = ""
while (opt != "exit" and opt != "q"):
opt = input("Would you like to:\n- import all data\n- export all data\n- print all cars\n- add a new car to the collection?\n-> ").lower()
if opt == "import":
importCars()
elif opt == "export":
exportCars()
elif opt == "add":
addNewCar()
printSuccess()
elif opt == "print":
printCars()
if __name__ == '__main__':
main()
Edit: I just realized I'm calling printSuccess()
in different contexts. Not gonna change the code now, just a heads up to clarify that I should move all to main()
and maybe do some exception handling, but that's no the point right now.
1 Answer 1
def printCars():
for i, car in enumerate(cars):
print("Car #{:d}\n{{\n\tname:{:s}\n\tyear:{:s}\n\tcost:{:s}\n}}\n---\n".format(i+1, car.carName, car.year, car.cost))
cars is a global variable: that should be avoided.
Use dictionaries
if opt == "import":
importCars()
elif opt == "export":
exportCars()
elif opt == "add":
addNewCar()
printSuccess()
elif opt == "print":
printCars()
should be a dictionary.
Also I feel like all your methods should be inside the car class as they are logically connected to it.
Explore related questions
See similar questions with these tags.