Attribute Error when importing dictionary from module to another - python

So I have 4 different classes which I need to combine into one class at the end in a program called "Main" . However whenever I run the Main program, it keeps throwing up an attribute error when it comes to accessing the emp_det dictionary from the Employee class into the other classes so I can use the generated Employee ID stored in the dictionary. (There are two more classes called Weekly_Paid and Timecard but I've only mentioned 3 for the sake of the brevity and because the error seems to be universal).
(All 3 classes are in different files.)
The error I keep getting:
Traceback (most recent call last):
File "C:/Users/Saloni/Documents/Case Sudy 3/MAIN.py", line 28, in <module>
s.MaintainTimecard()
File "C:/Users/Saloni/Documents/Case Sudy 3\Monthly_Paid.py", line 24, in MaintainTimecard
if emp_id in Employee.emp_det:
AttributeError: module 'Employee' has no attribute 'emp_det'
Employee Class:
# ATTRIBUTES: emp_nm, emp_ph, emp_add,emp_id, emp_dob
from random import *
class Employee:
emp_det={} #dictioary to save the details of the employees
#emp_id:[emp_nm,emp_ph,emp_add,emp_dob]
def add_emp(self):
lst=[] #to store all inputed details
print("Enter Employee Details:")
emp_nm=input("Name: ")
emp_ph=input("Contact Number: ")
emp_add=input("Address: ")
emp_dob=input("Date of Birth:")
lst.extend([emp_nm,emp_ph,emp_add,emp_dob]) #store the details
emp_id="emp"+str(randrange(1000,10000))
while emp_id in Employee.emp_det: # avoid repetition
emp_id="emp"+str(randrange(1000,10000))
Employee.emp_det[emp_id]=lst # make dictionary key and store in list
print("Your Employee ID is",emp_id)
def del_emp(self):
t=0 # to count number of invalid inputs
while t<=3:
emp_id=input("Employee ID:")
if emp_id in Employee.emp_det:
del Employee.emp_det[emp_id]
t=4 # to get the program out of the loop
else:
print("Invalid ID. Try Again.")
t+=1
def edit_emp(self):
t=0 # counting invalid inputs
while t<=3:
emp_id=input("Employee ID:")
if emp_id in Employee.emp_det: # checking validity
print("\n Edit: \n 1.Contact \n 2.Address \n")
ch=int(input("Option:"))
if ch==1:
Employee.emp_det[emp_id][1]=input("New Contact Number:")
elif ch==2:
Employee.emp_det[emp_id][2]=input("New Address:")
else:
print("Invalid Option")
t=4 #t o get the program out of the loop
else:
print("Invalid ID. Try Again.")
t+=1
def Edisplay(self):
print("The Employees are:")
print(" ID \t Name \t Contact \t Address \t Date of Birth")
for i in Employee.emp_det: # access to each dictionary element
print(i,"\t",end=" ")
for j in Employee.emp_det[i]: # access every value under the key
print(j,"\t",end=" ")
print("\n")
Monthly-Paid Class
import Employee
import Timecard
class Monthly_Paid:
fixSalary = 40000
def AcceptTimeCard (self):
print ("Timecard details are:")
for i in Timecard.emp_tcinfo:
print(i, "\t", end ="")
for j in Timecard.emp_tcinfo[i]:
print(j,"\t",end=" ")
def Gen_Paycheck (self):
emp_id = input("please enter employee ID")
if emp_id in Employee.emp_det:
print ("Total Salary of " + emp_id + " is :" + fixSalary)
def MaintainTimecard (self):
emp_id = input("Please enter your employee ID")
if emp_id in Employee.emp_det:
print("\n 1.Edit Start Time Hour "
"\n 2.Edit Start Time Minute "
"\n 3. Edit End Time Hour "
"\n 4.Edit End Time Minute")
ch = int(input("Input option"))
if ch == 1:
Timecard.emp_tcinfo[emp_id][1] = input(
"Input new Start Time Hour")
if ch ==2:
Timecard.emp_tcinfo[emp_id][2] = input(
"Input new Start Time Minute")
if ch == 3:
Timecard.emp_tcinfo[emp_id][3] = input(
"Input new End Time Hour")
if ch == 4:
Timecard.emp_tcinfo[emp_id][4] = input(
"Input new End Time Minute")
else:
print("Invalid input")
Main script
print ("Welcome to Employee Time Card System")
import Employee
e= Employee.Employee()
e.add_emp()
print("What kind of employee are you?")
print ("\n 1.Monthly Paid \n 2.Weekly Paid")
ch= int(input("Enter Choice"))
if ch ==1:
import Monthly_Paid
import Timecard
s = Monthly_Paid.Monthly_Paid()
w = Timecard.Timecard()
print("Monthly Paid")
t1= "y"
while t1=="y" or t1=="Y":
print ("\n 1.See Time Card \n2.Edit TimeCard \n 3.See Paycheck")
ch1 = int(input("Enter Choice"))
if ch1 == 1:
s.AcceptTimeCard
if ch1 == 2:
s.MaintainTimecard()
if ch1 == 3:
s.Gen_Paycheck()
else:
print("Invalid Choice")
t1 = input("Continue with Monthly Paid? Y/N")
elif ch == 2:
import Weekly_Paid
a= Weekly_Paid.Weekly_Paid()
t2= "y"
print ("Weekly Paid")
while t2=="y" or t2=="Y":
print ("\n 1.See Time Card \n2.Edit TimeCard \n 3.See Paycheck")
ch1 = int(input("Enter Choice"))
if ch1 == 1:
a.AcceptTimeCard()
if ch1 == 2:
a.MaintainTimeCard()
if ch1 == 3:
a.Gen_Paycheck()
else:
print("Invalid Choice")
t2 = input("Continue with Weekly Paid? Y/N")
else:
print("Invalid choice")

import Employee will look for a module Employee.py. If there is no file called Employee.py then you won't be able to make that import work.
So in the Monthly-Paid Class file you have to do something like:
from path.to.employee_file_name import Employee
The problem then arises from the fact that there's a module called Employee but that contains a class called Employee. Importing the module Employee doesn't give you access to the class automatically. To access the attribute of the
Employee class called emp_det you have to specify the class. So if you imported using
from Employee import Employee
To access you need:
Employee.emp_det
Alternatively if you imported with:
import Employee
then to access you need:
Employee.Employee.emp_det

Related

python basic phonebook application with IO

I had a basic phone book application that adds, lookup, updates, and deletes a record and it works fine. I wanted to add functionality to it in which when I close and restart the program the previously added records are still there saved in a file. And when I want to add more records to the dictionary file it will also be appended to the file but I am running into 2 issues the first one is when I try to integrate my saved file with my dictionary I get error dictionary update sequence element #0 has length 1; 2 is required so I for some reason can't read the file to check if I have a record in the file with the same name for example. The second issue is when I Quit the program I added a save Record function which when run adds the newly added records onto the file to save it before it quits but when I print it, it only shows the first string printed the other is not shown I don't know what is causing this. Any help is appreciated thanks in advance.
#!/usr/bin/python3
import os.path
from os import path
phones = {}
if path.exists('phones.txt'):
with open("phones.txt") as f:
phones = dict(x.rstrip().split(None, 1) for x in f)
else:
phoneFile = open("phones.txt", "w")
print("File Created")
phoneFile.close()
with open("phones.txt") as f:
phones = dict(x.rstrip().split(None, 1) for x in f)
def menu():
print("1. Add a record")
print("2. Lookup a record")
print("3. Update a record")
print("4. Remove a record")
print("5. List all records")
print("6. Quit")
selection = input("Please make your selection from the options above: ")
if(selection == '1'):
addRecord()
menu()
elif(selection == '2'):
lookupRecord()
menu()
elif(selection == '3'):
updateRecord()
menu()
elif(selection == '4'):
removeRecord()
menu()
elif(selection == '5'):
listRecords()
menu()
elif(selection == '6'):
saveRecords()
print("Goodbye")
#exit(0)
else:
print("Sorry, invalid input, try again.")
menu()
def addRecord():
a = str(input("Person's name to add to record: "))
b = int(input("Number to add to record: "))
if a in phones:
print("Name already in records, Please choose another name")
else:
phones[a] = b
print(phones)
def lookupRecord():
a = str(input("Person's name to look: "))
if a in phones:
print(a + "'s number is " + str(phones.get(a)))
else:
print("Person not found")
def updateRecord():
a = str(input("Person's name to update: "))
if a in phones:
b = int(input("New phone number to update: "))
phones[a] = b
print(phones)
else:
print(a + " is not in your phone book")
def removeRecord():
a = str(input("Person's name to remove: "))
if a in phones:
del phones[a]
print(a + " removed from phone book")
else:
print("Name not found")
def listRecords():
for i in phones.items():
print(i)
def saveRecords():
for i in phones.items():
writePhoneFile = open("phones.txt", "w")
finalRecord = ':'.join('%s' %id for id in i)
writePhoneFile.write(finalRecord)
readPhoneFile = open("phones.txt", "r+")
print(readPhoneFile.read())
def main():
print("== Welcome to the Phonebook App ==")
menu()
if __name__ == "__main__":
main()
use below because phone number in integer :
phones = dict( (x.rstrip().split(':')[0] , int(x.rstrip().split(':')[1])) for x in f)
in addition, open the file outside for loop in saverecords:
writePhoneFile = open("phones.txt", "w")
for i in phones.items():
print(i)
finalRecord = ':'.join('%s' %id for id in i)+'\n'
writePhoneFile.write(finalRecord)
writePhoneFile.close()

Writing File and Reading from File in python

import random
class Student:
#easy way or short way to printing student details
def student_details(self):
print("Student number :",self.student_number)
print("-----------")
print("First Name : ",self._firstname)
print("-----------")
print("Last Name : ",self._lastname)
print("-----------")
print("Date Of Birth : ",self._date_of_birth)
print("-----------")
print("Gender : ",self._sex )
print("-----------")
print("Country of birth : ",self._country)
#constructor for the class and assign the variables(eg:firstname)
def __init__(self,firstname,lastname,date_of_birth,sex,country):
self.student_number = random.randint(1,18330751)
self._firstname = firstname
self._lastname = lastname
self._date_of_birth = date_of_birth
self._sex = sex
self._country = country
def get_firstname(self):
return self._firstname
def set_firstname(self,firstname):
self._firstname = firstname
def get_lastname(self):
return self._lastname
def set_lastname(self,lastname):
self._lastname = lastname
def get_date_of_birth(self):
return self._date_of_birth
def set_date_of_birth(self,date_of_birth):
self._date_of_birth = date_of_birth
def get_sex(self):
return self._sex
def set_sex(self,sex):
self._sex = sex
def get_country(self):
return self._country
def set_country(self,country):
self._country = country
#this method for converting object when writing to file and reading the file
def __str__(self):
return f"{firstname,lastname,date_of_birth,sex,country}"
student = []
while True:
print("1. Enter 1 and you are going Write the contents of the student array to a file")
print("-----------")
print("2.Read student data from a file and populate the student array.")
print("-----------")
print("3.Add a new student")
print("-----------")
print("4. Enter 4 and you are going to see all students information")
print("-----------")
print("5. Enter 5 and you are going to write born year to find students who born in this year")
print("-----------")
print("6. Enter 6 and you are going to modify a student record by typing student number because you can't change student number")
print("-----------")
print("7. Enter 7 and you are going to write student number to delete student")
print("-----------")
print("8. Enter 8 and exit the program")
print("-----------")
print("You can choose what to do")
option = int(input("Please write your option: "))
print("-----------")
if option == 1:
f = open("cmse318.txt","w")
for data in student:
f.write(data)
print("-----------")
print("Successfully write to a file!!")
print("-----------")
break
f.close()
if option == 2:
f = open("cmse318.txt","r")
for ln in f:
firstname,lastname,date_of_birth,sex,country = ln.split(",")
s = Student(firstname,lastname,date_of_birth,sex,country)
student.append(s)
print(s)
f.close()
if option == 3:
firstname,lastname,date_of_birth,sex,country = map(str,input("Please Enter student details like this(cemal,göymen,2000,male,cyprus) : ").split(","))
s = Student(firstname,lastname,date_of_birth,sex,country)
student.append(s)
print("-----------")
print('Student created successfully!!')
print("-----------")
print("-----------")
if option == 4 :
for st in student:
st.student_details()
print("-----------")
print("For now these are the students")
print("-----------")
if option == 5:
year1 = int(input("Enter year to show students who born in this year(eg:2000): "))
for dob in student:
if (int(dob.get_date_of_birth()) == year1):
dob.student_details()
print("-----------")
print("All students who born in ", year1)
print("-----------")
if option == 6:
snr = int(input("Enter a student number: "))
for sn in student:
if sn.student_number == snr:
firstname,lastname,date_of_birth,sex,country = map(str,input("Please Enter student details like this(cemal,göymen,2000,male,cyprus) :").split(","))
sn.set_firstname(firstname)
sn.set_lastname(lastname)
sn.set_date_of_birth(date_of_birth)
sn.set_sex(sex)
sn.set_country(country)
print("-----------")
print("Student modify success")
print("-----------")
if option == 7:
snr = int(input("Enter the student number to be deleted : "))
for sn in student:
if sn.student_number == snr:
temp = sn
student.remove(temp)
print("-----------")
print("Student deleted successfully")
print("-----------")
if option == 8:
break
I need help in option 1 and option 2 about reading and writing file. In the reading file it does not read all students from a file it reads just one student and ıf there is more than one student in the file it gives an error. In the writing to file part, the problem is I cannot write the student array to file it just write the last element from the student array but I need all elements from my student array.
Code can be improved as follows.
import random
class Student:
def __init__(self,firstname,lastname,date_of_birth,sex,country,student_number = None):
# reuse student number when we read from file (i.e. if specified)
# set new one if we don't have one
self.student_number = student_number or random.randint(1,18330751) # or causes use of rand value
# if student_number = None
self._firstname = firstname
self._lastname = lastname
self._date_of_birth = date_of_birth
self._sex = sex
self._country = country
def student_details(self):
return (f"Student number : {self.get_student_number()}\n"
f"----------- First Name : {self.get_firstname()}\n"
f"----------- Last Name : {self.get_lastname()}\n"
f"----------- Date Of Birth : {self.get_date_of_birth()}\n"
f"----------- Gender : {self.get_sex()}\n"
f"----------- Country of birth : {self.get_country()}")
def get_firstname(self):
return self._firstname
def set_firstname(self,firstname):
self._firstname = firstname
def get_lastname(self):
return self._lastname
def set_lastname(self,lastname):
self._lastname = lastname
def get_date_of_birth(self):
return self._date_of_birth
def set_date_of_birth(self,date_of_birth):
self._date_of_birth = date_of_birth
def get_sex(self):
return self._sex
def set_sex(self,sex):
self._sex = sex
def get_country(self):
return self._country
def set_country(self,country):
self._country = country
def get_student_number(self):
return self.student_number
def __str__(self):
' For serializing attributes to string --useful for writing to file '
return (f"{self.get_student_number()},"
f"{self.get_firstname()},"
f"{self.get_lastname()},"
f"{self.get_date_of_birth()},"
f"{self.get_sex()},"
f"{self.get_country()}")
def get_student_info():
' Use helper function to ensure student entry has correct number of fields '
while True:
while True:
entry = input('''Please Enter student details comma delimited like this (firstname,lastname,date of birth,gender,country)
Example Emal,Göymen,4/15/2000,Male,Cyprus : ''')
fields = entry.split(',')
if len(fields) == 5:
# Correct number of fields
return fields
else:
print(f'Entry {entry} incorrecst format')
print('Shoulbe be five comma delimitede fields i.e. firstname,lastname,date of birth,gender,country')
students = []
while True:
print('''
1. Write the contents of the student array to a file
-----------
2. Read student data from a file and populate the student array.
-----------
3. Add a new student
-----------
4. Display all students information
-----------
5. Information for students born in a particular year
-----------
6. Modify student record (you need to know student number)
-----------
7. Delete a student (you need to know student number)
-----------
8. Exit program
-----------
Enter option''')
option = int(input("Please write your option: "))
print("-----------")
if option == 1:
with open("cmse318.txt", "w") as f:
for st in students:
f.write(str(st) + '\n')
print("-----------\nSuccessfully wrote to a file!!\n-----------")
if option == 2:
with open("cmse318.txt","r") as f:
students = [] # Start new student array
for ln in f:
student_number,firstname,lastname,date_of_birth,sex,country = ln.rstrip().split(",") # rstrip remove '\n' at end of line
student_number = int(student_number)
s = Student(firstname,lastname,date_of_birth,sex,country,student_number)
students.append(s)
print(str(s))
if option == 3:
firstname,lastname,date_of_birth,sex,country = get_student_info()
s = Student(firstname,lastname,date_of_birth,sex,country)
students.append(s)
print('''-----------
Student created successfully!!
-----------
-----------''')
if option == 4 :
print('''-----------
For now these are the students
-----------
-----------''')
for st in students:
print(st.student_details())
if option == 5:
birth_year = input("Enter year to show students who born in this year(eg:2000): ")
print("-----------"
f"All students who born in {birth_year}"
"-----------")
for st in students:
if birth_year in st.get_date_of_birth(): # e.g. birth_year = 2000, date_of_birth = "May 5, 2000" we get a match
print(st.student_details())
if option == 6:
snr = int(input("Enter a student number: "))
for sn in students:
if sn.student_number == snr:
firstname,lastname,date_of_birth,sex,country = get_student_info()
sn.set_firstname(firstname)
sn.set_lastname(lastname)
sn.set_date_of_birth(date_of_birth)
sn.set_sex(sex)
sn.set_country(country)
print("-----------\nStudent modify success\n-----------")
break
else:
print(f"Student number {snr} not found!!!")
if option == 7:
snr = int(input("Enter the student number to be deleted : "))
# Normally bad practice to delete elements in list while iterating over it,
# but in this case we are only deleting a single element so okay
for sn in students:
if sn.student_number == snr:
students.remove(sn)
print(f"-----------\nStudent {snr} deleted successfully")
break
else:
print("Student {snr} not found")
if option == 8:
print('Exiting')
break

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()

Python: TypeError: list indices must be integers or slices, not list

Ok I have completely changed my code now so that the customers lists are inside another list. Now I am trying to refer to the individual lists for each customer with a for loop. But when I am trying to access individual values in the customer lists I am getting a TypeError: list indicies must be integers or slices, not list. Here is the code:
customers = [ ]
customers.append(["Bilbo","Baggins","Dodge Dart", "120876","March 20 2017"])
customers.append(["Samwise"," Gamgee","Ford Tarus","190645","January 10 2017"])
customers.append(["Fredegar","Bolger","Nissan Altima", "80076","April 17 2017"])
customers.append(["Grima"," Wormtounge","Pontiac G6", "134657", "November 24 2016"])
customers.append(["Peregrin"," Took","Ford Focus", "143567", "February 7 2017"])
customers.append(["Meriadoc","Brandybuck","Ford Focus", "143567", "February 19 2017"])
print("At Holden's Oil Change we use our custom built Python program to keep \
track of customer records \
and to display our company logo!!")
time.sleep(7)
print("Select and option from the menu!")
QUIT = '4'
COMMANDS = ('1','2','3','4')
MENU = """1 Current Customers
2 New Customers
3 Company Logo
4 Quit"""
def main():
while True:
print(MENU)
command = realCommand()
commandChoice(command)
if command == QUIT:
print("Program Ended")
break
def realCommand():
while True:
command = input("Select an option: ")
if not command in COMMANDS:
print("That is not an option!")
else:
return command
def commandChoice(command):
if command == '1':
oldCust()
elif command == '2':
newCust()
elif command == '3':
Turt()
def oldCust():
print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
for i in customers:
print("%8s%18s%22s%24s%32s" % (customers[i][0],customers[i][1],customers[i][2],customers[i][3],customers[i][4]))
the function oldCust() is where the error comes up when the for loop runs it is giving the type error. I've tried it several different ways but each ways sends back the same error.
Here is the whole error that gets returned:
Traceback (most recent call last):
File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 264, in <module>
main()
File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 49, in main
commandChoice(command)
File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 66, in commandChoice
oldCust()
File "C:\Users\hdaug\Documents\Holden's Personal\Spring 2016-2017\CSCI 1121\HoldensOilChange.py", line 79, in oldCust
print("%8s%18s%22s%24s%32s" % (customers[i][0],customers[i][1],customers[i][2],customers[i][3],customers[i][4]))
TypeError: list indices must be integers or slices, not list
First of all use list to store customer variables. Then you can easily add new customer in the list.
Here is the complete solution of your problem:
"""
Program that is used to store service
records for prior customers or prompt
user for customer information for new customers.
The program also uses Turtle Graphics to display
the company logo.
"""
#Import time module for delays in program
import time
#Define current customers
customer_list = []
customer_list.append(["Bilbo","Baggins","Dodge Dart", "120876","March 20 2017"])
customer_list.append(["Samwise"," Gamgee","Ford Tarus","190645","January 10 2017"])
customer_list.append(["Fredegar","Bolger","Nissan Altima", "80076","April 17 2017"])
customer_list.append(["Grima"," Wormtounge","Pontiac G6", "134657", "November 24 2016"])
customer_list.append(["Peregrin"," Took","Ford Focus", "143567", "February 7 2017"])
customer_list.append(["Meriadoc","Brandybuck","Ford Focus", "143567", "February 19 2017"])
#Announce the company and what our program does
print("At Holden's Oil Change we use our custom built Python program to keep \
track of customer records \
and to display our company logo!!")
time.sleep(7)
#Tell the user what to do
print("Select and option from the menu!")
#Make the menu and menu options for the user
QUIT = '4'
COMMANDS = ('1','2','3','4')
MENU = """1 Current Customers
2 New Customers
3 Company Logo
4 Quit"""
#Define how the menu works if quit option selected
def main():
while True:
print(MENU)
command = realCommand()
commandChoice(command)
if command == QUIT:
print("Program Ended")
break
#Define what happens if a invalid command is entered or a correct command is entered
def realCommand():
while True:
command = input("Select an option: ")
if not command in COMMANDS:
print("That is not an option!")
else:
return command
#Command selection and running
def commandChoice(command):
if command == '1':
oldCust()
elif command == '2':
newCust()
elif command == '3':
Turt()
#Runs old customer selection
def oldCust():
#Print list of customers for the user to select from.
print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
for customer in customer_list:
for value in customer:
print(value,end="\t")
print("")
#Request response from user and define what happens depending on the input.
response = input("Ener a customers last name from the list: ")
customer_search_result = 0
for customer in customer_list:
if response.lower() == customer[1].lower():
user_milage = input("Enter current vehicle mileage: ")
user_date = input("Enter todays date (Month Day Year Format): ")
print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
print("%9s%13s%19s%25.9s%34s" % (customer[0], customer[1], customer[2], customer[3], customer[4]))
print("Have a great day!")
customer_search_result=1
if customer_search_result==0:
print("That is not a current customer!")
time.sleep(2)
#Request user input wheter they want to input new customer info or try another customer name.
nonCustResponse = input("Choose 1 to re-enter customer name or 2 to enter new customer info: ")
#if statement that decides what to do with the user input
if nonCustResponse == "1":
oldCust()
elif nonCustResponse == '2':
#Send the user to the newCust function if they enter a non-current customer
newCust()
#If the customer enters an invalid option the program restarts
else:
print("That is not an option. Program restarting")
time.sleep(3)
#Prompts user for information for the new customer
def newCust():
#Make an empty list for the new customer to be assigned to
new_customer = [" "," "," "," "," "]
#Request user input for the new customer information
new_customer[0] = input("Enter the customers firsts name: ")
new_customer[1] = input("Enter the customers last name: ")
new_customer[2] = input("Enter the customers vehilce (Make Model): ")
new_customer[3] = input("Enter the vehicle mileage: ")
new_customer[4] = input("Enter today's date (Month Day Year): ")
print("%6s%12s%20s%24s%22s" % ("First Name", "Last Name", "Car Make & Model", "Mileage Last Service", "Date Last Oil Change"))
print("%8s%13s%22s%25s%34s" % (new_customer[0], new_customer[1], new_customer[2], new_customer[3], new_customer[4]))
customer_list.append(new_customer)
if __name__=='__main__':
main()
I have updated some part of your original code to make it run able. This code can be improvised.
You can allow some escape code when you have finished your input, i.e. just empty string:
customers = []
new_customer = input('> ')
while new_customer:
customers.append(new_customer)
new_customer = input('> ')
So when the user has hit enter without writing anything, the input is done. If you want to change that 'exit code' to something more sophisticated, use this:
customers = []
exit_code = 'stop'
new_customer = input('> ')
while new_customer != exit_code:
customers.append(new_customer)
new_customer = input('> ')
To save an input to multiple vars, do something like this:
tmp = raw_input(">>> ")
var1 = tmp
var2 = tmp
var3 = tmp
To use an input multiple times, use a function:
def function(num):
i = 0
while i < num:
tmp = raw_input(">>> ")
function(3)
var1 = tmp
var2 = tmp
var3 = tmp

Categories

Resources