Python class (input name,output number) - python

i want to create code which will be outputing the sum of the product prize. Example below.
Input:
bread,rice
Output:
6,5 $
Here is my code:
class product:
def __init__(self,name,color,prize)
self.name=name
self.color=color
self.prize=prize
def info(self)
input(name)
return (self.prize)
tomato=product()
tomato.name="tomato"
tomato.color="czerwony"
tomato.prize= 4,56
turnip=product()
turnip.name="turnip"
turnip.color="white"
turnip.prize= 5.65
print("write the name of one products from the list and I will tell you how much it costs [tomato,turnip] "
info()
There is only 2 products,i wanted to reduce code lines.

I think you are looking for something like this, please note, the code below does not have any error/validation checks in place:
class product:
def __init__(self,name=None,color=None,prize=None):
self.name=name
self.color=color
self.prize=prize
def info(self):
return (self.prize)
tomato=product()
tomato.name="tomato"
tomato.color="czerwony"
tomato.prize= 4.56
turnip=product()
turnip.name="turnip"
turnip.color="white"
turnip.prize= 5.65
user_input = raw_input("write the name of one products from the list and I will tell you how much it costs [tomato,turnip]:")
print(eval(user_input).info())

Related

Cannot append objects to a list

I'm having some troubles with my code. This is a budget app in which you can add categories and for every category you can deposit/withdraw money. The problem is that I have to save all the transactions in the format {"amount": x, "description":y} and to do this I create an object of class Amount which is defined in the code, but when I try to append the new Amount object to the list every single element of this list changes to the last object. I understood that when I add an object, all the other elements in the list refer to the same object, and that's probably the problem, but I cannot solve this. Can you help me? Thank you very much
(This bug happens in the methods deposit and withdraw)
class Amount:
tot={"amount":0,"description":""}
def __init__(self,am,descr=""):
self.tot["amount"]=am
self.tot["description"]=descr
def getTot(self):
return self.tot
class Category:
title=""
deposit_list=list()
balance=0
def __init__(self,name):
self.title=name
def __str__(self):
final_string=""
length=int((30-len(self.title))/2)
for i in range(0,length):
final_string+="*"
final_string+=self.title
for i in range(0,length):
final_string+="*"
final_string+="\n"
for x in self.deposit_list:
y=x.getTot()["description"]
y=y[0:23]
z=float(x.getTot()["amount"])
final_string+=y
l=len(y)
if l<23:
for i in range(l,23):
final_string+=" "
z=str(z)
l=len(z)
if l<7:
for i in range(l,7):
final_string+=" "
final_string+=z
final_string+="\n"
final_string+="Total: "
final_string+=str(self.balance)
return final_string
def get_balance(self):
return self.balance
def getTitle(self):
return self.title
def deposit(self,amount,description=""):
if description!="":
description=str(description)
dep=Amount(amount,description)
self.deposit_list.append(dep)
self.balance+=dep.getTot()["amount"]
def withdraw(self,amount,description=""):
if description!="":
description=str(description)
wd=Amount(-1*amount,description)
if self.check_funds(amount):
self.deposit_list.append(wd)
self.balance+=wd.getTot()["amount"]
return True
else:
return False
def transfer(self,amount,dest):
descr_dest="Transfer from "
descr_dest+=self.getTitle()
descr_src="Transfer to "
descr_src+=dest.getTitle()
if self.withdraw(amount,descr_src)==True:
dest.deposit(amount,descr_dest)
return True
else:
return False
def check_funds(self,amount):
if amount>self.balance:
return False
else:
return True
def create_spend_chart(categories):
return
Edit:
I'm sorry, here is a test you can run
import budget
from unittest import main
food = budget.Category("Food")
food.deposit(1000, "initial deposit")
food.withdraw(10.15, "groceries")
food.withdraw(15.89, "restaurant and more food for dessert")
clothing = budget.Category("Clothing")
food.transfer(50, clothing)
print(food)
It should print this:
*************Food*************
initial deposit 1000.00
groceries -10.15
restaurant and more foo -15.89
Transfer to Clothing -50.00
Total: 923.96
I also have to say that it should print only the first 23 characters of the description, but this shouldn't be important for the question.
#frno that was an attempt to avoid the problem described in the question, I edited the code as it was before that update
Thank you!

How to input data in classes in python, if number of students I want to input is not known

I want to input data in a class. I don't know the number of students I want to input. I can only write p1.name="John" p2.name="Jack" etc but if I want to input more students I have to write p3,p4,p5...
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person
p1.name="John"
p1.age=15
print(p1.name)
print(p1.age)
Is there a method to work like with arrays for example p[0].name="John"....... p[123].name="Jack" or something like that... Sorry for my bad english
You probably meant
p1 = Person('John', 15)
p2 = Person('Jack', 42)
If you needed an arbitrary number of objects, you can store them in a data structure like
people = [Person('John', 15), Person('Jack', 42)]
for person in people:
print(person.name)
You can read data into that array as well-
people = []
with open('people.txt') as f:
for line in f:
name, age = line.split()
people.append(Person(name, age))
But my advice would be to find a more introductory tutorial to follow, you're going to struggle :)
Sounds like you need a list.
A list is a data structure that you can use for zero or more elements, and you can access each element by iteration or by indexing the list.
You can do something like this:
persons = [
Person("John", 15),
Person("Adele", 16),
...
]
and then you can access each person by an index: persons[0] will give you Jonh, and persons[1] will give Adele.
if your objective is to store the students in an array-like structure, then you can definitely do this in Python. What you're currently doing is instantiating a new class object for each student. While this is totally valid, it may not be appropriate for the task you're trying to achieve.
Before mastering classes, I'd recommend familiarising yourself with python data structures like dictionaries, lists and tuples.
Just another idea. You could store all of the students in a dictionary that is contained within a class. Wrapping the dictionary in a class will let you add or fetch students very easily.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Classroom:
def __init__(self):
self.students = {}
def add_student(self, student):
self.students[student.name] = student
def get_student(self, name):
return self.students[name]
classroom = Classroom();
classroom.add_student(Person("John", 12))
classroom.add_student(Person("Sarah", 13))
print(classroom.get_student("Sarah").age)
#Output
#13
def main():
classroom = Classroom()
n = input("How many students would you like yo add? ")
for i in range(int(n)):
classroom.add_student(Person(input("Enter Name: "), int(input("Enter Age: "))))

How to call objects from a class in a function of another class

I want to use an object of a class in a function of another class. I know it's a really easy thing to solve, but I still can't figure it out.
I have the following class that is an object of players
class Players():
def __init__(self, name_player, surname, age, height, wheight):
self.name_player= name_player
self.surname = surname
self.age= age
self.height= height
self.wheight= wheight
def __repr__(self):
return "{}, {}, {}, {}, {} //".format(self.name_player,self.surname,self.age,self.height,self.wheight)
Then I have this class of teams
class Teams():
def __init__(self, name, points, goals_in_favour, goals_against):
self.name= name
self.points= points
self.goals_in_favour= goals_in_favour
self.goals_against= goals_against
def __repr__(self):
return "{} : {} : {}: {}".format(self.name,self.points,self.goals_in_favour,self.goals_against)
Now in the function 'ages' I want it to return a list of the players with an age less or equal to the one on the file. If I write 'i.Players.age' it sends me an error, which is the right way to spell it?
def ages(lists_teams,age):
list_players =""
return [list_players + i for i in list_teams if (i.Players.age <= age)]
(I have to write it in a list comprehension way).
Thanks a lot in advance.
To help you understand.
1.If list_teams is already an list of objects...you cannot call i.Players, because i here is already an object.
2.list_players="" you should change it to []...."" is not a list, you cannot add object on to it.
3.Try not use i for object, it is normally used to indicate an index..
def ages(list_teams,age):
list_players =[]
return [list_players + [player] for player in list_teams if (player.age <= age)]

Yatzy, using asciitable, how to fix the columns?

My issue right now with yatzy is that I wanna print a board with columns containing names and how much points they have. Currently my code is looking like this:
from terminaltables import AsciiTable
class Player:
def __init__(self,name):
self.name=name
self.lista={"ones":0,"twos":0,"threes":0, "fours":0,"fives":0,"sixs":0,"abovesum":0,"bonus":0,"onepair":0,"twopair":0,"threepair":0,"fourpair":0,"smalladder":0,"bigladder":0,"house":0,"chance":0,"yatzy":0,"totalsum":0}
self.spelarlista=[]
def __repr__(self):
return self.name
def __str__(self):
return self.name
def welcome(self):
t=0
print("Welcome to the yahtzee game!")
players = int(input("How many players: "))
rounds=0
while not players==rounds:
player=input("What is your name?: ")
rounds=rounds+1
self.spelarlista.append(Player(player))
table_data = [
['Heading1', 'Heading2'],
['hans', 'joha'],
['jens', 'drev'],
['sonny', 'elias']]
table = AsciiTable(table_data)
print(table.table)
def main():
play=Player("joakim")
play.welcome()
main()
Notice that the asciitable code is pretty much copied, because I'm not sure how to solve the issue to get columns based on how many players I have. As you can see, it starts with asking how many players, let's say I go with 3, "James","Patrik" and "Andy", then I want 3 columns, is this possible to make? Second question, is Asciitable the right way to go? Is there an easier way, perhaps with something built-in already in python, I just tried this out because I got recommended. Thanks in advance.

Python input Job Code

I'm Code doesn't seem to work, I am trying to get input of a job, category, and salary, and store the input
class Jobs:
def GetJob(self):
name = raw_input('Enter a Job Title: ')
category = raw_input('Enter what Category that Job is: ')
salary = raw_input('Enter the salary of that Job: ')
print name,category, salary
def __init__(self,name,category,salary):
self.name = Jobs.GetJob(name)
self.category = Jobs.GetJob(category)
self.salary = Jobs.GetJob(salary)
GetJob = Jobs()
print GetJob
Your code is totally out of good OOP practices, and the first part eandersson's answer too…
A class has for role to store values, get/set them and return (or apply) transformations to its encapsulated values. What you tried to achieve is totally nonsense: you're calling the GetJob method of the Jobs class inside another method. It could work if you would have written:
def __init__(self,name…):
self.name = Jobs.GetJob(self, name)
…
But that would be a wrong way to design your program. You'd better stick your class to hold your values and making it good at that, and make another function that helps populate your class:
class Jobs:
def __init__(self, name, category, salary):
self.name = name
self.category = category
self.salary = salary
def __repr__(self):
return "Jobs<%s,%s,%s>" % (self.name, self.category, self.salary)
def GetJob():
name = raw_input('Enter a Job Title: ')
category = raw_input('Enter what Category that Job is: ')
salary = raw_input('Enter the salary of that Job: ')
return Jobs(name, category, salary)
print GetJob()
I do not agree with eandersson's approach because it deceives the purpose of the constructor, by directly calling the GetJob method. Then GetJob is not useful. And one would want to be able to use the Job class without always having the raw inputs at construction. EDIT: valid only as a comment on the first part of his answer.
And finally, I think that you really misunderstands a lot about programming. You should better read thoroughly a python course like the ones on http://wiki.python.org/moin/BeginnersGuide/NonProgrammers, because there's really a lot of concepts you ignored to be able to write something like that.
go have a look at:
http://hetland.org/writing/instant-hacking.html
http://www.learnpython.org/
http://cscircles.cemc.uwaterloo.ca/
http://learnpythonthehardway.org/book/

Categories