Check element value of specific element in list - python

I'm working on an assignment covering classes. There are several requirements but my program meets nearly all of them the way it is currently.
The program is to prompt the user to enter either a car or truck into their virtual garage. From there they select a number of options depending on if it is a car or truck.
The user continues doing this until they are done adding vehicles, then they get prompted with the vehicles they entered and their info.
As it is currently, I can enter an endless amount of cars or trucks and it will print what I entered correctly. It will not allow me to enter in both cars and trucks, which is what I need it to do.
I know the issue is likely with my last loop since it references carTruck and it should probably reference the value of the element in the instances list. I am unsure how to do that though.
I realize there are probably better ways to achieve this but there are certain ways it must be done according to the assignment. Also, error handling isn't needed in this so that is why it is not included.
class Vehicle:
def __init__(self, make, model, color, fuelType,options):
self.make = make
self.model = model
self.color = color
self.fuelType = fuelType
self.options = options
def getMake(self):
self.make = input('Please enter the vehicle make: ').title()
return self.make
def getModel(self):
self.model = input('Please enter the vehicle model: ').title()
return self.model
def getColor(self):
self.color = input('Please enter the vehicle color: ')
return self.color
def getFuelType(self):
self.fuelType = input('Please enter the vehicle fuel type: ')
return self.fuelType
def getOptions(self):
optionslist = []
print('\nEnter Y or N for the following options')
radio = input('Does your vehicle have a radio: ').lower()
bluetooth = input('Does your vehicle have bluetooth: ').lower()
cruise = input('Does your vehicle have cruise control: ').lower()
window = input('Does your vehicle have power windows: ').lower()
lock = input('Does your vehicle have power locks: ').lower()
mirror = input('Does your vehicle have power mirrors: ').lower()
rstart = input('Does your vehicle have remote start: ').lower()
bcamera = input('Does your vehicle have a back up camera: ').lower()
if radio == 'y':
optionslist.append('Radio')
if bluetooth == 'y':
optionslist.append('Bluetooth')
if cruise == 'y':
optionslist.append('Cruise Control')
if window == 'y':
optionslist.append('Power Windows')
if lock == 'y':
optionslist.append('Power Locks')
if mirror == 'y':
optionslist.append('Power Mirrors')
if rstart == 'y':
optionslist.append('Remote Start')
if bcamera == 'y':
optionslist.append('Backup Camera')
self.options = optionslist
return self.options
#car child class
class Car(Vehicle):
def __init__ (self, make, model, color, fuelType,options, engineSize, numDoors):
self.engineSize = engineSize
self.numDoors = numDoors
Vehicle.__init__(self, make, model, color, fuelType,options)
def getEngineSize(self):
self.engineSize = input('Please enter your engine size in liters: ')
return self.engineSize
def getNumDoors(self):
self.numDoors = input('Please enter the number of doors: ')
return self.numDoors
#pickup child class
class Pickup(Vehicle):
def __init__ (self, make, model, color, fuelType,options, cabStyle, bedLength):
self.cabStyle = cabStyle
self.numDoors = bedLength
Vehicle.__init__(self, make, model, color, fuelType, options)
def getCabStyle(self):
self.cabStyle = input('Please enter the cab style: ')
return self.cabStyle
def getBedLength(self):
self.bedLength = input('Please enter the bed length: ')
return self.bedLength
#creates instance and loops to get info for vehicles from user
instances = []
Exit = 'n'
x = 0
while Exit == 'n':
carTruck = input('Are you entering a car or truck? ')
plateNum = input('please enter your license plate number: ')
instances.append(carTruck + plateNum)
#if statement to use correct class based on user input
if carTruck == 'car':
instances[x] = Car('','','','','','','')
instances[x].getMake()
instances[x].getModel()
instances[x].getColor()
instances[x].getFuelType()
instances[x].getEngineSize()
instances[x].getNumDoors()
instances[x].getOptions()
if not instances[x].options:
print('\nYou need to select at least one option.')
Vehicle.getOptions(instances[x])
elif carTruck == 'truck':
instances[x] = Pickup('','','','','','','')
instances[x].getMake()
instances[x].getModel()
instances[x].getColor()
instances[x].getFuelType()
instances[x].getCabStyle()
instances[x].getBedLength()
instances[x].getOptions()
if not instances[x].options:
print('\nYou need to select at least one option.')
Vehicle.getOptions(instances[x])
#allows user to stop adding vehicles
Exit = input('Are you done adding vehicles (Y/N): ').lower()
x = x + 1
#loops through instances and provides output dependent on whether it is a car or truck.
b = 0
while b < len(instances):
if carTruck == 'truck':
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].cabStyle} and a {instances[b].bedLength} ft bed that runs on {instances[b].fuelType}.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
elif carTruck == 'car':
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].numDoors} door with a {instances[b].engineSize} liter {instances[b].fuelType} engine.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
b = b + 1
Output:
Are you entering a car or truck? car
please enter your license plate number: 123456
Please enter the vehicle make: ford
Please enter the vehicle model: mustang
Please enter the vehicle color: red
Please enter the vehicle fuel type: gas
Please enter your engine size in liters: 5
Please enter the number of doors: 2
Enter Y or N for the following options
Does your vehicle have a radio: y
Does your vehicle have bluetooth: y
Does your vehicle have cruise control: y
Does your vehicle have power windows: y
Does your vehicle have power locks: y
Does your vehicle have power mirrors: y
Does your vehicle have remote start: y
Does your vehicle have a back up camera: y
Are you done adding vehicles (Y/N): n
Are you entering a car or truck? truck
please enter your license plate number: 789456
Please enter the vehicle make: chevy
Please enter the vehicle model: 1500
Please enter the vehicle color: black
Please enter the vehicle fuel type: gas
Please enter the cab style: crew cab
Please enter the bed length: 6
Enter Y or N for the following options
Does your vehicle have a radio: y
Does your vehicle have bluetooth: y
Does your vehicle have cruise control: y
Does your vehicle have power windows: y
Does your vehicle have power locks: y
Does your vehicle have power mirrors: y
Does your vehicle have remote start: y
Does your vehicle have a back up camera: y
Are you done adding vehicles (Y/N): y
Traceback (most recent call last):
File "c:\Users\chris\Desktop\School\Intro to Programming\python_work\classes.py", line 138, in <module>
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].cabStyle} and a {instances[b].bedLength} ft bed that runs on {instances[b].fuelType}.')
AttributeError: 'Car' object has no attribute 'cabStyle'
``

Before you read the answer, ask yourself where did you get the carTruck instance you are trying to print.
...
You are referring to the last entry you have added instead of referring to the current instance! So correct way will be, eg.
b = 0
while b < len(instances):
if isinstance(instances[b], Pickup): #CHANGED
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].cabStyle} and a {instances[b].bedLength} ft bed that runs on {instances[b].fuelType}.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
elif isinstance(instances[b], Car): #CHANGED
print(f'Your vehicle is a {instances[b].color} {instances[b].make} {instances[b].model} {instances[b].numDoors} door with a {instances[b].engineSize} liter {instances[b].fuelType} engine.')
print(f'The options are ' + ", ".join(instances[b].options) +'.\n')
b = b + 1
I want to add two suggestions...
1st - don't use while loop here use for, eg.
for moving_thing in instances:
if isinstance(moving_thing, Pickup):
...
2nd - create __str__ method for each class so you could call it without checking what type of vehicle it is. More here Dunder methods, than you could call
for moving_thing in instances:
print(moving_thing)

Related

How can i sort user input into a list based on conditionals

So im stuck on a homework problem, and i just need some guidance or criticism if what i have so far is wrong. But the prompt is to "Create a program that will create a clothing object. The clothing object must have the following
attributes: minimum temperature, maximum temperature, and formality level. Once you have created
a list of clothes, enter the current temperature and the formality of the event that you are going to.
Then, output a list of acceptable clothes to wear based upon the formality level."
And heres what i have so far, but i dont know if i cant sort the user input into a list based on my class instances
class Clothing:
def __init__(self, fit: str, mintemp: int, maxtemp: int, formalitylvl: str):
self.fit = fit
self.mintemp = mintemp
self.maxtemp = maxtemp
self.formalitylvl = formalitylvl
if __name__ == '__main__':
listofclothes = []
listofclothes.append(Clothing("coat", 0, 60, "yes"))
listofclothes.append(Clothing("dress", 0, 100, "yes"))
listofclothes.append(Clothing("T-shirt", 40, 100, "no"))
listofclothes.append(Clothing("Hoodie", 0, 60, "no"))
listofclothes.append(Clothing("jean shorts", 60, 100, "no"))
catalog = int(input("please enter the number of clothing pieces you want to catalog: "))
for i in range(catalog):
str("please enter the clothing item: ")
int(input("Please enter the minimmum temp you would wear the item:"))
int(input("Please enter the maximum temp you would wear the item:"))
str(input("Is the item formal: "))
you are on the right track! you should save the input to variables and not reset the input while looping:
type = input(str("please enter the clothing item: "))
min_temp = int(input("Please enter the minimmum temp you would wear the item:"))
max_temp = int(input("Please enter the maximum temp you would wear the item:"))
is_formal = str(input("Is the item formal: "))
Now, loop over the clothes and check which are right:
output_list = []
for item in listofclothes:
if (item.fit == type and item.mintemp == min_temp and item.maxtemp == max_temp and item.formalitylvl == is_formal):
output_list.append(item)
I've removed your catalog range since it is not mentioned in your assignment. Furthermore, it is not what you should loop over. You should loop over the list of clothes!
EDIT: added type for fit since I forgot that clothing part.

Creating and storing a set # of class objects from user input

I am making a game scoring calculator that needs to be able to prompt a user for the number of players, and then ask for each players information, storing it for each round of scoring.
The problem I have currently is how to write out a user input prompt that creates the number of Player objects given and then assigns each newly created object its own callable variable (preferably it would print the entered player name).
I have tried to use input that creates an input loop based on the given number but it only asks for input without storing anything.
Here is my Player class:
class Player:
def __init__(self, name, inca, power, power_mask, short, medium, long):
self.name = name
self.inca = inca
self.power = power
self.power_mask = power_mask
self.short = short
self.medium = medium
self.long = long
Would it be best to somehow write a def that creates a class object with all of parameters I need it stored under?
If so how would I write this out?
Perhaps something along these lines, you can create a dictionary that contains all the instances, then you can call on them by name for whatever purpose you need.
class Player:
def __init__(self, name, inca, power, power_mask, short, medium, _long):
self.name = name
self.inca = inca
self.power = power
self.power_mask = power_mask
self.short = short
self.medium = medium
self.long = _long
n = int(input('Enter amount of players: '))
d = {}
for i in range(n):
name = input('Enter name: ')
inca = input('Enter inca: ')
power = input('Enter power: ')
power_mask = input('Enter power mask: ')
short = input('Enter short: ')
medium = input('Enter medium: ')
_long = input('Enter long: ')
d[name] = Player(name, inca, power, power_mask, short, medium, _long)
print(d['vash'].power)
Enter amount of players: 1
Enter name: vash
Enter inca: rnation
Enter power: over 9000
Enter power mask: off
Enter short: comings
Enter medium: ...
Enter long: oh yeah
over 9000

manipulate class instance

I want to give the second instance of my Player class the remaining marker after the first instance gets one of them.
class Player():
available_markers = ['X', 'O']
num_of_players = 0
player2_marker = ' '
def __init__(self):
self.name = input('Please enter your name : ')
self.marker = ' '
Player.num_of_players += 1
def choose_marker(self):
while Player.num_of_players != 2:
self.marker = input('Choose X or O')
if self.marker == Player.available_markers[0]:
Player.player2_marker == Player.available_markers[-1]
else:
Player.player2_marker == Player.available_markers[0]
else:
self.marker = Player.player2_marke
I would like to accomplish this in the instance method but have went through a lot of code that doesn't quite work.
There are some misunderstandings of object-oriented coding in your code so I'll try to address them in my answer. One of the goals of object-oriented programming is the separation of concerns. If you have some logic about how a game works and you have some logic about how a player works, you don't want the logic for both in the same place intermixed.
All the player really needs to know is what their name, marker and player number are:
class Player():
num_of_players = 0
def __init__(self, name, marker):
Player.num_of_players += 1
self.name = name
self.marker = marker
self.number = Player.num_of_players
print(self.number, self.marker)
Separate from that is how you want to start the game and initialize the players. You could create another class called Game but for now, I'll just do a function:
def start_game():
available_markers = ['X', 'O']
print("Player 1")
name = input('Please enter your name : ')
Let's not trust that the user of the program will enter the right thing:
while True:
marker = input('Choose X or O: ')
We will loop forever and just break out of it if a valid option is chosen:
if marker in available_markers:
break
else:
print("Invalid choice. Please pick again")
player1 = Player(name, marker)
We'll remove that marker from the list so the list just has one element in it now:
available_markers.remove(marker)
print("Player 2")
name = input('Please enter your name : ')
player2 = Player(name, available_markers[0])
start_game()
# Player 1
# Please enter your name : Adam
# Choose X or O: X
# 1 X
# Player 2
# Please enter your name : Joe
# 2 O
Note that I create two separate instances of Player.
Let's talk briefly about class variables vs instant variables. I kept num_of_players as a class variable to track the total number of players (accessible by doing Player.num_of_players or player1.num_of_players both will return that there are 2 total players). I also created another variable number so each player can track what their number is. That's an instance variable and tracked separately for each instance.

I am having problems with my elif statements

I'm programming a game to try and improve my skills in python. In this part of the code I am trying to program a shop with a money system testing one variable against 5 different possible answers
while True:
choice=str(input("What would you like to buy? (Type in 'nothing' when you don't want anymore items) "))
if choice!="health potion" and "strength potion" and "strength booster" and "armour piece" and "nothing":
print()
next_line=input("I do not understand what you wrote. Try again please ")
print()
elif choice=="nothing":
next_line=input("The merchant says 'Thanks for business' ")
print()
break
elif choice=="health potion":
gold=gold-10
if gold<0:
gold=gold+10
next_line=input("Sorry but you don't have enough gold ")
print()
else:
next_line=input("You bought a health potion ")
health_potions=health_potions+1
next_line=input("You now have "+str(gold)+" gold coins ")
print()
elif choice=="strength potion":
gold=gold-15
if gold<0:
gold=gold+15
next_line=input("Sorry but you don't have enough gold ")
print()
else:
next_line=input("You bought a strength potion ")
strength_potions=strength_potions+1
next_line=input("You now have "+str(gold)+" gold coins ")
print()
elif choice=="strength booster":
gold=gold-45
if gold<0:
gold=gold+45
next_line=input("Sorry but you don't have enough gold ")
print()
else:
next_line=input("You boosted your strength ")
strength_booster=strength_booster+1
next_line=input("You now have "+str(gold)+" gold coins ")
print()
elif choice=="armour piece":
gold=gold-30
if gold<0:
gold=gold+30
next_line=input("Sorry but you don't have enough gold ")
print()
else:
next_line=input("You bought an armour piece ")
armour=armour+1
next_line=input("You now have "+str(gold)+" gold coins ")
print()
When you input health potion the code goes on like normal but with the other inputs it goes to this part of the code
if choice!="health potion" and "strength potion" and "strength booster" and "armour piece" and "nothing":
print()
next_line=input("I do not understand what you wrote. Try again please ")
print()
For fun, here is a significantly more advanced version.
Don't worry if it doesn't all make sense right away; try tracing through it and figuring out how it works. Once you fully understand it you will have a much better grasp of Python!
class Character:
def __init__(self, name, health=50, strength=20, gold=200, inventory=None):
"""
Create a new character
inventory is a list of items (may have repeats)
"""
self.name = name
self.health = health
self.strength = strength
self.gold = gold
self.inventory = [] if inventory is None else list(inventory)
def buy(self, item):
"""
Buy an item
"""
if self.gold >= item.cost:
print(item.buy_response.format(name=item.name, cost=item.cost)) # print acceptance
self.gold -= item.cost # pay gold
item.buy_action(self) # apply purchased item to character
return True
else:
print("Sorry but you don't have enough gold.")
return False
class Item:
def __init__(self, name, cost, buy_response="You bought a {name} for {cost} GP", buy_action=None):
# store values
self.name = name
self.cost = cost
# what to print on a successful purchase
self.buy_response = buy_response
# apply a purchased item to the character
self.buy_action = self.make_buy_action() if buy_action is None else buy_action
def make_buy_action(self):
def buy_action(char):
"""
Purchase default action: add item to character inventory
"""
char.inventory.append(self)
return buy_action
#staticmethod
def buy_strength_booster(char):
"""
Purchase strength booster action: increase character strength
"""
char.strength += 1
def __str__(self):
return self.name
class Shop:
def __init__(self, name, *inventory):
"""
Create a shop
inventory is a list of (num, item); if num is None the store has an unlimited supply
"""
self.name = name
self.inventory = {item.name:(num, item) for num,item in inventory}
def visit(self, char):
"""
Serve a customer
"""
print("\nHowdy, {}, and welcome to {}!".format(char.name, self.name))
while True:
print("\nWhat would you like to buy today? (type 'list' to see what's available or 'done' to leave)")
opt = input("{} GP> ".format(char.gold)).strip().lower()
if opt == 'done':
print("Have a great day, and c'mon back when you've got more gold!")
break
elif opt == 'list':
item_names = sorted(name for name, (num, item) in self.inventory.items() if num is None or num > 0)
if item_names:
print(", ".join(item_names))
else:
print("Huh - looks like we're all sold out. Try again next week!")
break
elif opt in self.inventory:
num, item = self.inventory[opt]
if num is None or num > 0:
yn = input("That's {} GP. You want it? [Y/n]".format(item.cost)).strip().lower()
if yn in {'', 'y', 'yes'}:
if char.buy(item) and num is not None:
self.inventory[opt] = (num - 1, item)
else:
print("(scowling, the proprietor stuffs the {} back under the counter)".format(item.name))
else:
print("'Fraid we're all out of those.")
else:
print("Sorry, hain't had one o' those around in a coon's age!")
def main():
# stock the store
shop = Shop("Dwarven Dave's Delving Deal Depot",
(6, Item("health potion", 10)),
(6, Item("strength potion", 15)),
(3, Item("strength booster", 45, "You boosted your strength!", Item.buy_strength_booster)),
(None, Item("armor piece", 30)) # unlimited stock
)
# create a buyer
jeff = Character("Jeff")
# visit the store
shop.visit(jeff)
if __name__ == "__main__":
main()
Your issue is with this statement:
if choice!="health potion" and "strength potion" and "strength booster" and "armour piece" and "nothing":
Comparing strings like this doesn't work. You need to make sure it isn't in an array of the strings
if choice not in ("health potion","strength potion","strength booster","armour piece","nothing"):
Otherwise it will always be true, so the first statement will always execute.

Python pick item from list of classes

So first I'm trying to make a class, which holds an item's name, price, and quantity available. Then I wanted to make a function that will deduct the quantity sold to a buyer after they enter the amount they are buying, and then calculate the total price.
Now to add on top of that, I am trying to have the user select from a list of items.
The problem is it seem I seem to be getting errors around the time the program starts running the 'buy' function.
class Retail:
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy (self):
print ("How many are you buying?")
quant = int(input("Amount: "))
unitsOnHand -= quant
subto = price * quant
total = subto * 1.08
print ("There are now ", unitsOnHand, " left")
print ("The total price is $", total)
box = Retail(4.95, 20, "Boxes")
paper =Retail(1.99, 50, "Big Stacks of Paper")
staples =Retail(1.00, 200, "Staples")
ilist = (box, paper, staples)
print ("Which are you buying? ", [box.description, paper.description, staples.description])
ioi = input("Please use the exact word name: ")
if ioi == 'box':
Retail.buy(ilist[0])
elif ioi == 'paper':
Retail.buy(ilist[1])
elif ioi == 'staples':
Retail.buy(ilist[2])
The error I get when I tried to run it is
Traceback (most recent call last):
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 22, in <module>
Retail.buy(ilist[0])
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 9, in buy
unitsOnHand -= quant
UnboundLocalError: local variable 'unitsOnHand' referenced before assignment
I'm guessing is that it doesn't see the values I already assigned to the item, and if that is the case, how do I get it to?
Others have pointed out your error, but the other thing that is wrong is your buy call needs to be done on an instance of the object, not the class itself. In other words, right now you are executing buy on the Retail class where you need to execute it on instance (objects) of the class.
I have another suggestion to help organize your code. Use a dictionary to map the keys to the various objects to make your loop a bit cleaner. Putting all that together (and some other checks), here is an updated version of your class:
class Retail(object):
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy(self):
if self.unitsOnHand == 0:
print('Sorry, we are all out of {} right now.'.format(self.description))
return
print("How many are you buying? We have {}".format(self.unitsOnHand))
quant = int(input("Amount: "))
while quant > self.unitsOnHand:
print('Sorry, we only have {} left'.format(self.unitsOnHand))
quant = int(input("Amount: "))
self.unitsOnHand -= quant
subto = self.price * quant
total = subto * 1.08
print("There are now {} left".format(self.unitsOnHand))
print("The total price is ${}".format(total))
return
stock = {}
stock['box'] = Retail(4.95, 20, "Boxes")
stock['paper'] = Retail(1.99, 50, "Big Stacks of Paper")
stock['staples'] = Retail(1.00, 200, "Staples")
print("Which are you buying? {}".format(','.join(stock.keys())))
ioi = input("Please use the exact word name: ")
while ioi not in stock:
print("Sorry, we do not have any {} right now.".format(ioi))
print("Which are you buying? {}".format(','.join(stock.keys())))
ioi = input("Please use the exact word name: ")
stock[ioi].buy()

Categories