Take user input in Python 2.7 - python

Below is a simple python 2.7 code using class and objects.
class Student:
def __init__(self,name,pref):
self.name = name
self.preference = pref
student1=Student("Tom","cce")
print(student1.name)
print(student1.preference)
How can this code be implemented so that the name and preference values(string) are taken using user-input(raw_input())

Here is also a working code.
class Student:
def __init__(self,name,pref):
self.name = name
self.preference = pref
student1=Student(raw_input("enter name:"),raw_input("enter branch:"))
print(student1.name)
print(student1.preference)

Here's an example:
class Student:
def __init__(self,name,pref):
self.name = name
self.preference = pref
name1 = raw_input("Name:")
pref1 = raw_input("Preference:")
student1 = Student(name1, pref1)
print(student1.name)
print(student1.preference)

Related

How to call object of class by input?

I am generating a class of persons and want to get information about a certain person by input. I would like to use the str funtction because I am trying to understand it better. My Idea goes as follows:
class Person:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
__str__(self):
return "The persons full name is:" + f_name + l_name
person1 = Person(Peter, Punk)
person2 = Person(Mia, Munch)
person = input("What persons full name would you like to know?")
print(person) #I am aware that this just fills in the string saved in person, but how do I connect it to the variable?
another idea was to do it as follows:
#class stays the same except:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
list.append(self)
#and then for the main:
list = []
person1 = Person(Peter, Punk)
person2 = Person(Mia, Munch)
person = input("What persons full name would you like to know?")
index = list(person)
print(list[index])
Thankful for any edvice since I am obviously new to Python :D
I think OP has some concept problems here which this answer may go some way to help with.
Start by building a robust class definition. Simple in this case as there are just 2 attributes. Note the use of setters, getters and str, repr and eq dunder overrides.
A small function that checks if a given Person can be found in a list of Persons and reports accordingly.
Create a list with 2 different Person instances
Create another Person that is known not to match anything already in the list.
Run check()
Modify the 'standalone' Person to make it equivalent to something previously constructed.
Run check()
class Person:
def __init__(self, forename, surname):
self._forename = forename
self._surname = surname
#property
def forename(self):
return self._forename
#forename.setter
def forename(self, forename):
self._forename = forename
#property
def surname(self):
return self._surname
#surname.setter
def surname(self, surname):
self._surname = surname
def __str__(self):
return f'{self.forename} {self.surname}'
def __repr__(self):
return f'{self.forename=} {self.surname=}'
def __eq__(self, other):
if isinstance(other, type(self)):
return self.forename == other.forename and self.surname == other.surname
return False
def check(list_, p):
if p in list_:
print(f'Found {p}')
else:
print(f'Could not find {p}')
plist = [Person('Pete', 'Piper'), Person('Joe', 'Jones')]
person = Person('Pete', 'Jones')
check(plist, person)
person.surname = 'Piper'
check(plist, person)
Output:
Could not find Pete Jones
Found Pete Piper
You probably want a mapping between a name and an object. This is what Python's dict dictionary structure is for:
people = {} # an empty dictionary
people[f'{person1.f_name} {person1.l_name}'] = person1
people[f'{person2.f_name} {person2.l_name}'] = person2
This is creating a string of the first and last name.
You can then lookup the Person object using the full name:
print(people['Peter Punk'])
You could do this with list comprehension like so (also allowing multiple people to have the same first name)
class Person:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
__str__(self):
return "The persons full name is:" + f_name + l_name
personList= []
personList.append(Person(Peter, Punk))
personList.append(Person(Mia, Munch))
personName = input("What persons full name would you like to know?")
print([str(person) for person in personList if person.f_name == personName])

How to make each instance of a child class not require parent attributes (kinda?)

class User:
def __init__(self, username):
self.username = username
#classmethod
def get_user(cls):
return cls(input("Username: "))
class Budget(User):
def __init__(self, monthtly_income):
super().__init__(User.get_user())
self.monthly_income = monthtly_income
self.perc_lis = []
self.category_obj_lis = []
self.category_name_lis = []
self.value_lis = []
...
# creates objects and adds them to a list
for i in range(len(self.category_name_lis)):
self.category_obj_lis.append("")
self.category_obj_lis[i] = Category(self.category_name_lis[i], self.monthly_income)
...
class Category(Budget):
def __init__(self, name, monthly_income):
super().__init__(monthly_income)
self.name = name
self.perc = 0
self.amt = 0
self.left = 0
self.max = 0
# defines the percentage for each category
def get_perc(self):
self.perc = float(input(f"{self.name}: "))
When I run this it asks for username 3 times after I have asked for the categories because I create each Category object in a loop. Username is asked for at the start of the code. I need the category class to be a child class because I need the monthly_income variable to use in code not posted. I am not very good at inheritance so i could easily be missing something obvious. Is there a way for each instance of Category to not ask for username and just use the one already asked in the beginning? I apologize if this is somewhat confusing but idk where to go from here.

I need to figure out how to save the user input as the new variables, not sure what to do from here

#I need to figure out how to save the user input as the new variables, not sure what to do from here.
class Person:
def __init__(self):
#I'm supposed to have the object set to these generic names at first and then after the prompt function they need to be updated.
self.name = 'anonymous'
self.b_year = 'unknown'
def prompt(self):
print('Please enter the following:')
self.name = input('Name: ')
self.b_year = input('Year: ')
b = Book()
b.prompt()
def display(self):
print(f'Author:\n{self.name} (b. {self.b_year})\n')
class Book:
def __init__(self):
self.title = 'untitled'
self.publisher = 'unpublished'
def prompt(self):
self.title = input('Title: ')
self.publisher = input('Publisher: ')
def display(self):
print(f'\n{self.title}\nPublisher:\n{self.publisher}')
p = Person()
`enter code here`p.display()
def main():
p = Person()
b = Book()
b.display()
p.prompt()
b.display() #right here I need it to display the new information
if __name__ == '__main__':
main()
Two things you need to do here. First of all you need to initialize your variables in your Person class. Second of all I don't understand what the point of creating objects in a class and then doing the same outside of the class. I suggest taking the following code and modifying it to your likings. Additionally I reorganized the way you call your methods. First you prompt the user with all the necessary questions, then display them all together.
class Person:
def __init__(self):
self.name = None
self.b_year = None
def prompt(self):
print('Please enter the following:')
self.name = input('Name: ')
self.b_year = input('Year: ')
def display(self):
print(f'Author:\n{self.name} (b. {self.b_year})\n')
class Book:
def __init__(self):
self.title = 'untitled'
self.publisher = 'unpublished'
def prompt(self):
self.title = input('Title: ')
self.publisher = input('Publisher: ')
def display(self):
print(f'\n{self.title}\nPublisher:\n{self.publisher}')
def main():
p = Person()
b = Book()
b.display()
p.display()
p.prompt()
b.prompt()
b.display()
p.display()#right here I need it to display the new information
if __name__ == '__main__':
main()
output
untitled
Publisher:
unpublished
Author:
None (b. None)
Please enter the following:
Name: a
Year: b
Title: c
Publisher: d
c
Publisher:
d
Author:
a (b. b)
I'm not designer so you don't have to go with my idea, but IMO, don't add \n like this '\n{self.title}\nPublisher:\n{self.publisher}'. It looks a bit weird in the output.
You create one Book in the main function, and then another Book inside the Person.prompt method. They aren't the same Book - you have two!
You need to decide if a book belongs within a person, or whether they are two top level objects that may have a relationship. From a "real world" perspective, I don't think a person should automatically have a book associated with them. Perhaps you could create a Book and then pass to the Person constructor...

Python object creating a group with 3 members of aggregation relationship

I had an assignment to create a python code using class to create a group with 3 members (aggregation relationship). This is my code so far:
class Member:
def __init__(self,name,age):
self.name = name
self.age = age
def getInfo(self):
memberInfo = "Name: " + str(self.name) + "." + "Age: " + str(self.age)
return memberInfo
class Group:
def __init__(self,name):
self.name = name
self.memlist = []
def addMember(self,member):
self.memlist.append(member)
def getInfo(self):
info = "Member List: \n"
for i in range(len(self.memlist)):
info += self.memlist[i].getInfo() + "\n"
print(info)
break
mem1 = Member("Chi",20)
mem2 = Member("Bach",7)
mem3 = Member("Gen", 22)
group1 = Group("Siblings")
group1.addMember(mem1)
group1.addMember(mem2)
print(group1.getInfo())
print(mem2.getInfo())
print(group1.memList)
But it has shown an error: AttributeError: 'Group' object has no attribute 'memList'. Is there anything I can do to fix this?
I wrote little function for listing members and their ages.
class member:
def __init__(self, name, age):
self.name = name
self.age = age
def member_Info(self):
memberInfo = f"Name: {str(self.name)}-->Age: {str(self.age)}"
return memberInfo
class Group:
def __init__(self, name):
self.name = name
self.memlist = []
def addMember(self, name):
self.memlist.append(name)
def getInfo(self):
for i in range(len(self.memlist)):
info = self.memlist[i].member_Info() + "\n"
print(info)
This all_members function is basically getting the information stored in the member class and return to list. I print using memlist in Group but it didn't work out so I made a new list using all_member function and get information from memlist in group1 with the code that you used for getting information in memlist at group1.getInfo .
def all_members():
all_mems = []
for i in range(len(group1.memlist)):
all_mems.append(group1.memlist[i].member_Info())
print(all_mems)
mem1 = member("Chi", "20")
mem2 = member("Bach", "7")
mem3 = member("Gen", "22")
group1 = Group("Siblings")
group1.addMember(mem1)
group1.addMember(mem2)
group1.addMember(mem3)
print(group1.getInfo())
print(mem2.member_Info() + "\n")
print(all_members())
I guess this isn't the best answer you can get but I think it will work and also I learn many things while trying to correct it so thank you for posting that.
change
print(group1.memList)
to
print(group1.memlist)

Understanding Inheritance

I'm trying to understand inheritance better. In the following code, when I try to print friend.salary, it throws an AttributeError. Doesn't WorkingStudent inherit all methods of the Student class?
class Student:
def __init__(self,name,school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks)/len(self.marks)
def friend(self,friend_name):
return Student(friend_name, self.school)
anna = Student("Anna","MIT")
friend = anna.friend("Motilal")
#print (friend.name)
#print (friend.school)
class WorkingStudent(Student):
def __init__(self,name,school,salary):
super().__init__(self,name,school)
self.salary = salary
anna = WorkingStudent("Anna","SXS",25000)
anna.friend("Greg")
anna.marks.append(50)
print friend.salary
You should modify your source code as below
class Student:
def __init__(self,name,school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks)/len(self.marks)
def friend(self,friend_name):
return Student(friend_name, self.school)
anna = Student("Anna","MIT")
friend = anna.friend("Motilal")
#print (friend.name)
#print (friend.school)
class WorkingStudent(Student):
def __init__(self,name,school,salary):
super(WorkingStudent,self).__init__(name,school)
self.salary = salary
# anna = WorkingStudent("Anna","SXS",25000)
def friend(self,friend_name):
return WorkingStudent(friend_name, self.school, self.salary)
# You should put your code here, because as your original code
# anna is an instance of Student not WorkingStudent class
# so it and its friend don't have "salary".
anna = WorkingStudent("Anna","SXS",25000) # After this line, anna is a different variable to "anna" variable that was defined before (anna = Student("Anna","MIT"))
friend = anna.friend("Greg") # friend now is an instance of WorkingStudent class, so it have salary
anna.marks.append(50)
print(friend.salary)
Editted. So code can work now

Categories