I'm working on a program for a final in a class and I'm having some troubles with updating the created inventory. I've been able to get it to the point where I can do everything else in the code, but when I go to run the update section, nothing updates. I'd be really grateful for any help with this. All of my code is included below
class Automobile:
def __init__(self, make, model, year, color, mileage=0):
self._make = make
self._model = model
self._year = year
self._color = color
self._mileage = mileage
#classmethod
def make_vehicle(cls):
make = input('Enter vehicle make: ')
model = input('Enter vehicle model: ')
while True:
year = input('Enter vehicle year: ')
try:
year = int(year)
break
except ValueError:
print("Year must be a number", file=sys.stderr)
color = input('Enter vehicle color: ')
while True:
mileage = input('Enter vehicle mileage: ')
try:
mileage = int(mileage)
break
except ValueError:
print("Mileage must be an integer", file=sys.stderr)
return cls(make, model, year, color, mileage)
def add_Vehicle(self):
vehicle = Automobile.make_vehicle()
self.vehicles.append(vehicle)
def __str__(self):
return '\t'.join(str(x) for x in [self._make, self._model, self._year, self._color, self._mileage])
class Inventory:
def __init__(self):
self.vehicles = []
def add_vehicle(self):
vehicle = Automobile.make_vehicle()
self.vehicles.append(vehicle)
def viewInventory(self):
print('\t'.join(['','Make', 'Model','Year', 'Color', 'Mileage']))
for idx, vehicle in enumerate(self.vehicles) :
print(idx + 1, end='\t')
print(vehicle)
print("This is the Vehicle Inventory Program.")
inventory = Inventory()
while True:
print ("""
1.Add a Vehicle
2.Delete a Vehicle
3.View Inventory
4.Update Inventory
5.Export Inventory
6.Quit
""")
ans=input("What would you like to do? ")
if ans=="1":
#add a vehicle
inventory.add_vehicle()
elif ans=='2':
#delete a vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be removed: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
inventory.vehicles.remove(inventory.vehicles[item - 1])
print ()
print('This vehicle has been removed')
elif ans == '3':
#list all the vehicles
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
elif ans == '4':
#edit vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be updated: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
if Inventory().add_vehicle() == True :
inventory.vehicles.remove(inventory.vehicles[item - 1])
inventory.vehicles.insert(item - 1, Automobile)
print('This vehicle has been updated')
elif ans == '5':
#export inventory to file
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
f = open('vehicle_inventory.txt', 'w')
f.write('\t'.join(['Make', 'Model','Year', 'Color', 'Mileage']))
f.write('\n')
for vechicle in inventory.vehicles:
f.write('%s\n' %vechicle)
f.close()
print('The vehicle inventory has been exported to a file')
elif ans == '6':
#exit the loop
print('Thank you for utilizing the Vehicle Inventory Program. Have a nice day.')
break
else:
print('invalid')
As already mentioned in the comments, the if condition is wrong and also you are inserting the class Automobile. What you need probably is Automobile.make_vehicle(). So, update the code,
elif ans == '4':
#edit vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be updated: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
inventory.vehicles.remove(inventory.vehicles[item - 1])
inventory.vehicles.insert(item - 1, Automobile.make_vehicle())
print('This vehicle has been updated')
Related
I want it so that my current balance will be the as the amount withdrawn for the next loop.
Enter pin:123
1 – Balance Inquiry
2 – Withdraw
3 – Deposit
X – Exit
Enter your choice:2
Hi name1.
Your current balance is 50000
Enter amount to withdraw: 400
Transaction Successful
Your current balance is 49600
Enter pin:123
1 – Balance Inquiry
2 – Withdraw
3 – Deposit
X – Exit
Enter your choice:2
Hi name1.
Your current balance is 50000 *** Problem ***
Enter amount to withdraw:
This is currently my code. (sorry for the messy code as I am a beginner)
pin = [123, 456, 789]
balance = [50000, 2000, 500]
name = ["name1", "name2", "name3"]
def main():
while True:
pin_input = input('Enter pin:')
try:
n = int(pin_input)
except:
break
if n in pin:
print('1 – Balance Inquiry')
print('2 – Withdraw')
print('3 – Deposit')
print('X – Exit')
choice = input('Enter your choice:')
c = int(choice)
if choice == 'X':
print('Thank you for banking with us!')
break
else:
pol = pin.index(n)
if c == 1:
print(f'Hi {name[pol]}.')
print(f'Your current balance is {balance[pol]} ')
elif c == 2:
print(f'Hi {name[pol]}.')
print(f'Your current balance is {balance[pol]} ')
withdraw = int(input('Enter amount to withdraw: '))
if withdraw > balance[pol]:
print('Not enough amount')
else:
difference = balance[pol] - withdraw
print('Transaction Successful')
print(f'Your current balance is {difference}')
elif c == 3:
print(f'Hi {name[pol]}.')
print(f'Your current balance is {balance[pol]} ')
deposit = int(input('Enter amount to deposit: '))
sums = deposit + balance[pol]
print('')
print(f'Your current balance is {sums}')
main()
welcome to Python. I see what is your problem. When you handle the withdrawal you create a new variable and performed the subtraction you just displayed the new result and never updated it.
So to solve it you need to replace this code:
difference = balance[pol] - withdraw
print(f'Transaction Successful.\nYour current balance is {difference}')
with:
balance[pol] -= withdraw
print(f'Transaction Successful.\nYour current balance is {balance[pol]}')
I took the liberty to edit your code a bit and make it more "professional" but also so that you could read and understand it (I added comments for you to read).
pin = [123, 456, 789]
balance = [50000, 2000, 500]
name = ["name1", "name2", "name3"]
def main():
while True:
try:
pin_input = int(input('Enter pin:'))
except ValueError: #It's bad practice to leave it just as "except".
break
if pin_input in pin:
print('1 – Balance Inquiry')
print('2 – Withdraw')
print('3 – Deposit')
print('X – Exit')
choice = input('Enter your choice:')
#As you can see, I have removed the conversion because no one will care if it is int or str, it's happening behind the scene.
if choice == 'X':
print('Thank you for banking with us!')
break
#You don't need the else statement because if the choice would be 'X' it would automatically exit.
pol = pin.index(pin_input)
if choice == '1':
print(f'Hi {name[pol]}.\nYour current balance is {balance[pol]}') #Using \n to downline instead of using two prints.
elif choice == '2':
print(f'Hi {name[pol]}.\nYour current balance is {balance[pol]}') #Using \n to downline instead of using two prints.
withdraw = int(input('Enter amount to withdraw: ')) #Assuming the user will write an integer.
if withdraw > balance[pol]:
print('Not enough amount')
break # Let's just add that here (easier to read) and we don't need the else statement anymore.
balance[pol] -= withdraw
print(f'Transaction Successful.\nYour current balance is {balance[pol]}')
elif choice == '3':
print(f'Hi {name[pol]}.\nYour current balance is {balance[pol]}')#Using \n to downline instead of using two prints.
deposit = int(input('Enter amount to deposit: ')) #Assuming the user will write an integer. the user
sums = deposit + balance[pol]
print(f'\nYour current balance is {sums}') #\n instead of a whole print function.
if __name__ == "__main__": #Use this script as the main script.
main()
Nice work, keep up with this good job!
Also, I want to add my own way of creating an ATM machine. I hope that one day when you will learn and have more knowledge you would open this again and try to understand this. (This code will work only in py-3.10 or higher)
Code:
class ATM:
def __init__(self, pin) -> None:
self.pin = pin
def Balance(self) -> str:
return f"{data[self.pin][1]}, Your balance is: {data[self.pin][0]}"
def Withdraw(self) -> str:
try:
withdraw = int(input('Enter amount to withdraw: '))
if withdraw > data[self.pin][0]:
return f"{data[self.pin][1]}, Looks like you can't withdraw {withdraw}$ due to lower balance.\nYou can withdraw up to {data[self.pin][0]}$."
data[self.pin][0] -= withdraw
except ValueError:
return f"{data[self.pin][1]}, Looks like there was an error with your request to withdraw. Please try again."
return f"{data[self.pin][1]}, You've successfully withdrawn {withdraw}$. Your remaining balance is: {data[self.pin][0]}$."
def Deposit(self) -> str:
try:
deposit = int(input('Enter amount to Deposit: '))
data[self.pin][0] += deposit
except ValueError:
return f"{data[self.pin][1]}, Looks like there was an error with your request to deposit. Please try again."
return f"{data[self.pin][1]}, You've deposited {deposit}$ into your account. Your balance right now is {data[self.pin][0]}"
if __name__ == "__main__":
data = {
123 : [50000, "name1"],
456 : [2000, "name2"],
789 : [500, "name3"]
}
options = {
1 : "Balance Inquiry",
2 : "Withdraw",
3 : "Deposit",
'X' : "Exit"
}
running = True
while running:
try:
pin = int(input("Enter your pin: "))
if pin in data:
user = ATM(pin)
else:
print(f"User {pin} Doesn't exist. Please check your input and try again.")
continue
for key, value in options.items():
print(f"Press '{key}' for {value}")
while True:
action = input("Please enter your action: ")
match action:
case '1':
print(user.Balance())
break
case '2':
print(user.Withdraw())
break
case '3':
print(user.Deposit())
break
case 'X' | 'x':
running = False
break
case _:
print("This action doesn't exist. Please try again.")
continue
except ValueError:
print("There is an error in the given pin. Please try again.")
continue
I'm trying to write a code where there are a bunch of if statements in each function. I want to be able to use a variable from a previous function and then add that variable into another function.
Here is an example:
def main():
name = input('What is your name?')
age = int(input('What is your age?'))
number = int(input('What is your favourite number?'))
if number > 0:
print('Your favourite number is %d and it is positive.' % (number))
elif number < 0:
print('Your favourite number is %d and it is negative.' % (number))
else:
print('Your favourite number is %d and it is equal to 0.' % (number))
subtract()
def subtract():
salary = float(input('Enter your monthly salary.'))
expenses = float(input('Enter your monthly expenses'))
result = (salary - expenses)
if result < 0:
print('Save more!')
else:
print('Congratulations on saving!')
def final():
percentage = result / a
finalpercent = percentage * 100
if finalpercent == 0:
print('No money!!')
elif finalpercent < 50:
print('Getting there...')
else:
print('You have lots of money!!')
main()
What I want is to use the result variable from def subtract(): function in the def final(): function?
Make the result variable from the subtract function the return value of that function.
Something like this:
def main():
name = input('What is your name?')
age = int(input('What is your age?'))
number = int(input('What is your favourite number?'))
if number > 0:
print('Your favourite number is %d and it is positive.' % (number))
elif number < 0:
print('Your favourite number is %d and it is negative.' % (number))
else:
print('Your favourite number is %d and it is equal to 0.' % (number))
final(subtract()) # RESULT IS RETURNED BY SUBTRACT AND THEN USED BY FINAL AS PARAMETER
def subtract():
salary = float(input('Enter your monthly salary.'))
expenses = float(input('Enter your monthly expenses'))
result = (salary - expenses)
if result < 0:
print('Save more!')
else:
print('Congratulations on saving!')
return result
def final(result):
percentage = result / a
finalpercent = percentage * 100
if finalpercent == 0:
print('No money!!')
elif finalpercent < 50:
print('Getting there...')
else:
print('You have lots of money!!')
main()
Also the variable a is not defined in the final function, that will cause an error, so check that too :).
Use Global variable. Creating a Global variable means you could access that variable from any function or class.
def main():
name = input('What is your name? ')
age = int(input('What is your age? '))
number = int(input('What is your favourite number? '))
if number > 0:
print('Your favourite number is %d and it is positive.' % (number))
elif number < 0:
print('Your favourite number is %d and it is negative. ' % (number))
else:
print('Your favourite number is Zero.')
subtract()
def subtract():
global salary # Declaring salary as Global Variable
salary = float(input('Enter your monthly salary: '))
expenses = float(input('Enter your monthly expenses: '))
global result # Declaring result as Global Variable
result = (salary - expenses)
if result < 0:
print('Save more!')
else:
print('Congratulations on saving!')
final()
def final():
percentage = result / salary
finalpercent = percentage * 100
if finalpercent == 0:
print('No money!!')
elif finalpercent < 50:
print('Getting there...')
else:
print('You have lots of money!!')
main()
I convert those local variable salary and result using global keyword. so that I could use that two variables outside of that function.
Another Approach is to pass that variable as an argument by calling final function. Like this...
def main():
name = input('What is your name? ')
age = int(input('What is your age? '))
number = int(input('What is your favourite number? '))
if number > 0:
print('Your favourite number is %d and it is positive.' % (number))
elif number < 0:
print('Your favourite number is %d and it is negative. ' % (number))
else:
print('Your favourite number is Zero.')
subtract()
def subtract():
salary = float(input('Enter your monthly salary: '))
expenses = float(input('Enter your monthly expenses: '))
result = (salary - expenses)
if result < 0:
print('Save more!')
else:
print('Congratulations on saving!')
final(result, salary) # calling final function by passing it as argument
def final(result, salary):
percentage = result / salary
finalpercent = percentage * 100
if finalpercent == 0:
print('No money!!')
elif finalpercent < 50:
print('Getting there...')
else:
print('You have lots of money!!')
main()
I have been trying to resolve my script with no results. I can't get
the load data to display. It is saving in members.txt and can read
it manually if opened. If someone can give any other advice on the
script as a whole it would be greatly appreciated.
I have reasearced greatly changed script around still have no luck.
import os if 'file' in vars():
wk_dir = os.path.dirname(os.path.realpath('file')) else:
print('We are running the script interactively')
class playerCLass(object):
name = ""
phone = ""
number = 0
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
def setname(self, name):
self.name = name
def setphone(self, phone):
self.phone = phone
def setnumber(self, number):
self.number = number
def getname(self):
return self.name
def getphone(self):
return self.phone
def getnumber(self):
return self.number
def display_data(self):
print("")
print("Member information: ")
print("Name:", self.name)
print("Phone number:", self.phone)
print("Jersey number:", self.number)
def displayMenu():
print("===========Menu Selections===========")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Data.")
print("6. Load Data.")
print("9. Exit Program.")
print("")
return int(input("<<Selection>> "))
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
else:
x = 1
while x < len(players):
print(x)
x = x + 1
def addPlayer(players):
newName = input("Type in member's name to be added to the roster:")
newPhone = input("Type in the member's phone number:")
newNumber = int(input("Type in the member's jersey number:"))
players[newName] = playerCLass(newName, newPhone, newNumber)
return players
def removePlayer(players):
name = input("Enter member's name to be removed:")
if name in players:
del players[name]
else:
print("member's name not found in list: ")
return players
def editPlayer(players):
oldName = input("Enter the name you want to edit: ")
if oldName in players:
newName = input("Enter a new name: ")
newPhone = input("Enter new phone number: ")
newNumber = int(input("Enter new jersey number: "))
players[oldName] = playerCLass(newName, newPhone, newNumber)
else:
print("No such name in memory: ")
return players
def saveData():
filename = input("Filename to save: ")
print("Saving data...")
outFile = open(filename, "wt")
for x in players.keys():
name = players[int(x)].getname()
phone = players[int(x)].getphone()
number = str(players[x].getnumber())
outFile.write(name + "," + phone + "," + number + "\n")
print("Data saved.")
outFile.close()
def loadData():
players = {}
filename = input("Filename to load: ")
inFile = open(filename, "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, number = inLine.split(",")
players[name] = (name, phone, number)
print("Data Loaded Successfully.")
inFile.close()
return players
print("Welcome to the Team Manager")
players = {}
menuSelection = displayMenu()
print()
while menuSelection != 9:
if menuSelection == 1:
printPlayer(players)
elif menuSelection == 2:
players = addPlayer(players)
elif menuSelection == 3:
players = removePlayer(players)
elif menuSelection == 4:
players = editPlayer(players)
elif menuSelection == 5:
saveData()
elif menuSelection == 6:
loadData()
menuSelection = displayMenu()
print("Exiting Program...")
If your issue is specifically not getting printPlayer to work you can do
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
#Iterate through dictionary of player name and player object and call
#display data on each of them
else:
for name, player in players.items():
print(player.display_data())
If you then run the code and input according to the statements you wrote, you should get something like this.
Welcome to the Team Manager
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
No current members in memory.
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 2
Type in member's name to be added to the roster:Joe
Type in the member's phone number:123
Type in the member's jersey number:456
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
Member information:
Name: Joe
Phone number: 123
Jersey number: 456
None
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>>
So I originally completed this task with nothing but a few if, elif statements. But it was requested that I break the work of those statements out into a separate functions as an additional exercise. I need to acquire names to add to a list and have the ability to edit or remove the names. But Im struggling to have the functions return their output to the list.
Here is what I have so far
print("Roster Management")
def addplayer():
name=input("Enter new player name: ")
roster = [name]
list(roster)
roster.append(name)
def removeplayer():
name = input('Enter player for removal: ')
roster.remove(name)
def editplayer():
oldname = input('Enter name you want to edit: ')
newname = input('Enter new name: ')
[x.replace(oldname, newname) for x in roster]
while 1==1:
print('---------- Main Menu ------------')
print("Choose from the following options")
print('1. Display Team Roster')
print('2. Add Member')
print('3. Remove Member')
print('4. Edit Member')
print('9. Exit Program')
print(" ")
selection = input("Enter Selection: ")
if selection == '1':
for x in roster:
print(roster)
elif selection == '2':
addplayer()
elif selection == '3':
removeplayer()
elif selection == '4':
editplayer()
elif selection == '9':
print("Closing program...")
break`enter code here`
There're few things that are wrong with your code:
#1
roster = [name] # this creates a new list with a single element in it instead of appending to some existing list
list(roster) # you're trying to convert a list to a list, so not needed
roster.append(name) # you should've some local/global roaster to append to
#2
def removeplayer():
name = input('Enter player for removal: ')
roster.remove(name) # again, you should've some local/global roaster to append to
#in case of local you should return the list for further usage, in case of global you can simply remove
#3
[x.replace(oldname, newname) for x in roster]
# again you're neither updating any existing list/ nor returned anything
# also check if `x==oldname` then replace with new name
#4
for x in roster:
print(roster) # x is what you should be printing, not the whole list (roaster)
So, your updated code with these changes would be something like this:
roster = []
def addplayer():
name=input("Enter new player name: ")
roster.append(name)
def removeplayer():
name = input('Enter player for removal: ')
roster.remove(name)
def editplayer():
global roster
oldname = input('Enter name you want to edit: ')
newname = input('Enter new name: ')
roster = [newname if x == oldname else oldname for x in roster]
print("Roster Management")
while 1==1:
print('---------- Main Menu ------------')
print("Choose from the following options")
print('1. Display Team Roster')
print('2. Add Member')
print('3. Remove Member')
print('4. Edit Member')
print('9. Exit Program')
print(" ")
selection = input("Enter Selection: ")
if selection == '1':
for x in roster:
print(x)
elif selection == '2':
addplayer()
elif selection == '3':
removeplayer()
elif selection == '4':
editplayer()
elif selection == '9':
print("Closing program...")
break
Add
return list
at the end of your definition because right now the definition doesn't know what it is supposed to return. Also in your, if statement you should have
print(def())
instead of just
def()
Hope this helps
ok so this is my program so far to operate as an ordering system of a cafe with multiple items. My goal is to calculate the price of an order, store that order to keep count of which coffee was ordered and how many of that coffee was ordered. Right now I am stuck on calculating the order total for an order. The main problem im stuck on is getting the coffee price of a coffee based on what the user wants, say if i want x coffee, i need to get the price of that coffee. I've stored instances of coffee in an array and right now I am not sure of how to get the price of a coffee to be used in the calculation of the total price
class Coffee(object):
def __init__ (self, coffee_type, price):
self.coffee_type = coffee_type
self.price = price
class Order(object):
def __init__(self, coffee_type, coffee_amount):
self.coffee_type = coffee_type
self.coffee_amount = coffee_amount
if name =="main":
coffee_available=[Coffee("1 : Flat White", 3.50),
Coffee("2 : Long Black", 3.50),
Coffee("3 : Cappuccino", 4.00),
Coffee("4 : Espresso", 3.25),
Coffee("5 : Latte", 3.50)]
ordering = 'Y'
total_cost = 0
while ordering == 'Y':
print("Coffee Type\t\tPrice")
print("-----------\t\t-----")
for coffee in coffee_available:
print("{}\t- - -\t$ {}".format(coffee.coffee_type,coffee.price))
print()
order_coffee = int(input("What is the number of the coffee you want? "))
order_amount = input("How many would you like to order? ")
new_order = None
if order_coffee >= 1 and order_coffee <=5:
coffee_choice = coffee_available[coffee.price]
new_order = Order(coffee_choice, order_amount)
total_cost = new_order.coffee_type * order_amount
else:
print ("Please enter a valid number")
dine_in = input('You like to dine in? (Y/N)')
dine_in = dine_in.upper()
if dine_in == 'Y' or 'YES':
total_cost = total_cost + (total_cost * 0.1)
print (total_cost)
Ordering = 'N'
elif dine_in == 'N' or 'No':
total_cost = total_cost
else:
print("Please enter a valid input")
continue
It's better to split the id of the coffee from the name:
class Coffee(object):
def __init__ (self, coffee_id, coffee_type, price):
self.coffee_id = coffee_id
self.coffee_type = coffee_type
self.price = price
Then when you create object use:
Coffee(1, "Flat White", 3.5)
And when you want the price use:
def get_price(coffee_available, coffee_id):
for coffee in coffee_available:
if coffee.coffee_id == coffee_id:
return coffee.price
return None