I am probably making a big mess right now... But I want to create a menu that can activate different classes that holds attributes. What would be the easiest way to write this?
import replit
class Logistics_System():
print("Welcome to Express Delivery")
user = []
def menu(self):
while True:
print("")
print("[1]. Add/remove/update: user to the system.")
print("[2]. Add/remove/update: corporate customer.")
print("[3]. Add/remove/update: private customer.")
print("[4]. Add bike to the system.")
print("[5]. Add Truck to the system.")
print("[6]. Add Ship to the system.")
print("[7]. Create shipment/order of items. ")
print("[8]. Add Items to a shipment.")
print("[9]. Update status of order.")
print("")
try:
option = int(input("Choose from the menu: "))
if option == 1:
b.User()
else:
print("Program quits")
break
except:
print("Wrong value!")
self.menu()
b = Logistics_System()
b.menu()
class User(Logistics_System):
user_list = []
def __init__(self, first, last, id, adress, number, email, password, path):
self.first = first
self.last = last
self.email = first + '.' + last + '#expressdelivery.com'
self.id = id
self.adress = adress
self.number = number
self.password = password
def user_input():
try:
first = input("First name: ")
last = input("Last name: ")
id = input("ID: ")
adress = input("Adress: ")
number = int(input("Number: "))
if user_list >= 0:
user_list.append([first, last, email, id, adress, number, password])
except:
print("Wrong value!")
I wanted to save these values to a csv file so I can remove data or add data when I need to
Related
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()
So im having trouble displaying the admins first name, for some reason it keeps saying it doesnt exist, please give me some feedback on whats wrong, very appreciated
below you can find the admin class where we set all parameters like first name and last name etc
after that weve got the bank system class where ive imported the admin class and instanced it and still nothing, even after adding the missing positional argument it says that fname does not exist
class Admin:
def __init__(self, fname, lname, address, user_name, password, full_rights):
self.fname = fname
self.lname = lname
self.address = address
self.user_name = user_name
self.password = password
self.full_admin_rights = full_rights
def update_first_name(self, fname):
self.fname = fname
def update_last_name(self, lname):
self.lname = lname
def get_first_name(self):
return self.fname
def get_last_name(self):
return self.lname
from customer_account import CustomerAccount
from admin import Admin
accounts_list = []
admins_list = []
class BankSystem(object):
def __init__(self):
self.accounts_list = []
self.admins_list = []
self.load_bank_data()
def load_bank_data(self):
# create admins
admin_1 = Admin("Julian", "Padget", ["12", "London Road", "Birmingham", "B95 7TT"], "id1188", "1441", True)
self.admins_list.append(admin_1)
admin_2 = Admin("Cathy", "Newman", ["47", "Mars Street", "Newcastle", "NE12 6TZ"], "id3313", "2442", False)
self.admins_list.append(admin_2)
def search_admins_by_name(self, admin_username):
found_admin =None
for a in self.admins_list:
username =a.get_username()
if username ==admin_username:
found_admin =a
break
if found_admin ==None:
print("\n The Admin %s does not exist! Try again...\n"%admin_username)
return found_admin
def main_menu(self):
#print the options you have
print()
print()
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("Welcome to the Python Bank System")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("1) Admin login")
print ("2) Quit Python Bank System")
print (" ")
option = int(input ("Choose your option: "))
return option
def run_main_options(self):
loop = 1
while loop == 1:
choice = self.main_menu()
if choice == 1:
username = input ("\n Please input admin username: ")
password = input ("\n Please input admin password: ")
admin_obj = self.admin_login(username, password)
if admin_obj != None:
self.run_admin_options(admin_obj)
elif choice == 2:
loop = 0
print ("\n Thank-You for stopping by the bank!")
def admin_login(self, username, password):
found_admin=self.search_admins_by_name(username)
msg="\n Login failed"
if found_admin!=None:
if found_admin.get_password()==password:
print("Login Sucssesful")
return msg,found_admin
def admin_menu(self, admin_obj):
#print the options you have
admin_obj = Admin
print (" ")
print ("Welcome Admin %s %s : Avilable options are:" %(admin_obj.get_first_name(), admin_obj.get_last_name()))
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("1) Transfer money")
print ("2) Customer account operations & profile settings")
print ("3) Delete customer")
print ("4) Print all customers detail")
print ("5) Sign out")
print (" ")
option = int(input ("Choose your option: "))
return option
app = BankSystem()
app.run_main_options()
At least two problems:
BankSystem.admin_login() returns a pair consisting of a message and an admin object, but run_main_options() assigns that pair to a single variable admin_obj. You should change it to something like msg, admin_obj = … to behave like you appear to expect.
BankSystem.admin_menu() overwrites the object it was passed on the first line. This line should be removed.
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
I am trying to allow a member to leave the Team if they so wish. By doing this, the system will delete them and their user ID will become available to the next person who wishes to join the team. I am receiving an error with my code. Can someone please advise what I am doing wrong and how this can be achieved?
I would like my add members and remove members to update all the time, based on user input and the needs of the members. I hope this makes sense!
For example: If 'Carl' decided to leave, he would be removed and the next member to join would be assigned the membership ID '2'
Below is my code:
all_users = []
class Team(object):
members = []
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
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")
all_users.append(Team(first_name, second_name, address))
#staticmethod
def remove_member():
print()
print("We're sorry to see you go , please fill out the following information to continue")
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")
unique_id = input("Finally, what is your User ID?\n")
if unique_id in all_users:
del unique_id
all_users(User(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. Want to join the team?")
print("3. Need to leave the team?")
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:
Team.remove_member()
elif choice == 4:
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()
The remove_member method is wrong for several reasons. The line del unique_id will not remove the value from all_users, which is just a list of Team Members. And you shouldn't have to ask the user for all of this information - just the ID (or the name) would be enough.
What I suggest is:
#staticmethod
def remove_member():
print()
print("We're sorry to see you go , please fill out the following information to continue")
print()
unique_id = input("what is your User ID?\n")
unique_id = int(unique_id)
for i, user in enumerate(all_users):
if user.user_id == unique_id:
all_users.remove(i)
break
If it is important that the user ids are reused, you can keep a list of user ids that are available again. When creating a new member, you can first check that list, and use an old id if there is one.
You can also choose not to reuse the user ids of removed users. An id doesn't really have a meaning and not reusing it makes it simpeler for you.
Finally, you might want to restructure your code:
Team(first_name, second_name, address)
This doesn't make sense: a team with a first name, last name and adress! Better would be to have two classes:
team = Team()
user = User(first_name, second_name, address)
team.add_member(user)
team.remove_member(user)
Some other tips:
# This won't work, because all_users contains Team instances, not numbers. So the user will never be found.
if unique_id in all_users:
# This won't do anything: `del` only removes the access to the variable (might free up memory in heavy applications). It doesn't remove the user from all_users
del unique_id
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()