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.
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()
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 trying to write a quiz program that saves and reads from text files, storing the users details in a unique text file for each user. Each user file is saved in the format:
name, age, (line 1)
username (line 2)
password (line 3)
I currently am getting the error 'IndexError: list index out of range' whilst attempting to read a two lines from a file so the program can decide whether the user has entered the correct login details. I understand that the error is due to the program not seeing line three but I cannot understand why.
import sys
def signUp ():
name=input("Please enter your first name and last name. \n- ")
name = name.lower()
username=name[0:3]
age= input("Please input your age. \n- ")
username = username + age
password = input("Please input a password. \n- ")
print ("Your username is "+username+" and your password is " +password)
userfile = open(name+".txt", "r")
userfile.write(name+", "+age+"\n")
userfile.write(username+"\n")
userfile.write(password+"\n")
userfile.close()
return name, age, username, password
def login():
logname = input("Please enter your first name and last name. \n- ")
logname = logname.lower()
loginFile = open (logname+".txt", "r")
inputuname = input ("Enter your username. \n- ")
inputpword = input("Enter your password. \n- ")
username = loginFile.readlines(1)
password = loginFile.readlines(2)
print (username)
print (password)
loginFile.close()
if inputuname == username[1].strip("\n") and inputpword ==
password[2].strip("\n"):
print("success")
quiz()
else:
print("invalid")
def main():
valid = False
print ("1. Login")
print ("2. Create Account")
print ("3. Exit Program")
while valid != True:
choice =input("Enter an Option: ")
if choice == "1":
login()
elif choice == ("2"):
user = signUp()
elif choice== ("3"):
valid = True
else:
print("not a valid option")
def quiz():
score = 0
topic = input ("Please choose the topic for the quiz. The topics available
are: \n- Computer Science \n- History")
difficulty = input("Please choose the diffilculty. The difficulties
available are: \n- Easy \n- Medium \n- Hard")
questions = open(topic+"questions.txt", "r")
for i in range(0,4):
questions = open(topic+" "+difficulty+".txt", "r")
question = questions.readline(i)
print(question)
answers = open (topic+" "+difficulty+" answers.txt", "r")
answer = answers.readline(i)
print(answer)
userAns = input()
questions.close
answers.close
if userAns == answer:
score = score + 1
return score
main()
You should use with open(....) as name: for file operations.
When writing to a file you should use a for append / r+ for read+write, or w to recreate it - not 'r' that is for reading only.
As for your login():
def login():
logname = input("Please enter your first name and last name. \n- ")
logname = logname.lower()
inputuname = input("Enter your username. \n- ")
inputpword = input("Enter your password. \n- ")
with open(logname + ".txt", "r") as loginFile:
loginfile.readline() # skip name + age line
username = loginFile.readline() # read a single line
password = loginFile.readline() # read a single line
print(username)
print(password)
if inputuname == username.strip("\n") and inputpword == password.strip("\n"):
print("success")
quiz()
else:
print("invalid")
File-Doku: reading-and-writing-files
If the file does not exist your code will crash, see How do I check whether a file exists using Python?
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.