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

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

Related

Creating new instances of a class from user input

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.

How to deal with a ValueError and re-prompt the user a specific question in Python?

First-time poster and very new to Python and programming in general. I have been working on a character creator project and I'm trying to figure out how to deal with a non-integer being typed in for one of the attributes prompts, like "int(input('Strength: ')),"
I want to prevent a crash from the user typing in something other than an integer, and then to prompt the user to input the specific attribute again.
Here's a chunk of the code that I'm talking about.
class Char_presets:
def __init__(self, name, type, strength, dexterity, wisdom, intelligence, faith):
self.name = name
self.type = type
self.strength = strength
self.dexterity = dexterity
self.wisdom = wisdom
self.intelligence = intelligence
self.faith = faith
def create_clss():
c1 = input('Save name?: ')
c1 = Char_presets(
input("What is your name?: "),
input('Class type?: '),
int(input('Strength: ')),
int(input('Dexterity: ')),
int(input('Wisdom: ')),
int(input('Intelligence: ')),
int(input('Faith: '))
)
Thanks for any help.
Determine if the input string is an integer or not, and continue asking if not.
strength = input("Strength: ")
while not strength.isnumeric():
strength = input("That's not an integer! Strength: ")
# at this point, strength will contain an integer
You can utilize the walrus operator introduced in python 3.9:
def create_clss():
c1 = input('Save name?: ')
while (strength := input('Strength: ')): # strength is defined here!
if strength.isdigit(): # check if the input is all digits
break
c1 = Char_presets(
input("What is your name?: "),
input('Class type?: '),
int(strength),
int(input('Dexterity: ')),
int(input('Wisdom: ')),
int(input('Intelligence: ')),
int(input('Faith: '))
)
Of course, if you want to order in which the user inputs data to be kept, you'll need to store the rest of the input values in variables too:
def create_clss():
c1 = input('Save name?: ')
name = input("What is your name?: ")
class_type = input('Class type?: ')
while (strength := input('Strength: ')):
if strength.isdigit():
break
dexterity = input('Dexterity: ')
wisdom = input('Wisdom: ')
intelligence = input('Intelligence: ')
faith = input('Faith: ')
c1 = Char_presets(
name,
class_type,
int(strength),
int(dexterity),
int(wisdom),
int(intelligence),
int(faith)
)
Use a try…except block inside of a while loop.
try block first executes and then if there is any Exception in the try block, it immediately stops the execution of the try block and goes to the except block.
Python Exception Handling
Sample code:
while True:
try: #Executes the block of code under it, and if an Exception occurs, it immediately jumps to the except block
strength = int(input('Strength: '));
break;
except ValueError: #Here we are 'catching' the Exception and giving our own commands when the specified Exception occurs
print("Enter integer only!");

code that allows to input score of five students but how to add the score of all the students

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

How do I create instances in class using user's input?

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

Tying values to keys in a dictionary and then printing

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)

Categories