I am trying to create any number of instances in a class depending on the user's input but so far I unable to:
class CLASS_INVENTORY:
maxcount_inventory = int(input("How many Inventories: "))
for count_inventory in range(maxcount_inventory):
def __init__(Function_Inventory, inventory_name(count_inventory)):
add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1)))
inventory_name[count_inventory] = add_inventory
Note: I'm kind of new in Python 3 so I'm not sure if some of my syntax are right.
I want the output to be like this:
How many Inventories: 4
Enter Inventory #1: Fruits
Enter Inventory #2: Veggies
Enter Inventory #3: Drinks
Enter Inventory #4: Desserts
Here's my full code:
https://pastebin.com/3FBHgP6i
I'd also like to know the rules in writing Python 3 code if I'm following them right or I should change something. I'd like it to be readable as much as possible for other Python programmers.
class CLASS_INVENTORY():
maxcount_inventory = int(input("How many Inventories: "))
inventory=[]
def __init__(self):
for count_inventory in range(0, self.maxcount_inventory):
add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1)))
self.inventory.append(add_inventory)
I would do something like this:
# Define class
class CLASS_INVENTORY():
# On making a class object init will be called
def __init__(self):
# It will ask for the inventory type count
self.maxcount_inventory = int(input("How many Inventories: "))
self.inventory = []
# Just loop around it to get the desired result
for count_inventory in range(0, self.maxcount_inventory):
add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1)))
self.inventory.append(add_inventory)
Output:
CLASS_INVENTORY()
How many Inventories: >? 2
Enter Inventory #1: >? Apple
Enter Inventory #2: >? Orange
You can construct your dicitonary within def _init__(self) then set up a separate method print_inventories with a loop to print while maintaining the order of entry
class Inventory():
def __init__(self):
self.inventories = {}
n = int(input('How many inventories: '))
for i in range(1, n+1):
self.inventories[i] = input('Enter inventory #{}: '.format(i))
def print_inventories(self):
for k in self.inventories:
print('#{}: {}'.format(k, self.inventories[k]))
a = Inventory()
a.print_inventories()
How many inventories: 4
Enter inventory #1: Fruits
Enter inventory #2: Veggies
Enter inventory #3: Drinks
Enter inventory #4: Desserts
#1: Fruits
#2: Veggies
#3: Drinks
#4: Desserts
Related
I am trying to make a weekly meal prep program in Python. Part of that program is having a database of recipes that the user has entered. I thought the best way to make this would be to make a class Recipe where it stores the title, ingredients (as a dictionary with the key being the ingredient and the amount being value) and then the instructions. However I can't find a way to make a new variable each time I try to input a new recipe.
This is my class code
class Recipe:
def __init__(self):
ingredients = {}
while True:
ingredient = input('Type in an ingredient. Type finish when you have added in all the ingredients. ')
if ingredient == 'finish':
break
amount = input("How much of this ingredient? ")
ingredients[ingredient]=amount
self.ingredients = ingredients
self.title = input('What is the name of the recipe? ')
self.instructions = input('Type out your recipe instructions; ')
meal1 = Recipe()
print(meal1.title)
print(meal1.ingredients)
print(meal1.instructions)
Basically this works for creating one recipe. But instead of the ''' meal1 = Recipe()''' I want to create a new recipe each time the user selects the option in the main menu to 'add a recipe' how can I accomplish this without making lots of pre-named variables.
I think the better approach is to separate between user input (menu) and the recipe class
class Recipe:
def __init__(self):
ingredients = {}
while True:
ingredient = input('Type in an ingredient. Type finish when you have added in all the ingredients. ')
if ingredient == 'finish':
break
amount = input("How much of this ingredient? ")
ingredients[ingredient]=amount
self.ingredients = ingredients
self.title = input('What is the name of the recipe? ')
self.instructions = input('Type out your recipe instructions; ')
class Menu:
def __init__(self):
self.recipes = []
while True:
print("=" * 20)
print('1. Add a recipe')
print('2. Print the recipes')
print('3. Quit')
print("=" * 20)
choice = input('What would you like to do? ')
if choice == '1':
self.add_recipe()
elif choice == '2':
self.print_recipes()
elif choice == '3':
break
else:
print('That is not a valid choice. Please try again.')
def print_recipes(self):
for recipe in self.recipes:
print(recipe.title)
print(recipe.ingredients)
print(recipe.instructions)
def add_recipe(self):
recipe = Recipe()
self.recipes.append(recipe)
Menu()
The recipe is saved in variable self.recipes. With this way, you can save as many recipes as you want.
if I understand your question properly, you want to create a fresh, brand new object every time that a user creates a recipe after inserting the instruction Type out your recipe instructions, then you can delete your object using __del__ function in your class.
class Recipe:
def __init__(self):
ingredients = {}
while True:
ingredient = input('Type in an ingredient. Type finish when you have added in all the ingredients. ')
if ingredient == 'finish':
break
amount = input("How much of this ingredient? ")
ingredients[ingredient]=amount
self.ingredients = ingredients
self.title = input('What is the name of the recipe? ')
self.instructions = input('Type out your recipe instructions; ')
def __del__(self):
print("I have been destroyed.")
and to create a new object every time:
for i in range(5):
meal1 = Recipe()
print(meal1.title)
print(meal1.ingredients)
print(meal1.instructions)
del meal1
#print(meal1) # runs into NameError: name 'meal1' is not defined
note that how __del__ behaves, it may not be called every time if the reference to the object is not counted to zero. you may see this and this.
I am a newbie who just learnt about functions and classes. I created a code using Class with a while loop that allows the entry of marks of five students in four subjects. Now I don't know how to add up the avg scores of all students and find the overall average score of the five students combined. I am providing the full code here. Please suggest all the improvements and solution to the problem.
entry = 1
while entry <=5:
class Marks():
def __init__(self, name, english_marks, hindi_marks, science_marks, economics_marks):
self.name = name
self.english_marks = english_marks
self.hindi_marks = hindi_marks
self.science_marks = science_marks
self.economics_marks = economics_marks
def output(self):
print("\n")
print("Hi "+self.name.title())
avg_marks = (self.english_marks + self.hindi_marks + self.science_marks + self.economics_marks)/4
print("Your average score is ", avg_marks)
print("\n")
name = input("Enter your name: ")
english_marks = int(input("Enter your English score: "))
hindi_marks = int(input("Enter your Hindi score: "))
science_marks = int(input("Enter your science score: "))
economics_marks = int(input("Enter your economics score: "))
j = Marks(name, english_marks, hindi_marks, science_marks, economics_marks)
j.output()
entry = entry + 1
updated
Use the average values from each student to make a variable that averages the values
(you can make the five avg_marks variables in the output function based on what your entry value is.)
example:
total =(avg_marks1+avg_marks2+avg_marks3+avg_marks4+avg_marks5)/5
I’m finding the Python syntax very confusing, mainly concerning variables. I’m trying to learn it using the Microsoft EDX course but I’m struggling when trying to check if a string from an input is in the variable.
Example 1: Check if a flavor is on the list
# menu variable with 3 flavors
def menu (flavor1, flavor2, flavor3):
flavors = 'cocoa, chocolate, vanilla'
return menu
# request data from the user flavorName = input('What flavor do your want? ')
data = input("What flavor do you want? ")
#print the result
print ("It is", data in menu, "that the flavor is available")
Example 2: Print a message indicating name and price of a car
def car (name, price):
name = input(“Name of the car: “)
price = input (“Price of the car: “)
return (name, price)
print (name, “’s price is”, price)
Also, I would like to know what would be the disadvantage of doing something like this for the example 2:
name = input("name of the car: ")
price = input ("price of the car: ")
print (name,"is", price,"dollars")
Could someone please clarify this to me? Thank you very much!
i didnt understand what your trying to do in first example.
But i can partially understand what your trying to do in second example,
def car ():
name = input("Name of the car: ")
price = input ("Price of the car: ")
return name, price
name,price = car()
print ("{}\'s price is {}".format(name,price))
the above code is the one of the way to solve your problem,
python can return multiple variable
use format function in print statement for clean display.
You dont need function parameters for car. since your taking input from in car function and returning it to the main.
Hope it helps you understand.
Example 1
# menu variable with 3 flavors
def menu():
flavors = 'cocoa, chocolate, vanilla'
return flavors #return flavors instead of menu
# request data from the user flavorName = input('What flavor do your want? ')
data = input("What flavor do you want? ")
# print the result
print ("It is", data in menu(), "that the flavor is available") #menu is a function so invoke with menu () instead of menu
Example 2:
def car(): #no input required since you are getting the input below
name = input('Name of the car: ')
price = input('Price of the car: ')
return (name, price)
name, price = car() #call the function to return the values for name and price
print (name, "’s price is", price)
The below approach works and is faster as compared to calling the function although adding small stuff to form functions allows the program to be modularized, making it easier to debug and reprogram later as well as better understanding for a new programmer working on the piece of code.
name = input("name of the car: ")
price = input("price of the car: ")
print (name, "is", price, "dollars")
Just found how to print the result in the way the exercise required. I had difficulty explaining, but here it is an example showing:
def car(name,price):
name_entry = input("Name car: ")
price_entry = input("Price car: ")
return (name_entry,price_entry)
This is the way to print the input previously obtained
print (car(name_entry,price_entry))
Thank you very much for all the explanations!
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
This is a smaller portion of the main code I have been writing. Depending on user selection they can add player informationa and then print the information from the dictionary player roster. I want to store the information and then print in this format but I havent been able to figure out how to do this.
Name ****
Phone Number ****
Jersey Number ****
Im new to dictionaries but I have spent hours reading and searching over the past couple of days about dictionaries and have tried several different ways to do this but failed. I have gotten the closest the way I have it setup now but it still doesnt work right. I feel like I am storing the information incorrectly into the dictionary for starters, any help would be greatly appreciated.
player_roster = {}
def display_roster(self): #Print Roster
if len(player_roster) != 0:
for x in player_roster.keys():
print('Name:', x, 'Phone Number:', player_roster[x])
else: #Print No One on Roster
len(player_roster) == []
print('No names have been entered:')
def add_player(self,): #Enter Members Name
name = input('Enter New Players Name:')
phone_number = input('Enter Players Phone Number:')
jersey_number = int(input('Enter Players Jersey Number'))
player_roster[name] = phone_number, 'Jersey Number', jersey_number
#If I input Toby as Name 444-444 as Phone Number and 3 as Jersey number it outputs like this
Name: Toby Phone Number: ('444-4444', 'Jersey Number', 3)
# I would like it to output like
Name: Toby
Phone Number: 444-4444
Jersey Number: 3
There are some things i would change in your code but to keep this close to what you asked for take a look at this:
def display_roster():
if len(player_roster) != 0:
for x in player_roster.keys():
print('Name:', x)
print('Phone Number:', player_roster[x][0])
print('Jersey Number:', player_roster[x][1])
else:
print('Roster is empty.')
return
player_roster = {}
def add_player():
name = input('Enter New Players Name:\t')
phone_number = input('Enter Players Phone Number:\t')
jersey_number = int(input('Enter Players Jersey Number:\t'))
player_roster[name] = [phone_number, jersey_number]
return
add_player()
display_roster()
# PRINTS:
#Name: Toby
#Phone Number: 444-4444
#Jersey Number: 3
Printing in multiple lines gives you the result you want. As stated in the comments this can also be done with a single print() statement but i do not think compact code makes much difference to you yet.
Further, this len(self.player_roster) == [] line does not make sense. This is as good as simply writing True in a line. The "emptiness" of the team is checked by the else:.
Finally, i would slightly change the way players are stored in the "Roster" dictionary and have it like this: {"Toby": ['444-4444', 3], ...}
I would propose that you replace the print statement to this:
print(" Name: %s \n Phone Number: %s \n Jersey Number: %d") % player_roster[x]
You're pretty much there. The below modification would allow you to print as you need (and is slightly more readable):
class PlayerDictionary():
def __init__(self):
pass
player_roster = {}
def display_roster(self): #Print Roster
if len(self.player_roster) != 0:
for key, value in self.player_roster.iteritems():
print(str(key) + ": " + str(value))
else: #Print No One on Roster
len(self.player_roster) == []
print('No names have been entered:')
def add_player(self,):
self.player_roster['Name'] = input('Enter New Players Name:')
self.player_roster['Phone Number'] = input('Enter Players Phone Number:')
self.player_roster['Jersey Number'] = int(input('Enter Players Jersey Number'))
if __name__ == "__main__":
player = PlayerDictionary()
player.add_player()
player.display_roster()
A slightly more maintainable solution would be to create a class for Player. Set the properties on the object and overload the str function e.g.
class Player(object):
def __init__(self):
self.__name = ""
self.__phone_number = ""
self.__jersey_number = ""
#property
def name(self):
return self.__name
#property
def phone_number(self):
return self.__phone_number
#property
def jersey_number(self):
return self.__jersey_number
#name.setter
def name(self, val):
self.__name = val
#phone_number.setter
def phone_number(self, val):
self.__phone_number = val
#jersey_number.setter
def jersey_number(self, val):
self.__jersey_number = val
def __str__(self):
return ("Name: %s\nPhone Number: %s\nJersey Number: %s" % (str(self.__name), str(self.__phone_number), str(self.__jersey_number)))
if __name__ == "__main__":
player = Player()
player.name = input('Enter New Players Name:')
player.phone_number = input('Enter Players Phone Number:')
player.jersey_number = int(input('Enter Players Jersey Number'))
print(player)