So long story short, I have been working on a Python program and I have been trying to get what the user inputs into the program to a txt file - I received some help online overall, but a bit stumped here.. Need it to include index, make, model, color, year and mileage of the vehicles that have been input (basically what is visible in the output when user hits "4" at main menu). The idea is when user hits "6" , that list/ data will be exported to txt file named "Vehicle Inventory" and then Exit the application. The issue is definitely around end of code at elif ch == 6: ... Any assistance or resolution on this would be appreciated !! Here is what I have so far:
# automobile class
class automobile:
# constructor
def __init__(self, make="", model="", color="", year=2018, mileage=0):
self.make = make
self.model = model
self.color = color
self.year = year
self.mileage = mileage
# setter methods
def set_make(self, make):
self.make = make
def set_model(self, model):
self.model = model
def set_color(self, color):
self.color = color
def set_year(self, year):
self.year = year
def set_mileage(self, mileage):
self.mileage = mileage
# getter methods
def get_make(self):
return self.make
def get_model(self):
return self.model
def get_color(self):
return self.color
def get_year(self):
return self.year
def get_mileage(self):
return self.mileage
# end of automobile class
# method to add a new vehicle to the inventory
def add_vehicle(v_list):
make = input("Enter make: ")
model = input("Enter model: ")
color = input("Enter color: ")
year = int(input("Enter year: "))
mileage = int(input("Enter mileage: "))
v = automobile(make, model, color, year, mileage)
v_list.append(v)
print("*** VEHICLE ADDED SUCCESSFULLY...")
# method to remove a vehicle from the inventory
def remove_vehicle(v_list):
index = int(input("Enter the index # of vehicle you would like to remove: "))
if index >= 0 and index < len(v_list):
make = v_list[index].get_make()
model = v_list[index].get_model()
v_list.pop(index)
print(make, model, "HAS BEEN REMOVED FROM INVENTORY !")
else:
print("*** INVALID INDEX #... PLEASE TRY AGAIN")
# method to update a vehicle info in the inventory
def update_vehicle(v_list):
index = int(input("Enter the index # of vehicle you would like to update: "))
if index >= 0 and index < len(v_list):
make = input("Enter new make: ")
model = input("Enter new model: ")
color = input("Enter new color: ")
year = int(input("Enter new year: "))
mileage = int(input("Enter new mileage: "))
v_list[index].set_make(make)
v_list[index].set_model(model)
v_list[index].set_color(color)
v_list[index].set_year(year)
v_list[index].set_mileage(mileage)
print("*** UPDATED SUCCESSFULLY !")
else:
print("*** INVALID INDEX #... PLEASE TRY AGAIN")
# method to print all vehicle details in proper formatted order
def display_vehicles(v_list):
print('{:10} {:10} {:10} {:10} {:10} {:10}'.format('INDEX #', 'MAKE', 'MODEL', 'COLOR', 'YEAR', 'MILEAGE'))
for i in range(len(v_list)):
v = v_list[i]
print('{:10} {:10} {:10} {:10} {:10} {:10}'.format(str(i), v.get_make(), v.get_model(), v.get_color(), str(v.get_year()), str(v.get_mileage())))
v_list = [] # initial list
# looping infinitely
while True:
# showing menu
print("1. Add a vehicle")
print("2. Remove a vehicle")
print("3. Update a vehicle")
print("4. Display all vehicle inventory")
print("5. Exit")
print("6. Export to 'Vehicle Inventory' txt file and Exit")
# getting choice
ch = int(input("*** PLEASE CHOOSE AN OPTION: "))
# performing actions based on choice
if ch == 1:
add_vehicle(v_list)
elif ch == 2:
remove_vehicle(v_list)
elif ch == 3:
update_vehicle(v_list)
elif ch == 4:
display_vehicles(v_list)
elif ch == 5:
break;
elif ch == 6:
with open('Vehicle Inventory.txt', 'w') as filehandle:
for display_vehicles in v_list:
filehandle.write("%s\n" % display_vehicles)
break;
else:
print("*** INVALID OPTION... PLEASE TRY AGAIN")
Executing your code, the txt file contains lines such as
<__main__.automobile object at 0x0000017F5E7017C0>.
The problem is that at line filehandle.write("%s\n" % display_vehicles) pass an object reference as data to be written to the file. As far as I know, there is no ready-made function that allows you to pass a file an object reference and have the data auto-extracted from it. If you really want to use a txt file, you can do something like this:
with open('Vehicle Inventory.txt', 'w') as filehandle:
for display_vehicles in v_list:
filehandle.write("make: {}, model: {}, color: {}, year: {}, mileage:{} \n".format(display_vehicles.get_make(),display_vehicles.get_model(),display_vehicles.get_color(),display_vehicles.get_year(),display_vehicles.get_mileage()))
Output
make: car, model: a, color: red, year: 2020, mileage:20
make: car2, model: b, color: black, year: 10, mileage: 10
A brief explanation of Format.
Format allows you to insert values into a string using a style based on placeholders. {} correspond to anonymous placeholders: this means that the value that goes in that position depends on the order used inside .format(value1, value2, ...).
Alternatively, you can use named placeholders such as:
"my car is {color} and i bought it in {year}".format(color= "red", year= 2010)
About the txt file
Personally I would not use a txt file, especially since loading data from this type of file can be quite annoying in cases where you are only interested in a few rows or a certain value of each row (e.g.: all red cars). I don't know if the txt file is mandatory for you, so I won't provide any detailed info on the following alternative methods. In any case, you should know that there are other types of files that are widely used for storing information.
Json. The data are stored into a dictionary, i.e. a set of key-value pairs. Reading and writing files is trivial thanks to the json module
Csv. This is very similar to a txt but has a more structured form, as if it were a table. Each row corresponds to a record, each record consists of columns. Thanks to pandas, it is easy to use csv to extract subsets of data based on the value contained in the records or the row index. The file structure also allows you to quickly create graphs and export data to Excel.
Pickle. If you don't even care about human-friendly representation but just want to save the data permanently to a file, you could try pickle
Related
am working on a restaurant project, and I need a hand :)
so the program will display the main dishes, and the user has to enter which dish he/she wants..
and then the choice will be taken and then added to the bill (dish name, price, num of items)...
so far I chose a dictionary so when the user enters 1 (key), the program will display Mashroum Risto...
this what've created:
dishes = {1 : ('Mashroum Risito', 3.950), 2 : ['Tomato Pasta', 2.250],3:['Spagehtie',4.850]}
now my question is how to get the dish name without the price (the price is 3.950) and extract it! and also how to get the price without the name so then I can send it into the bill function to calculate it? and if you have any suggestions please go ahead, because i don't know if using dictionary was the right choice
def MainDish():
dishes = {1 : ('Mashroum Risito', 3.950), 2 : ['Tomato Pasta', 2.250],3:
['Spagehtie',4.850]}
dishes.values
print("1. Mashroum Risito 3.950KD")
print("2. Tomato Pasta 2.250KD")
print("3. Spagehtie 4.850KD")
choice = eval(input('Enter your choice: '))
NumOfItem = eval(input('How many dish(es): '))
while(choice != 0):
print(dishes.get(choice)) #to display the item only without the
price
a = dishes.values()
recipient(a)
break
The way you have implemented it:
print (dishes[1][0]) #will give you name
print (dishes[1][1]) #will give you price
where [x][y]
x = key in the dict (input in your case)
y = element of the value in the dict (0 = name, 1=price in your case)
You should probably create the dictionary better as below:
Follow up question is not so clear but I think this is what you are after roughly. You will need to tweak the returns to your usage:
def MainDish():
NumOfItem = float(input('How many dish(es): '))
dish = list(dishes)[choice-1]
cost_of_dish = dishes[dish]
totalcost = cost_of_dish * NumOfItem
print (f"\n\tOrdered {NumOfItem}x {dish} at {cost_of_dish}KD each. Total = {totalcost}KD\n")
return dish, cost_of_dish, totalcost
dishes = {'Mashroum Risito': 3.950, 'Tomato Pasta': 2.250}
for key,val in dishes.items():
print (f"{list(dishes).index(key)+1}. {key}: {val}KD")
keepgoing = True
while keepgoing:
choice = int(input('Enter your choice: '))
if choice == 0:
keepgoing = False
break
else:
dish, cost_of_dish, totalcost = MainDish()
Working on a homework problem. Have almost all of the code working but for some reason cant seem to get my program to save and exit properly.
here is the prompt given.
You should create a program that manages a tab-separated text file containing employees travel expenses. There are 4 and only 4 employees who travel for the company: alice, bob, carl, and diane. Each record in the data file will contain an employee name, a destination city, miles traveled, and gallons used.
For full credit:
Your program should properly read and store the given data to and from the tab-separated data file. That is, I should be able to use your program with my data file without error.
When the data is read into your program it should be organized as a list of dictionaries, where each dictionary is a row in the file, using these dictionary keys: name, city, miles, gallons.
You need to add functionality to display the user's name, total miles traveled, total gallons used, average mpg, and the expense of the total miles at 75 cents per mile. This should work for any of the 4 proper user names you enter.
You do not need to do any data validation unless just want to.
If and only if your program runs exactly like it should, I will add a 10 point bonus if, rather than using concatenation, you properly use the python CSV module to read and write the data to and from the file, converting the tab-separated data to a dictionary and vice versa.
You need to use the base code provided by the lecture notes, more or less. All 4 menu options should work.
Use formatting to have everything line up in neat columns for display option 1.
My problem is that I cannot get the 4th option "Save and exit" to function properly.
def read_file(travels):
salesperson_list = []
with open("travels.txt", 'r') as infile:
for line in infile.readlines():
line = line.strip().split('\t')
d = {}
d['name'] = line[0]
d['city'] = line[1]
d['miles'] = eval(line[2])
d['gallons'] = eval(line[3])
salesperson_list.append(d)
return salesperson_list
def display_all_data(data):
print('{0:<8}{1:<15}{2:<8}{3:<8}'.format('Name', 'City', 'Miles', 'Gallons'))
for row in data:
print('{0:<8}{1:<15}{2:^8}{3:^8}'.format(row.get('name'), row.get('city'), \
row.get('miles'), row.get('gallons')))
def calculate_user_data(data):
name = input('Enter user name: ').lower()
total_miles = sum([row.get('miles') for row in data if row.get('name') == name])
total_gallons = sum([row.get('gallons') for row in data if row.get('name') == name])
cities = [row.get('city') for row in data if row.get('name') == name]
mpg = total_miles/total_gallons
owed = mpg*0.75
print('Total miles travelled: {0}'.format(total_miles))
print('Total gallons used: {0}'.format(total_gallons))
print('mpg = ',mpg)
print('expense = $', owed, 'at 75 cents per mile')
def add_a_trip(data):
name = input('Input name: ').lower()
city = input('Input city travelled: ').lower()
miles = eval(input('Enter miles travelled: '))
gallons = eval(input('Enter gallons used: '))
d = {}
d['name'] = name
d['city'] = city
d['miles'] = miles
d['gallons'] = gallons
data.append(d)
print('Data added successfully')
def save_And_exit(data):
with open('F:\\travels.txt','w') as outfile:
for row in data:
outfile.write(row.get('name')+'\t'+row.get('city')+'\t'+\
str(row.get('miles'))+'\t'+str(row.get('gallons'))+'\n')
print('Saved to file')
def menu(salesperson_list):
print('Menu options. Choose 1, 2, 3, or 4')
print('[1] Display all trip data')
print('[2] Calculate user data')
print('[3] Add a trip')
print('[4] Save an exit')
while True:
choice = input('Enter choice --> ')
if choice == '1':
display_all_data(salesperson_list)
elif choice == '2':
calculate_user_data(salesperson_list)
elif choice == '3':
add_a_trip(salesperson_list)
elif choice == '4':
save_And_exit(salesperson_list)
print('Bye')
break
else:
print('Invalid selection')
def main():
salesperson_list = read_file('F:\\travels.txt')
menu(salesperson_list)
main()
I just need my program to save and exit properly with no global variables
First of all, I would like to apologize to anyone if there was a similar topic, but I've been looking for a solution on this for hours now and couldn't find anything. Perhaps I don't know exactly how to ask the question. I am quite new to python and programming in general.
So my issue is the following. I am currently working on my first little "project" that is not just following a guide or an example program. What I am trying to do is create a list string from user input bit the list must have an integer value this is what I am trying:
s1 = []
product = []
menu = 1
while menu > 0:
print("1. Add employee.")
print("2. Add a product.")
print("3. Add a sale")
print("4. quit")
action = int(input("what would you like to do? Select a number: "))
if action == 1:
name = input("Employee name: ")
s1.append(name)
elif action == 2:
temp = input("Select the name of the product: ")
value = int(input("What is the price of the product: "))
int_temp = temp
product.append(int_temp)
temp = value
elif action == 4:
menu = -1
I also tried the following:
temp = input("Select the name of the product? ")
product.append(temp)
value = int(input("What is the price of the product? "))
product[-1] = value
But then it just replaces the string of the product with the integer of the input I can't seem to make it a list of strings that can be referenced later in a calculation. I hope I was clear enough in my explanation of my problem and goal.
Based on your comments i think you can use a dictionary instead of a list if you want to have a mapping of product name and product price. So the code would look like below
employees = []
products = {}
menu = 1
while menu > 0:
print("1. Add employee.")
print("2. Add a product.")
print("3. Add a sale")
print("4. quit")
action = int(input("what would you like to do? Select a number: "))
if action == 1:
name = input("Employee name: ")
employees.append(name)
elif action == 2:
product_name = input("Select the name of the product: ")
product_price = int(input("What is the price of the product: "))
products[product_name] = product_price
elif action == 4:
menu = -1
Then later in your code you can simply do like this.
sales = products['apples'] * 100
or
sales = products.get('apples', 0) * 100
Hope this helps !!
Your code contains some errors, which I have mentioned below. Remove them and try again
Remove print from your input statements:
Like change this line:
name = input(print("Employee name: "))
to this:
name = input("Employee name: ")
Before this line of code:
product.append(int_temp)
make sure the product list is initiated like:
product = list()
And this line below:
product[-1] = value
will change the last value in the product list since -1 will refer to the last index, -2 will refer to second last and so on.
I am trying to create a simple database on python that:
- Add a record, delete a record, report on the database
(I am very new to this program and programming in general)
*NOTE: I am aware there are programs like SQL but my professor wants us to create a a database simply with what we learned in class *
I am having serious trouble on being able to store: ID, Class Name, and Class instructor
into one record of "Classes". I have been able to display the class ID and class name but I'm not sure how to add an instructor's name.
This is what I have currently:
def print_menu():
print('1. Print Class Records')
print('2. Add a Class')
print()
classes = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = int(input("Type in a number (1-5): "))
if menu_choice == 1:
print("Class Reports:")
for x in classes.keys():
print("Class ID: ", x, "\tClass Name:", classes[x], "\tClass Instructor:",)
print()
elif menu_choice == 2:
print("Add ClassID, Class Name, and Instructor Name")
classID = input("ID: ")
className = input("Class Name: ")
classInst = input("Class Instructor: ")
classes[classID] = className
elif menu_choice != 5:
print_menu()
I feel that I will be able to do the rest of the professor's requirements for this project but I have been stuck on this part for days with no response from my professor
I would highly appreciate quick responses as this assignment is due tonight at 11:59 and I am reaching out for help here as a last resort.
Thank you!
In your case, what you can do is, insert the ID as a key for each class and then insert a dictionary as it's value. What I mean by this is that each key on the classes dict, points to another dictionary as its value.
elif menu_choice == 2:
print ("Add ClassID, Class Name, and Instructor Name")
classID = input("ID: ")
className = input("Class Name: ")
classInst = input("Class Instructor: ")
classes[classID] = {"className" : className, "classInst" : classInst}
and printing the values as
print("Class ID: ", x , "\tClass Name:" , classes[x]["className"] , "\tClass Instructor:" , classes[x]["classInst"])
The purpose of the two programs is to have twitter.py manage tweet.py by having the 5 most recent tweets that are saved in the program twitter.py to show up once you search and find it. There are four options, make a tweet, view recents tweets, search a tweet and quit. I'm having trouble saving because it keeps saying no recent tweets are found. Also I'm having trouble with the fact that I can't search for my tweets but that is probably the same reason as my first problem because they aren't being saved correctly. Thank you please help!!
tweet.py
import time
class tweet:
def __init__(self, author, text):
self.__author = author
self.__text = text
self.__age = time.time()
def get_author(self):
return self.__author
def get_text(self):
return self.__text
def get_age(self):
now = time.time()
difference = now - self.__time
hours = difference // 3600
difference = difference % 3600
minutes = difference // 60
seconds = difference % 60
# Truncate units of time and convert them to strings for output
hours = str(int(hours))
minutes = str(int(minutes))
seconds = str(int(seconds))
# Return formatted units of time
return hours + ":" + minutes + ":" + seconds
twitter.py
import tweet
import pickle
MAKE=1
VIEW=2
SEARCH=3
QUIT=4
FILENAME = 'tweets.dat'
def main():
mytweets = load_tweets()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == MAKE:
add(mytweets)
elif choice == VIEW:
recent(mytweets)
elif choice == SEARCH:
find(mytweets)
else:
print("\nThanks for using the Twitter manager!")
save_tweets(mytweets)
def load_tweets():
try:
input_file = open(FILENAME, 'rb')
tweet_dct = pickle.load(input_file)
input_file.close()
except IOError:
tweet_dct = {}
return tweet_dct
def get_menu_choice():
print()
print('Tweet Menu')
print("----------")
print("1. Make a Tweet")
print("2. View Recent Tweets")
print("3. Search Tweets")
print("4. Quit")
print()
try:
choice = int(input("What would you like to do? "))
if choice < MAKE or choice > QUIT:
print("\nPlease select a valid option.")
except ValueError:
print("\nPlease enter a numeric value.")
return choice
def add(mytweets):
author = input("\nWhat is your name? ")
while True:
text = input("what would you like to tweet? ")
if len(text) > 140:
print("\ntweets can only be 140 characters!")
continue
else:
break
entry = tweet.tweet(author, text)
print("\nYour tweet has been saved!")
def recent(mytweets):
print("\nRecent Tweets")
print("-------------")
if len(mytweets) == 0:
print("There are no recent tweets. \n")
else:
for tweets in mytweets[-5]:
print(tweets.get_author, "-", tweets.get_age)
print(tweets.get_text, "\n")
def find(mytweets):
author = input("What would you like to search for? ")
if author in mytweets:
print("\nSearch Results")
print("----------------")
print(tweet.tweet.get_author(), - tweet.tweet.get_age())
print(tweet.tweet.get_text())
else:
print("\nSearch Results")
print("--------------")
print("No tweets contained ", author)
def save_tweets(mytweets):
output_file = open(FILENAME, 'wb')
pickle.dump(mytweets, output_file)
output_file.close()
main()
In twitter.py:add_tweets, mytweets is passed into the function and entry is created, but it is never added to mytweets. The created entry is lost after the function returns.
Your question was:
I'm having trouble saving because it keeps saying no recent tweets are
found.
Function add does not seem to be adding tweets anywhere. It creates a tweet.tweet instance, but it does not do anything with it.
You probably want to add the tweet to mytweets?
Another problem:
You initialize mytweets as a dicionary (tweet_dct = {}), but later you use it as a list (mytweets[-5]). It should be a list from start. And you probably want last five tweets (mytweets[-5:]), not just the fifth from the end.
On the sidenotes:
What you have here is not "two programs" - it is one program in two python files, or "modules"
Although there is nothing wrong with having getters (functions like get_author), there is no need for them in Python (see How does the #property decorator work?). Do youself a favour and keep it simple, e.g.:
class Tweet:
def __init__(self, author, text):
self.author = author
self.text = text
self.creation_time = time.time()
def get_age_as_string(self):
# your code from get_age
There will be time when you need private variables. When that happens, use a single leading underscore (self._author) until you fully understand what double underscore does and why.
Pickle is probably not the best way to store information here, but it is a good start for learning.