I am trying to define a class called 'Vacation' to store information about the user once they have answered a set of input statements (my project is a vacation program where the user answers a set of questions in order to receive a randomly generated vacation itinerary). My professor told me to put all of my questions (aka input statements) within my constructor, however I keep getting an error saying I have a syntax error although I am not sure why. I have tried putting the different variable names in the () of my constructor but this does nothing (I thought maybe I had a syntax error because I forgot to include one of the variable names - specifically the error is coming from 'excursions'). I am fairly new to Python (just started in January) so my knowledge of the programming language is very limited (plus I just learned classes about 2 weeks ago). Any and all help/feedback/ideas would be greatly appreciated!
class Vacation:
def __init__ (self, num_guests, max_price, vacay_len, excursions, user_input, excursions_price, excursions_num, user_preference):
user_input = input("Would you like a (R)andomly generated vacation or a (T)ailored vacation?: ")
num_guests = int(input("Please enter number of guests: "))
max_price = float(input("Please enter your maximum willingness to pay (ie. 700): "))
vacay_len = int(input("Please enter how many days you would like your vacation to be: ")
excursions = (input("Would you like to include excursions while on vacation? (Y/N) : ")).upper()
if excursions == "Y":
excursions_num = int(input("How many excursions would you like to sign up for (up to 2): "))
excursions_price = float(input("How much would you like to spend on each excursion? : "))
else:
print("Let's get to exploring!")
user_preference = user_input
self.user_preference = user_preference
self.num_guests = num_guests #number of guests
self.max_price = max_price #maximum price range
self.housing_price = .3(self.max_price) #housing budget allocation
self.vacay_len = vacay_len #vacation length
self.excursions_price = excursion_price #price for each excursion
self.excursions_num = excursions_num #number of excursions
You are missing closing bracket on this line:
vacay_len = int(input("Please enter how many days you would like your vacation to be: "))
You have a typo excursion_price should be excursions_price as below:
self.excursions_price = excursions_price #price for each excursion
You also need to add * for multiplication here:
self.housing_price = .3*(self.max_price)
You can remove the variables from the __init__ function in this case since they will be provided by the users input to the programme.
I would recommend using a python IDE which will highlight the issues for you in red.
Not sure if this is what you want but the following code seems to work:
class Vacation:
def __init__ (self):
user_input = input("Would you like a (R)andomly generated vacation or a (T)ailored vacation?: ")
num_guests = int(input("Please enter number of guests: "))
max_price = float(input("Please enter your maximum willingness to pay (ie. 700): "))
vacay_len = int(input("Please enter how many days you would like your vacation to be: "))
excursions = (input("Would you like to include excursions while on vacation? (Y/N) : ")).upper()
if excursions == "Y":
excursions_num = int(input("How many excursions would you like to sign up for (up to 2): "))
excursions_price = float(input("How much would you like to spend on each excursion? : "))
else:
print("Let's get to exploring!")
user_preference = user_input
self.user_preference = user_preference
self.num_guests = num_guests #number of guests
self.max_price = max_price #maximum price range
self.housing_price = .3(self.max_price) #housing budget allocation
self.vacay_len = vacay_len #vacation length
self.excursions_price = excursion_price #price for each excursion
self.excursions_num = excursions_num #number of excursions
As suggested by Steve I removed your variables from the constructors parameters as you probably won't be passing arguments. At the Excursions line you were simply missing a closing )
Related
class Budget:
def __init__(self):
self.wants_perc = 0
self.wants_amt = 0
self.wants_left = 0
self.needs_perc = 0
self.needs_amt = 0
self.needs_left = 0
self.food_perc = 0
self.food_amt = 0
self.food_left = 0
while True:
try:
self.monthly_income = float(input("Enter your monthly income after taxes: "))
break
except ValueError:
print("Invalid Input : Please enter a number")
continue
while True:
print("Enter desired percentage of income spent for each category (do not include %): ")
try:
self.wants_perc = float(input("Wants: "))
self.needs_perc = float(input("Needs: "))
self.food_perc = float(input("Food: "))
if self.wants_perc + self.needs_perc + self.food_perc not in range(95, 105):
print("Invalid Input : Must add to 100%")
continue
else:
break
except ValueError:
print("Invalid Input : Please enter a number")
continue
def deposit(self):
dep_loc = input("Where would you like to deposit? ")
while True:
try:
if dep_loc.lower() == "wants":
self.wdep_amt = float(input("Deposit amount: "))
self.wants()
break
elif dep_loc.lower() == "needs":
self.ndep_amt = float(input("Deposit amount: "))
self.needs()
break
elif dep_loc.lower() == "food":
self.fdep_amt = float(input("Deposit amount: "))
self.food()
break
else:
print("Invalid Input")
break
except ValueError:
print("Invalid Input : Please enter a number")
continue
def wants(self):
self.wants_max = (self.wants_perc / 100) * self.monthly_income
self.wants_amt += self.wdep_amt
self.wants_left = self.wants_max - self.wants_amt
print(f"Amount spent on wants: ${self.wants_amt} \nAmount left to spend: ${round(self.wants_left,2)}")
def needs(self):
self.needs_max = (self.needs_perc / 100) * self.monthly_income
self.needs_amt += self.ndep_amt
self.needs_left = self.needs_max - self.needs_amt
print(f"Amount spent on needs: ${self.needs_amt} \nAmount left to spend: ${round(self.needs_left,2)}")
def food(self):
self.food_max = (self.food_perc / 100) * self.monthly_income
self.food_amt += self.fdep_amt
self.food_left = self.food_max - self.food_amt
print(f"Amount spent on food: ${self.food_amt} \nAmount left to spend: ${round(self.food_left,2)}")
wyatt = Budget()
while True:
wyatt.deposit()
I know this is a very general question, but is it possible to reduce the amount of repeated code I use? I feel like there has to be a way to use one general variable in a loop for each of the categories. My three functions that use the food, wants, and needs variables are all the exact same besides the names. I thought of getting user input and adding it to a list and indexing that list to get each category, but I couldn't fully figure it out. This may be too broad for stack overflow and if it is I apologize. Thanks!
In general there is no mechanism for reducing the amount of code - if there was, it would already be part of the language. Making a dictionary instead of member variables doesn't really help, because all it will do is replace your 9 member variables with 9 dictionary items.
However, there is an opportunity for factoring out repeated operations. Your instinct is correct that repeated blocks of code are a sign of poor design. I would suggest you start with a class structure something like this:
class BudgetItem:
def __init__(self, name):
self.name = name
self.perc = 0
self.amt = 0
self.left = 0
def get_perc(self):
self.perc = float(input(f"{self.name}: "))
class Budget:
def __init__(self, monthly_income):
self.monthly_income = monthly_income
self.wants = BudgetItem("Wants")
self.needs = BudgetItem("Needs")
self.food = BudgetItem("Food")
self.all_items = (self.wants, self.needs, self.food)
def gather_percentages(self):
print("Enter desired percentage of income"
" spent for each category (do not include %): ")
for b in self.all_items:
b.get_perc()
if 95.0 <= sum(b.perc for b in self.all_items) <= 105.0:
print("Precentages must sum to 100")
# etc.
Create a separate class to represent a budget category, since the logic for each is identical. Add methods to the little class to capture that logic. Now re-write your main class in terms of those three individual items. I won't take the time to refactor your whole program, but I hope you get the idea. You should end up with a much shorter program and no significant repeated logic.
One other thing: I think that putting an "input" statement in a class constructor is a terrible idea. Constructors should not contain complicated loops or extended logic. I would put it outside the class and pass the data into the class as arguments, or as method calls.
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()
I have created two different functions, one to create an inventory of available products:
def create_piece():
print(Colour().blue('Creating a new piece'.center(200)))
piece_name = input(Colour().orange('Name of the piece: '))
piece_registration = input(Colour().orange('Piece registration number: '))
piece_date = input(Colour().orange('Date of manufacture: '))
piece_location = input(Colour().orange('Manufacturing location: '))
piece_price = input(Colour().orange('Price: '))
Parts.create(Name=piece_name , Parts_registration_number=piece_registration ,
Date_of_manufacture=piece_date ,
Manufacturing_locality=piece_location , Price=piece_price ,
Number_of_parts_sold='0')
print(Colour().green(('Part created satisfactorily')))
As you can see the option "Number_of_parts_sold" has the marker to 0.
Then I have created an option to execute purchase orders:
def order_purchase():
print(Colour().blue('Purchase order portal'.center(200))
Seller_name = input(Colour().orange('Who are you?: '))
number = int(input(Colour().orange('Number of items?: '))
pieces_list=[]
total_cost = 0
for i in range (0, number):
while True:
piece_name = input(Colour().orange('Name of the piece to buy: '))
try:
piece = Pieces.get(Pieces.Name == piece_name)
break
except DoesNotExist:
print(Colour().red('This piece does not currently exist in the system, ')
please enter a correct name.'))
ID = input(Colour().orange('Purchase ID: '))
for price in Piezas.select().where(Pieces.Name == piece_name):
price_orders = (price.price)
total_cost += price_orders
name_piece=str(name_piece)
parts_list.append(part_name)
Orders.create(ID_buy_orders=ID, Date_buy_orders=datetime.now(),
Order_Seller=Seller_name , Order_People = pieces_list,
Price_orders=total_cost)
print(Colour().green('Pieces sold satisfactorily'))
This last function fills in another table in which it stores the number of pieces that each seller buys. However, I would like to know how to relate the second table with the first so that for each piece that is sold (generated in the tuple "lista_piezas") change the marker and add in the first table how many pieces have been sold. How could I do this? Thanks in advance
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 instances of a certain class based on user input and the display their attributes this is my code:
class member_of_team:
def __init__(self, outside_shot, inside_shot, handling, speed):
self.outside_shot = outside_shot
self.inside_shot = inside_shot
self.handling = handling
self.speed = speed
choice = input("Would you like to enter a teamate? ")
y = choice
while y == "yes":
x = input("what is the teamates name? ")
a = int(input("How good is he at shooting outside? "))
b = int(input("What about his inside shot? "))
c = int(input("How well is he at handling the ball? "))
d = int(input("How fast is he? "))
x = member_of_team(a, b, c, d)
y = input("Do you want to enter another teamate? ")
r = input("what member of the team woulsd you like to check up")
s = input("what would you like ot know about him")
print(r.s)
AttributeError: 'str' object has no attribute 's'
I believe you were trying to create an object from member_of_team class. And later you were giving the object's name as input and then trying to access the attributes of that object.
You can use getattr() builtin function of Python.
getattr(object, name[, default])
Return the value of the named
attribute of object. name must be a string. If the string is the name
of one of the object’s attributes, the result is the value of that
attribute. For example, getattr(x, 'foobar') is equivalent to
x.foobar. If the named attribute does not exist, default is returned
if provided, otherwise AttributeError is raised.
So, you need maintain a directory of all the objects created. Because in python objects were created on the fly. And when you provide object's name from STDIN. You get that in that in the form of String. You need to find out out the its equivalent OOP's object actually.
Please check out this code.
class member_of_team(object):
def __init__(self, outside_shot, inside_shot, handling, speed):
self.outside_shot = outside_shot
self.inside_shot = inside_shot
self.handling = handling
self.speed = speed
choice = input("Would you like to enter a teamate? ")
object_directory = {}
while choice == "yes":
x1 = input("what is the teamates name? ")
a = int(input("How good is he at shooting outside? "))
b = int(input("What about his inside shot? "))
c = int(input("How well is he at handling the ball? "))
d = int(input("How fast is he? "))
x = member_of_team(a, b, c, d)
object_directory[x1] = x
y = input("Do you want to enter another teammate? ")
r = input("what member of the team would you like to check up?")
s = input("what would you like to know about him?")
print (getattr(object_directory[r], s))
Sample Console Output:
Would you like to enter a teamate? yes
what is the teamates name? Ronaldo
How good is he at shooting outside? 5
What about his inside shot? 7
How well is he at handling the ball? 8
How fast is he? 8
Do you want to enter another teammate? no
what member of the team would you like to check up?Ronaldo
what would you like ot know about him?handling
8