So I am new to SQL lite and Python in general...
I'm creating a search function that should return an else statement when the input receives an empty query. Not understanding while I fufill the else statement the whole database is returned instead of the print statement I called.
def search_task():
askjeeves = input("Enter Search Term: ")
cur = con.cursor()
if askjeeves != "" or askjeeves != " ":
cur.execute("SELECT * FROM books WHERE author LIKE'%'||?||'%' ", (askjeeves,))
finalsearch = cur.fetchall()
print(finalsearch)
search_task()
else:
print("No value inputted, program ended. ")
Also tried:
def search_task():
askjeeves = input("Enter Search Term: ")
cur = con.cursor()
if askjeeves != None:
cur.execute("SELECT * FROM books WHERE author LIKE'%'||?||'%' ", (askjeeves,))
finalsearch = cur.fetchall()
print(finalsearch)
search_task()
else:
print("No search input")
input("Do you want to search again? Input 1 for Yes, 0 for No:")
if input == 1:
search_task()
else:
print("Search Ended")
You have a circular dependency here. You are calling the function again in the if.
When it is empty, you have a problem with your checks.
Empty strings in python are False. So
def search_task():
askjeeves = input("Enter Search Term: ")
cur = con.cursor()
if askjeeves and askjeeves != " ":
cur.execute("SELECT * FROM books WHERE author LIKE'%'||?||'%' ", (askjeeves,))
finalsearch = cur.fetchall()
print(finalsearch)
search_task()
else:
print("No search input")
input("Do you want to search again? Input 1 for Yes, 0 for No:")
if input == 1:
search_task()
else:
print("Search Ended")
Related
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 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()
Can anyone please tell me why the "While loop" in the following code is not working as I am expecting to work? I want this code to ask for two inputs and then print.
def make_album(artist_name, album_title):
''' This function uses return option'''
album_details = artist_name + '' + album_title
return album_details
while True:
print("\n enter artist_name")
print("\n enter q to quit")
artist_name = input("artist_name: ")
if artist_name == 'q':
break
album_title = input("album_title: ")
if album_title == 'q':
break
album_details_Raj = make_album(artist_name, album_title)
print(album_details_Raj)
A python function works as
def add(x, y):
return x+y
The function uses whatever is passed into them.
You also have the function call itself. This is only useful if you are trying to have recursion, but it does not seem like you need it.
Try having the code look like this:
def make_album(artist_name, album_title):
''' This function uses return option'''
album_details = artist_name + '' + album_title
return album_details
while True:
print("\nenter artist_name")
print("\nenter q to quit")
artist_name = input("artist_name: ")
if artist_name == 'q':
break
album_title = input("album_title: ")
if album_title == 'q':
break
album_details_Raj = make_album(artist_name, album_title)
print(album_details_Raj)
Hope that helps.
You have a return statement before the while loop. Using return in a function will cause the function to not continue further.
I think you meant to not indent the loop. It does not need to be in the function. Otherwise, the return statement prevents the loop from starting
def make_album(artist_name, album_title):
''' This function uses return option'''
album_details = artist_name + ' ' + album_title
return album_details
while True:
print("\n enter artist name and album title")
print("\n enter q to quit")
artist_name = input("artist_name: ")
album_title = input("album_title: ")
if artist_name == 'q' or album_title == 'q':
break
album_details = make_album(artist_name, album_title)
print(album_details)
Working on Python 3.4.3
Let's say I have created three fuctions:
def choosing(mylist=[]):
print("We will have to make a list of choices")
appending(mylist)
done = False
while(done == "False"):
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(mylist)))
done = True
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
appending(mylist)
done = False
elif(action == "Delete"):
removing(mylist)
done = False
def appending(mylist1 = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
mylist1.append(c)
print("You have inserted {} choices".format(len(mylist1)))
print("Please verify them below: ")
for x in range(0, len(mylist1)):
print(mylist1[x])
def removing(mylist2 = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
mylist2.remove(r)
print("{} successfully removed!".format(r))
Now problem is I can't just call choices() in append or remove function as choices() function will call append again and again infinitely.
So how do I get back in choices after appending or removing data in list?
As suggested by tobias_k, you should add the contents of choices() into a while loop.
I also found
some other problems:
False does not equal "False", so your while loop never runs.
You use terms like mylist, mylist1, and mylist2 - it's better to rename these to choosing_list, appending_list, and removing_list, so it's clearer.
You also shouldn't use False to define a while loop - instead, make a variable, then set it to True. When you have to stop, set it to False.
Here is the code with those problems fixed:
def appending(appending_list = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
appending_list.append(c)
print("You have inserted {} choices".format(len(appending_list)))
print("Please verify them below: ")
for x in range(0, len(appending_list)):
print(appending_list[x])
return appending_list
def removing(removing_list = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
removing_list.remove(r)
print("{} successfully removed!".format(r))
return removing_list
print("We will have to make a list of choices")
choosing_list = appending()
list_incomplete = True
while list_incomplete:
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(choosing_list)))
list_incomplete = False
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
choosing_list = appending(choosing_list)
elif(action == "Delete"):
choosing_list = removing(choosing_list)
Let me know if there's any problems with this code.