How to pass user inputs to an object of a class? - python

This code is a Simple Student Management System in which I want it to receive inputs from the user and display according to the call. I have created a class Student and initialized the variables. I created a method accept(self) for receiving the user inputs and appending the details to a list of dictionaries. But I am stuck on how I can initialize the inputs that I have received. How can I call the methods outside of class Student since I am unable to create an object for class Student? I am a beginner in Python. Having a hard time understanding OOP. Please help me!
Here is the code I wrote:
class Student:
student_details = []
def __init__(self, name, rollno, mark1, mark2):
self.name = name
self.rollno = rollno
self.mark1 = mark1
self.mark2 = mark2
def accept(self):
no_of_entries = int(input("Enter the number of entries: "))
i = 1
while i <= no_of_entries:
print(f"Student {i}")
name = input("Name: ")
rollno = int(input("Roll: "))
mark1 = int(input("Mark 1: "))
mark2 = int(input("Mark 2: "))
Student(name, rollno, mark1, mark2).student_details.append({
"Name": self.name,
"Rollno": self.rollno,
"Mark1": self.mark1,
"Mark2": self.mark2,
})
print()
i += 1
print(Student.student_details)
student1 = Student()
proceed = True
while proceed:
print("STUDENT MANAGEMENT SYSTEM".center(50, '-'))
print()
print("* Accept Student entries (1): ")
print("* Search Student entries (2): ")
print("* Update Student entries (3): ")
print("* Delete Student entries (4): ")
print("* Display Student entries (5): ")
choice = int(input("Enter your choice: "))
if choice == 1:
I get the error:
Student.__init__() missing 4 required positional arguments: 'name', 'rollno', 'mark1', and 'mark2'
I don't know what to do. Even this is the problem I am facing with OOP in Python. If anyone can help me with this than I will be grateful

EDIT: The callback comes from the student1 = Student()
delete the statement and declare the accept method as a static method.
Then you can deklare a student in the method and can appent the student.
Your mistake should be here:
Student(name, rollno, mark1, mark2).student_details.append({
"Name": self.name,
"Rollno": self.rollno,
"Mark1": self.mark1,
"Mark2": self.mark2,
})
You try to initialise a object and then you try to use it as a dict.
st1 = Student(name, rollno, mark1, mark2)
Student.student_details.append(st1)
Also you can use a classattribut in a object but the changes will only be present in the object. It wouldnt be in all object.
It would be best make the method accept in a function or you will end up with many object with the same values.
If you want to leave it as a method you can change the code to:
Student.student_details.append(self)

By default methods defined in a Python class are instance methods, so they need to be called on an already-existing object instance. If you want to create a custom constructor, the method should be probably marked as a class method by using #classmethod decorator, so it can be called on the class itself.
class Student:
student_details = []
def __init__(self, name, rollno, mark1, mark2):
self.name = name
self.rollno = rollno
self.mark1 = mark1
self.mark2 = mark2
#classmethod
def accept(cls):
no_of_entries = int(input("Enter the number of entries: "))
for i in range(no_of_entries):
print(f"Student {i}")
name = input("Name: ")
rollno = int(input("Roll: "))
mark1 = int(input("Mark 1: "))
mark2 = int(input("Mark 2: "))
student = cls(name, rollno, mark1, mark2)
cls.student_details.append(student)
print(cls.student_details)
Student.accept()

student1 = Student()
you need to pass 4 parameters here
def __init__(self, name, rollno, mark1, mark2):
So you should have
student1 = Student('name', 'rollno', 'mark1', 'mark2')
or something

You forgot to put arguments when you call that class.
For example:
student1 = Student(name='a', rollno='0', mark1='1', mark2='2')
I'm not sure what your objective is. If you just want to input student information into a list, maybe the code below can give you an idea.
class Student:
student_details = []
def __init__(self, name, rollno, mark1, mark2):
self.name = name
self.rollno = rollno
self.mark1 = mark1
self.mark2 = mark2
student_list = []
print("STUDENT MANAGEMENT SYSTEM".center(50, '-'))
print()
print("* Accept Student entries (1): ")
print("* Search Student entries (2): ")
print("* Update Student entries (3): ")
print("* Delete Student entries (4): ")
print("* Display Student entries (5): ")
choice = int(input("Enter your choice: "))
if choice == 1:
print("You have selected (1) - Accept Student entries")
no_of_entries = int(input("Enter the number of entries: "))
for i in range(0, no_of_entries):
print("Input student no", i+1, "information.")
student = Student(name=input("Name: "), rollno=input("Roll: "), mark1=input("Mark 1: "), mark2=input("Mark 2: "))
student_list.append(student)
elif choice == 2:
pass
elif choice == 3:
pass
elif choice == 4:
pass
elif choice == 5:
pass
else:
print("Invalid choice.")

Related

Problem with referring to methods in classes in python

i have this code:
class Contact:
def __init__(self, name, phone):
Contact.name = name
Contact.phone = phone
class AddContact:
def __init__(self):
self.People = []
def add_people(self, x):
self.People.append(x)
def print_contact(self):
for x in self.People:
print("name:" + x.name)
print("phone:", x.phone)
while True:
print("----MENU----")
print("1 -> add contact")
print("2 -> contact list")
choice = int(input("enter your choice: "))
if choice == 1:
name = input("enter the name of the contact: ")
phone = input("enter the phone number of the contact: ")
person = Contact(name, phone)
AddContact.add_people(person)
if choice == 2:
AddContact.print_contact()
what im trying to make is a contact book where the user can add and view all of his contacts, ive recently learned classes and thought this was the correct way to make it but i get issues the erros im getting is that the parameters x and self are unfilled on this line:
def add_people(self, x):
when i call them below outside of the class, ive been trying but i dont understand the problem and would like some assistance.
thanks is advance.
You are using AddContact wrong. You need to create an instance of it (just like you created an instance of Contact).
While we are at it, PhoneBook would be a much better name for this class.
...
class PhoneBook:
def __init__(self):
self.People = []
def add_people(self, x):
self.People.append(x)
def print_contact(self):
for x in self.People:
print("name:" + x.name)
print("phone:", x.phone)
phone_book = PhoneBook()
while True:
print("----MENU----")
print("1 -> add contact")
print("2 -> contact list")
choice = int(input("enter your choice: "))
if choice == 1:
name = input("enter the name of the contact: ")
phone = input("enter the phone number of the contact: ")
person = Contact(name, phone)
phone_book.add_people(person)
if choice == 2:
phone_book.print_contact()

ValueError: not enough values to unpack (expected 3, got 2) & TypeError: must be str, not MemberClass

Below is my code for a class I am currently working. The title contains the errors I am receiving. Could someone please assist with my code? (The comment's explain the area of concern. Main Menu functions 5 & 6.)
PART 1 - CLASS ESTABLISHMENT
class MemberClass:
name = ""
phone = 0
number = 0
# Initiator Method
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
# Mutator Method 1
def set_name(self, name):
self.name = name
# Mutator Method 2
def set_phone(self, phone):
self.phone = phone
# Mutator Method 3
def set_number(self, number):
self.number = number
# Accessor Method 1
def get_name(self):
return self.name
# Accessor Method 2
def get_phone(self):
return self.phone
# Accessor Method 3
def get_number(self):
return self.number
# Display Method
def display_data(self):
print("")
print("Current Team Member's Information")
print("------------------------------------------------")
print("Member's Name: ", self.name)
print("Member's Phone Number: ", self.phone)
print("Member's Jersey Number: ", self.number)
print("------------------------------------------------")
PART 2 - PROGRAM FUNCTIONS AND DATA
# Create a function for the main menu
def print_menu():
print("===========Main Menu===========")
print("1. Display Current Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Progress.")
print("6. Load Current Team Roster")
print("9. Exit Program.\n")
return int(input("Please Enter Your Selection: "))
# Create a function for main menu option 1
def print_members(team_members):
if len(team_members) == 0:
print("No Current Team Members In Memory! Please Add All Team Members.")
else:
for x in team_members.keys():
team_members[x].display_data()
# Create a function for main menu option 2
def add_members(team_members):
new_name = input("Enter New Team Member's Name: ")
new_phone = int(input("Enter New Team Member's Phone Number: "))
new_number = int(input("Enter New Team Member's Jersey Number: "))
team_members[new_name] = MemberClass(new_name, new_phone, new_number)
return team_members
# Create a function for main menu option 3
def remove_members(team_members):
remove_name = input("Enter Existing Team Member's Name to Remove: ")
if remove_name in team_members:
del team_members[remove_name]
print("The Team Member ("+remove_name+") Is No Longer In Our Roster.")
else:
print("The Provided Name ("+remove_name+") Is Not Currently In Our Roster. Please Try Again.")
return team_members
# Create a function for main menu option 4
def edit_members(team_members):
original_name = input("Enter Existing Team Member's Name To Edit: ")
if original_name in team_members:
adjusted_name = input("Enter Existing Team Member's Updated Name: ")
adjusted_phone = int(input("Enter Existing Team Member's Updated Phone Number: "))
adjusted_number = int(input("Enter Existing Team Member's Updated Jersey Number: "))
del team_members[original_name]
team_members[original_name] = MemberClass(adjusted_name, adjusted_phone, adjusted_number)
else:
print("The Provided Name ("+original_name+") Is Not Currently In Our Roster. Please Try Again.")
return team_members
# Create a function for main menu option 5 ***PROBLEM AREA***
def save_members(members, filename):
out_file = open(filename, "wt")
with open(filename, "wt") as out_file:
for name, phone, number in members.items():
out_file.write(name + "," + phone + "," + number + "\n")
# Create a function for main menu option 6 ***PROBLEM AREA***
def load_members(members, filename):
in_file = open(filename, "rt")
with open(filename, "rt") as in_file:
while True:
in_line = in_file.readline()
if not in_line:
break
in_line = in_line[:-1]
name, phone, number = in_line.split(",")
members[name] = phone
PART 3 - PROGRAM ROOT CODE
# Team manager welcome screen, date & time
print("Welcome to San Angelo's Softball Team Roster")
print("This program keeps the most up-to-date information")
print("Today's Date: April 23, 2018")
print("Current Time: 0900\n")
# Create a dictionary named "team_members"
team_members = {}
# Provides Menu Screen
menu_selection = print_menu()
# Create while loop repeating the main menu.
while menu_selection != 9:
if menu_selection == 1:
print_members(team_members)
elif menu_selection == 2:
team_members = add_members(team_members)
elif menu_selection == 3:
team_members = remove_members(team_members)
elif menu_selection == 4:
team_members = edit_members(team_members)
elif menu_selection == 5:
filename = input("Enter Desired Filename: ")
save_members(team_members, filename)
elif menu_selection == 6:
filename = input("Enter Existing Filename: ")
load_members(team_members, filename)
menu_selection = print_menu()
print("Thank You For Updating San Angelo's Softball Team Roster!")
When you iterate a dictionary via dict.items, you may only iterate key / value pairs. Therefore, this line will fail as you are attempting to unpack 3 items when only 2 exist (key & value):
for name, phone, number in members.items():
Instead, what you should do:
for name, myclass in members.items():
phone = myclass.phone
number = myclass.number

How to add items to a class based on user input

I'm in the process of learning python and I am attempting to create a class for a football team. I am just working with different aspects of python to try and get a better understanding. I want a menu based system which will allow the user of the programme to either view all current team members or else register to join the team. Each team member will have a unique ID and when a person joins, it will simple give them the next available number. For example, Chris has the unique ID of 1, Carl has 2, so if Joe joins, he will be automatically given number three. Below is the code I currently have. Viewing card players works perfectly for me but I am struggling with adding a new player.
So my question is, how do I add a new member to the empty list I have which will store all my data and how do I implement that the next person who joins the team will be given the next available number? This is to ensure each member number is unique. Thanks in advance, eager to learn!
class Team(object):
members = [] #create an empty list to store data
def __init__(self, user_id, first, last, address):
self.user_id = user_id
self.first = first
self.last = last
self.address = address
self.email = first + '.' + last + '#python.com'
#instance is fully initialized so I am adding it to the list of users
Team.members.append(self)
def __str__(self):
print()
return 'Membership ID: {}\nFirst Name: {}\nSurname: {}\nLocation: {}\nEmail: {}\n'.format(self.user_id, self.first, self.last, self.address, self.email)
print()
#staticmethod
def all_members():
for user in Team.members:
print (user)
def add_member(Team):
print()
print("Welcome to the team!")
print()
first_name = input("What's your first name?\n")
second_name = input("What's your surname?\n")
address = input("Where do you live?\n")
for x in Team:
unique_id = unique_id =+ 1
user[user_id] = [user_id, first_name, second_name, address]
user_1 = Team(1, 'Chris', 'Parker', 'London')
user_2 = Team(2, 'Carl', 'Lane', 'Chelsea')
def menu(object):
continue_program = True
while continue_program:
print("1. View all members")
print("2. Add user")
print("3. Quit")
try:
choice = int(input("Please pick one of the above options "))
if choice == 1:
Team.all_members()
elif choice == 2:
Team.add_member(object)
elif choice == 3:
continue_program = False
print()
print("Come back soon! ")
print()
else:
print("Invalid choice, please enter a number between 1-3")
menu(object)
except ValueError:
print()
print("Please try again, enter a number between 1 - 3")
print()
#my main program
menu(object)
Things changes:
main function operation changed
user count field made static and automatically created with addition of new user
temp list created to hold users
please comment if you don't understand
all_users = []
class Team(object):
members = [] # create an empty list to store data
user_id = 0
def __init__(self, first, last, address):
self.user_id = Team.user_id
self.first = first
self.last = last
self.address = address
self.email = first + '.' + last + '#python.com'
Team.user_id += 1
# instance is fully initialized so I am adding it to the list of users
Team.members.append(self)
def __str__(self):
print()
return 'Membership ID: {}\nFirst Name: {}\nSurname: {}\nLocation: {}\nEmail: {}\n'.format(self.user_id,
self.first, self.last,
self.address,
self.email)
print()
#staticmethod
def all_members():
for user in all_users:
print(user)
#staticmethod
def add_member():
print()
print("Welcome to the team!")
print()
first_name = input("What's your first name?\n")
second_name = input("What's your surname?\n")
address = input("Where do you live?\n")
# for x in Team:
# unique_id = unique_id = + 1
all_users.append(Team(first_name, second_name, address))
def main():
user_1 = Team('Chris', 'Parker', 'London')
user_2 = Team('Carl', 'Lane', 'Chelsea')
all_users.extend([user_1, user_2])
continue_program = True
while continue_program:
print("1. View all members")
print("2. Add user")
print("3. Quit")
try:
choice = int(input("Please pick one of the above options "))
if choice == 1:
Team.all_members()
elif choice == 2:
Team.add_member()
elif choice == 3:
continue_program = False
print()
print("Come back soon! ")
print()
else:
print("Invalid choice, please enter a number between 1-3")
main()
except ValueError:
print()
print("Please try again, enter a number between 1 - 3")
print()
if __name__ == "__main__":
main()
You are so close:
#staticmethod
def add_member(): # belongs to the class
print()
print("Welcome to the team!")
print()
first_name = input("What's your first name?\n")
second_name = input("What's your surname?\n")
address = input("Where do you live?\n")
# get the maximum id and add one
if Team.members:
unique_id = max(Team.members, key=lambda m: m.user_id) + 1
else:
unique_id = 0
Team(unique_id , first_name, second_name, address)
And in the main function change on call:
elif choice == 2:
Team.add_member()

adding data to a database on python

I am trying to create a simple database on python that:
- Add a record, delete a record, report on the database
(I am very new to this program and programming in general)
*NOTE: I am aware there are programs like SQL but my professor wants us to create a a database simply with what we learned in class *
I am having serious trouble on being able to store: ID, Class Name, and Class instructor
into one record of "Classes". I have been able to display the class ID and class name but I'm not sure how to add an instructor's name.
This is what I have currently:
def print_menu():
print('1. Print Class Records')
print('2. Add a Class')
print()
classes = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = int(input("Type in a number (1-5): "))
if menu_choice == 1:
print("Class Reports:")
for x in classes.keys():
print("Class ID: ", x, "\tClass Name:", classes[x], "\tClass Instructor:",)
print()
elif menu_choice == 2:
print("Add ClassID, Class Name, and Instructor Name")
classID = input("ID: ")
className = input("Class Name: ")
classInst = input("Class Instructor: ")
classes[classID] = className
elif menu_choice != 5:
print_menu()
I feel that I will be able to do the rest of the professor's requirements for this project but I have been stuck on this part for days with no response from my professor
I would highly appreciate quick responses as this assignment is due tonight at 11:59 and I am reaching out for help here as a last resort.
Thank you!
In your case, what you can do is, insert the ID as a key for each class and then insert a dictionary as it's value. What I mean by this is that each key on the classes dict, points to another dictionary as its value.
elif menu_choice == 2:
print ("Add ClassID, Class Name, and Instructor Name")
classID = input("ID: ")
className = input("Class Name: ")
classInst = input("Class Instructor: ")
classes[classID] = {"className" : className, "classInst" : classInst}
and printing the values as
print("Class ID: ", x , "\tClass Name:" , classes[x]["className"] , "\tClass Instructor:" , classes[x]["classInst"])

Why are some variables not defined?

This is what I have to do:
Look up and print the student GPA
Add a new student to the class
Change the GPA of a student
Change the expected grade of a student
Print the data of all the students in a tabular format
Quit the program
import student
import pickle
lookup = 1
change = 2
add = 3
delete = 4
QUIT = 0
FILENAME = 'student.dat'
def main():
students_info = load_students()
choice = 0
load_students()
#add(students_info)
change_grade(students_info)
change_GPA(students_info)
#get_menu_choice()
look_up(students_info)
while choice != QUIT:
choice = get_menu_choice()
if choice == lookup:
look_up(students_info)
elif choice == add:
add(students_info)
elif choice == change:
change(students_info)
elif choice == delete:
delete(students_info)
save_students(students_info)
def load_students():
try:
input_file = open(FILENAME, 'rb')
students_dict = pickle.load(input_file)
input_file.close()
except IOError:
students_dict = {}
print(students_dict)
return students_dict
def get_menu_choice():
print()
print('Menu')
print("-------------------")
print('1. Look up ID')
print('2.....')
choice = int(input("Enter your choice:"))
return choice
def look_up(students_info):
ID = input('Enter ID:')
print(student_info.get(ID, "Not found!"))
## try:
## print(students_info[ID])
## except KeyError:
## print("Not found!")
def change_GPA(students_info):
ID = input("ID:")
if ID in students_info:
GPA= float(input("New GPA:"))
students=student.Student(ID,GPA,grade,work)
students_info[ID] = students
print ("This",students_info[ID])
else:
print("Not found!")
def change_grade(students_info):
ID = input("ID:")
if ID in students_info:
New_grade = input("Enter new grade:")
students=student.Student(ID,GPA,grade,work)
students_info[ID] = students
#new_grade = students_info[name]
else:
print("Not found!")
def add(students_info):
name = input("Enter the student name:")
ID= input("Enter student's ID:")
GPA= float(input("Enter GPA:"))
grade= input("Enter student's expected grade:")
work = input("Does the student work part time or full time?")
students=student.Student(name,ID,GPA,grade,work)
print(students_info['ID'])
def save_students(students_info):
output_file = open(FILENAME, 'wb')
pickle.dump(students_info, output_file)
output_file.close()
main()
Whenever I tried to change the GPA or grade it's not defined. How could I change one value from the dictionary studens_info?
As gus42 has commented, the errors you are getting are from the lines:
students=student.Student(ID,GPA,grade,work)
You've not defined grade or work in either of the places you do this (nor GPA in change_grade), so it should not be surprising that you're getting an error.
I think there are two ways to fix the issue:
The simplest way is to change your logic from creating a new Student object to modifying the one that already exists. I don't know exactly what the attribute names are in your Student class, but here's a reasonable guess at a solution:
def change_GPA(students_info):
ID = input("ID:")
if ID in students_info:
GPA= float(input("New GPA:"))
students_info[ID].GPA = GPA # assign new GPA to old student object
else:
print("Not found!")
def change_grade(students_info):
ID = input("ID:")
if ID in students_info:
grade = input("Enter new grade:")
students_info[ID].grade = grade # assign new grade to existing student object
else:
print("Not found!")
The other option is to replace the existing Student object with a new one with some different values. This is close to what your current code, but it only really makes sense if your Student objects are immutable (perhaps because you made the type with namedtuple?). To make it work (where your current code does not), you'll have to load the old values from the old Student object before making the new object:
def change_GPA(students_info):
ID = input("ID:")
if ID in students_info:
new_GPA = float(input("New GPA:"))
old_grade = students_info[ID].grade # load old values
old_work = students_info[ID].work
new_student = students.Student(ID, new_GPA, old_grade, old_work)
students_info[ID] = new_student # replace the old student with a new object
else:
print("Not found!")
def change_grade(students_info):
ID = input("ID:")
if ID in students_info:
new_grade = input("Enter new grade:")
old_GPA = students_info[ID].GPA
old_work = students_info[ID].work
new_student = students.Student(ID, old_GPA, new_grade, old_work)
students_info[ID] = new_student
else:
print("Not found!")

Categories

Resources