i'm doing a small script that received name from user and then search for name, if found prints his/her name otherwise print "not found".
def std_record():
print("1. Enter data.")
print("2. Search student")
user_input = int(input("Enter Choice: "))
if user_input == 1:
name = input("Whats your name: ")
elif user_input == 2:
search = input("Enter keyword: ")
if search in name:
print("data found: " + name +".")
else:
print("not found")
while True:
std_record()
UnboundLocalError: local variable 'name' referenced before assignment
you need to initialize strings before using them, either as an empty string or none
so name = ""
or name = None
Try initializing the name variable:
name = None
def std_record():
print("1. Enter data.")
print("2. Search student")
user_input = int(input("Enter Choice: "))
if user_input == 1:
name = input("Whats your name: ")
elif user_input == 2:
search = input("Enter keyword: ")
if name:
print("data found: " + name +".")
else:
print("not found")
while True:
std_record()
Related
As you can see i am trying to check if the entered input by the user is string or not. If not, I have to display invalid name.
student_name = input("Enter the name of the student")
x = type(student_name)
if x!=str:
print('invalid name')
else:
print(student_name)
student_name = input("Enter the name of the student")
try:
int(student_name)
print('invalid name')
except ValueError:
print(student_name)
or
import re
student_name = input("Enter the name of the student")
num_format = re.compile(r'^\-?[1-9][0-9]*$')
for c in student_name:
it_is = re.match(num_format,c)
if it_is: it_is = True
if it_is:
print('invalid name')
else:
print(student_name)
the difference is on the first one you can pass through numbers with characters (more like username) but second one you should enter only characters.
The phonebook cannot store more than one person with the same last name. For example if i have an entry with the last name x and i try to create a new entry with a last name x,it will replace the previous x with the info of the last x input. This is the code.blablablablablabla(i cant say more but it doesnt let me post)
# Used to store the entries in the telephone book
entries = []
new_entries = {}
# Create flag to decide when the program ix exited
exit_program = False
while exit_program == False:
print( "Welcome to the EG-244 Telephone Book" )
print( "------------------------------------\n" )
print( "Please select from one of the following options:" )
print( "\t1. Add a new entry" )
print( "\t2. List entries" )
print( "\t3. Search for an entry" )
print( "\t4. Delete an entry" )
print( "\t5. Add a personal note" )
print( "\t6. Remove a personal note" )
print( "\t7. Quit" )
menu_input = input()
menu_num = int(menu_input)
if menu_num == 1:
print("\nCan i have your Last name, First name,Age and phone number please")
last_name=input("Last name:")
name=input("Name:")
age=input("Age:")
phone=input("Phone number:")
new_entries[last_name] = {'Last Name':last_name, 'First Name':name, 'Age':age, 'Telephone':phone,'Personal Notes':{'1.':'', '2.':''}}
entries.append(new_entries.copy())
entries=sorted(new_entries.keys(), key=lambda x:x.lower())
continue
elif menu_num == 2:
if len(new_entries) == 0:
print("No entries have been submitted yet")
continue
else:
for i in entries:
values=new_entries[i]
print("Last Name:" + i)
print("First Name:"+values['First Name'])
print("Age:"+values['Age'])
print("Phone Number:"+values['Telephone'])
print('Personal Note 1.:'+values['Personal Notes']['1.'])
print('Personal Note 2.:'+values['Personal Notes']['2.'])
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Currently there are" + str(len(entries)) + "entries")
continue
elif menu_num == 3:
print("\nInsert the last name:")
last_name=input()
if last_name in new_entries:
print (last_name, new_entries[last_name])
continue
else:
print("\nThe person is not in the phone book")
continue
elif menu_num == 4:
print("\nInsert the Last name of the entry to be deleted:")
last_name=input()
if last_name in new_entries:
del new_entries[last_name]
print("Entry has been deleted")
continue
else:
print("The entry does not exist")
continue
elif menu_num ==5:
print("Can I have your last and first name please:")
last_name=input("Last name:")
name=input("First name:")
note=input("Personal Note:")
note_1=input("Another personal Note:")
name in [x for v in new_entries.values() for x in v]
if last_name in new_entries:
new_entries[last_name]['Personal Notes']['1.']=note
new_entries[last_name]['Personal Notes']['2.']=note_1
print (last_name, new_entries[last_name])
continue
else:
print("This entry does not exist")
continue
if menu_num == 6:
print("Can I have your last and first name please:")
last_name=input("Last name:")
name=input("First name:")
delete=input("Delete note 1 or 2?")
delete=int(delete)
name in [x for v in new_entries.values() for x in v]
if last_name in new_entries:
for notes in new_entries.values():
if delete == 1:
new_entries[last_name]['Personal Notes']['1.']=''
print("1st Note deleted")
elif delete == 2:
new_entries[last_name]['Personal Notes']['2.']=''
print("2nd Note deleted")
continue
else:
print("This entry does not exist")
elif menu_num == 7:
exit_program = True
else:
print( "Error: You entered an invalid choice. Please try again." )
print( "Thank you for using the EG-244 Telephone Book" )
I think that
new_entries[last_name] = {'Last Name':last_name, 'First Name':name, 'Age':age, 'Telephone':phone,'Personal Notes':{'1.':'', '2.':''}}
should be a list containing a dictionary rather than just a dictionary.
new_entries[last_name] = [{'Last Name':last_name, 'First Name':name, 'Age':age, 'Telephone':phone,'Personal Notes':{'1.':'', '2.':''}}]
That way you could append another item to that list stored under the same last_name key.
You'll then have to update the rest of your code to handle this new data structure.
I have been trying to resolve my script with no results. I can't get
the load data to display. It is saving in members.txt and can read
it manually if opened. If someone can give any other advice on the
script as a whole it would be greatly appreciated.
I have reasearced greatly changed script around still have no luck.
import os if 'file' in vars():
wk_dir = os.path.dirname(os.path.realpath('file')) else:
print('We are running the script interactively')
class playerCLass(object):
name = ""
phone = ""
number = 0
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
def setname(self, name):
self.name = name
def setphone(self, phone):
self.phone = phone
def setnumber(self, number):
self.number = number
def getname(self):
return self.name
def getphone(self):
return self.phone
def getnumber(self):
return self.number
def display_data(self):
print("")
print("Member information: ")
print("Name:", self.name)
print("Phone number:", self.phone)
print("Jersey number:", self.number)
def displayMenu():
print("===========Menu Selections===========")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Data.")
print("6. Load Data.")
print("9. Exit Program.")
print("")
return int(input("<<Selection>> "))
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
else:
x = 1
while x < len(players):
print(x)
x = x + 1
def addPlayer(players):
newName = input("Type in member's name to be added to the roster:")
newPhone = input("Type in the member's phone number:")
newNumber = int(input("Type in the member's jersey number:"))
players[newName] = playerCLass(newName, newPhone, newNumber)
return players
def removePlayer(players):
name = input("Enter member's name to be removed:")
if name in players:
del players[name]
else:
print("member's name not found in list: ")
return players
def editPlayer(players):
oldName = input("Enter the name you want to edit: ")
if oldName in players:
newName = input("Enter a new name: ")
newPhone = input("Enter new phone number: ")
newNumber = int(input("Enter new jersey number: "))
players[oldName] = playerCLass(newName, newPhone, newNumber)
else:
print("No such name in memory: ")
return players
def saveData():
filename = input("Filename to save: ")
print("Saving data...")
outFile = open(filename, "wt")
for x in players.keys():
name = players[int(x)].getname()
phone = players[int(x)].getphone()
number = str(players[x].getnumber())
outFile.write(name + "," + phone + "," + number + "\n")
print("Data saved.")
outFile.close()
def loadData():
players = {}
filename = input("Filename to load: ")
inFile = open(filename, "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, number = inLine.split(",")
players[name] = (name, phone, number)
print("Data Loaded Successfully.")
inFile.close()
return players
print("Welcome to the Team Manager")
players = {}
menuSelection = displayMenu()
print()
while menuSelection != 9:
if menuSelection == 1:
printPlayer(players)
elif menuSelection == 2:
players = addPlayer(players)
elif menuSelection == 3:
players = removePlayer(players)
elif menuSelection == 4:
players = editPlayer(players)
elif menuSelection == 5:
saveData()
elif menuSelection == 6:
loadData()
menuSelection = displayMenu()
print("Exiting Program...")
If your issue is specifically not getting printPlayer to work you can do
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
#Iterate through dictionary of player name and player object and call
#display data on each of them
else:
for name, player in players.items():
print(player.display_data())
If you then run the code and input according to the statements you wrote, you should get something like this.
Welcome to the Team Manager
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
No current members in memory.
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 2
Type in member's name to be added to the roster:Joe
Type in the member's phone number:123
Type in the member's jersey number:456
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
Member information:
Name: Joe
Phone number: 123
Jersey number: 456
None
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>>
I keep on getting this error when I run my program. In the bank_system file, an option is given to type the number 5 so it loads the run_admin_options function in the admin.py option. But everytime I run the program it comes with this error:
AttributeError: module 'admin' has no attribute 'run_admin_options'
The code from my admin.py module:
class Admin:
def __init__(self, fname, lname, address, house_number, road_name, town_city, postcode, user_name, password, full_rights):
self.fname = fname
self.lname = lname
self.address = address
self.house_number = house_number
self.road_name = road_name
self.town_city = town_city
self.postcode = postcode
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
def update_address(self, addr):
self.address = addr
def set_username(self, uname):
self.user_name = uname
def get_username(self):
return self.user_name
def get_address(self):
return self.address
# new
def get_house_number(self):
return self.house_number
# new
def update_house_number(self, house_number):
self.house_number = house_number
def get_road_name(self):
return self.road_name
def update_road_name(self, road_name):
self.road_name = road_name
# new
def get_town_city(self):
return self.town_city
def update_town_name(self, town_city):
self.town_city = town_city
# new
def get_postcode(self):
return self.postcode
def update_postcode(self, postcode):
self.postcode = postcode
def update_password(self, password):
self.password = password
def get_password(self):
return self.password
def set_full_admin_right(self, admin_right):
self.full_admin_rights = admin_right
def has_full_admin_right(self):
return self.full_admin_rights
def admin_account_menu(self):
# print the options you have
print()
print()
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Your admin options are:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("1) Update name")
print("2) Update address")
print(" ")
option = int(input("Choose your option: "))
return option
def run_admin_options(self):
loop = 1
while loop == 1:
choice = self.admin_account_menu()
if choice == 1:
fname = input("\n Enter new admin first name: ")
self.update_first_name(fname)
sname = input("\n Enter new admin last name: ")
self.update_last_name(sname)
elif choice == 2:
house_number = input("\n Enter new admin house number: ")
self.update_house_number(house_number)
road_name = input("\n Enter new admin road name: ")
self.update_road_name(road_name)
town_city = input("\n Enter new admin town or city: ")
self.update_town_name(town_city)
postcode = input("\n Enter new admin postcode: ")
self.update_postcode(postcode)
print("Admin details successfully updated")
The code from my bank_system module:
class BankSystem(object):
def __init__(self):
self.accounts_list = []
self.admins_list = []
self.load_bank_data()
def load_bank_data(self):
# create customers
account_no = 1234
customer_1 = CustomerAccount("Adam", "Smith", ["14", "Wilcot Street", "Bath", "B5 5RT"], account_no, 5000.00)
self.accounts_list.append(customer_1)
account_no += 5678
customer_2 = CustomerAccount("David", "White", ["60", "Holborn Viaduct", "London", "EC1A 2FD"], account_no,
3200.00)
self.accounts_list.append(customer_2)
account_no += 3456
customer_3 = CustomerAccount("Alice", "Churchil", ["5", "Cardigan Street", "Birmingham", "B4 7BD"], account_no,
18000.00)
self.accounts_list.append(customer_3)
account_no += 6789
customer_4 = CustomerAccount("Ali", "Abdallah", ["44", "Churchill Way West", "Basingstoke", "RG21 6YR"],
account_no, 40.00)
self.accounts_list.append(customer_4)
# create admins
admin_1 = Admin("Taran", "Basi", ["224", "Kenpas Highway", "Coventry", "CV3 6PB"], 224, "Kenpas Highway", "Coventry", "CV3 6PB", "1", "pass", True)
self.admins_list.append(admin_1)
def search_admins_by_name(self, admin_username):
# STEP A.2
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! Please try again.\n" % admin_username)
return found_admin
def search_customers_by_name(self, customer_lname):
# STEP A.3
found_customer = None
for c in self.accounts_list:
lastname = c.get_last_name()
if lastname == customer_lname:
found_customer = c
break
if found_customer == None:
print("\n The customer %s does not exist! Try again...\n" % customer_lname)
return found_customer
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: ")
msg, admin_obj = self.admin_login(username, password)
print(msg)
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 transferMoney(self, sender_lname, receiver_lname, receiver_account_no, amount):
# ToDo
pass
def admin_login(self, username, password):
# STEP A.1
found_admin = self.search_admins_by_name(username)
msg = "\n ❌ Login failed"
if found_admin != None:
if found_admin.get_password() == password:
msg = "\n ✔ Login successful"
return msg, found_admin
def admin_menu(self, admin_obj):
# print the options you have
print(" ")
print("Welcome Admin %s %s! Available 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) Update admin information")
print("6) Sign out")
print(" ")
option = int(input("Choose your option: "))
return option
def run_admin_options(self, admin_obj):
loop = 1
while loop == 1:
choice = self.admin_menu(admin_obj)
if choice == 1:
sender_lname = input("\n Please input sender surname: ")
amount = float(input("\n Please input the amount to be transferred: "))
receiver_lname = input("\n Please input receiver surname: ")
receiver_account_no = input("\n Please input receiver account number: ")
self.transferMoney(sender_lname, receiver_lname, receiver_account_no, amount)
elif choice == 2:
# STEP A.4
customer_name = input("\n Please input customer surname :\n")
customer_account = self.search_customers_by_name(customer_name)
if customer_account != None:
customer_account.run_account_options()
elif choice == 3:
# STEP A.5
customer_name = input("\n input customer surname you want to delete: ")
customer_account = self.search_customers_by_name(customer_name)
if customer_account != None:
self.accounts_list.remove(customer_account)
print("%s was successfully deleted!" % customer_name)
elif choice == 4:
# STEP A.6
self.print_all_accounts_details()
elif choice == 5:
admin.run_admin_options()
elif choice == 6:
loop = 0
print("\n You have successfully logged out")
def print_all_accounts_details(self):
# list related operation - move to main.py
i = 0
for c in self.accounts_list:
i += 1
print('\n %d. ' % i, end=' ')
c.print_details()
print("------------------------")
app = BankSystem()
app.run_main_options()
Can anyone please help me with this error, I've tried so many times to fix this myself but I'm having no luck at all and I don't understand what this error means. All this code is getting me so confused.
Thank you.
The line
admin.run_admin_options()
in BankSystem.run_admin_options should probably be
admin_obj.run_admin_options()
I am making a contact management program in Python 3.6 for my job and I am trying to add a function that will allow the user to delete an individual contact of their choosing within a list.
However, when I run the program, it does not delete the desired list item. Instead it returns this error:
Traceback (most recent call last):
File "C:/Users/cmanagerMain.py", line 10, in <module>
deleteContact()
File "C:\Users\cmanagerFunctions.py", line 23, in deleteContact
contactList.remove(item)
ValueError: list.remove(x): x not in list
I am still a bit new to Python and as a result am unable to identify where I went wrong.
I would like for someone to identify my error so I can learn from it and also suggest a solution.
Here is the code:
contactList = []
class Contact:
name = ""
number = ""
def addContact():
print()
contact = Contact()
contact.name = input("Enter contact name: ")
contact.number = input("Enter contact number: ")
contactList.append(contact)
print("Contact added.")
print()
def deleteContact():
print()
item = Contact()
item.name = input("Enter contact to be deleted: ")
item.number = input("Enter the number of contact: ")
contactList.remove(item)
print()
def getMenuChoice():
print("1. Add new contact")
print("2. Print all contacts")
print("3. Delete a contact")
print("4. Quit")
return input("Please enter your choice (1-4): ")
def printContacts():
print()
print("Printing contacts...")
for itm in contactList:
print(itm.name + "," + itm.number)
print()
while True:
choice = getMenuChoice()
if choice == "1":
addContact()
elif choice == "2":
printContacts()
elif choice == "3":
deleteContact()
elif choice == "4":
print("Goodbye")
else:
continue
To remove an element from a list you pass in the item number (zero-based), not the item itself.