The user needs to input the table number (Tables are numbered from 0 to 19). If the table is not available (reserved), inform the user that the selected table is not available. If the table is available, then ask for the name (name is a single word, no space) and mark the table as reserved. Now I need to keep two arrays (parallel arrays!), both are size 20, one of type boolean (true/false -- reserved/available) and the other one of type string (name on reservation if reserved, blank otherwise)
tableNum = []
def reserve():
global table
global name
global tableNum
avaible = False
tablenum = int(input("Enter a number: "))
if not tablenum in tableNum:
name = input("Table is avaiable, please enter your name: ")
else:
print("Table is unavaiable")
while(True):
print("1- Reserve a Table")
print("2- Clear Reservation")
print("3- Report")
print("0- Exit")
choice = int(input("Choose a option "))
if choice == 1:
reserve()
You could do it without keeping a list of all the tables. Append reservations as a key, value pair to a dictionary. You can then check if the input matches a key in the reservation dictionary. You can then use the reverse to remove a reservation.
reservationDictionary ={}
def reserve():
global reservationDictionary
tablechoice = int(input('Tables are numbered 0-19, Choose a table number'))
if tablechoice not in reservationDictionary.keys():
name = input("Table is available, enter your Name: ")
reservationDictionary[tablechoice] = name
else:
print("Table is unavailable")
Update to remove a booking:
def removeReservation():
global reservationDictionary
removetable = int(input('Choose table number to remove reservation for that table'))
if removetable not in reservationDictionary.keys():
print("This table doesn't have a reservation")
else:
del reservationDictionary[removetable]
print("Reservations for table {} has been deleted".format(removetable))
Related
When user adding details to a dictionary, I want check those details are already there or not,
When name, age, team and car have same values in another record ignore those inputs and tell the user "It's already there" otherwise "add" details to the dictionary. Also, this duplication check should happen before appending to the List.
I don't how to do this I tried but it doesn't work
driver_list = []
name = str(input("Enter player name : "))
try:
age = int(input("Enter the age : "))
except ValueError:
print("Input an integer",)
age = int(input("Enter the age : "))
team = str(input("Enter team name : "))
car = str(input("Enter name of the car : "))
try:
current_points = int(input("Enter the current points of the player : "))
except ValueError:
print("Input an integer")
current_points = int(input("Enter the current points of the player : "))
driver_details={"Name":name ,"Age": age,"Team": team ,"Car": car, "Current_points": current_points}
driver_list.append(driver_details)
# check all values in the driver_det is found in any of the
# dictionaries in the list driver_list
def checkAllInList(driver_det):
# define the keys we are interested in
Interest = ['name', 'age', 'team', 'car']
# get corresponding values from the driver_det
b = set([value for key, value in driver_det.items() if key in Interest])
# iterate over all driver_list dictionaries
for d in driver_list:
# get all values corresponding to the interest keys for the d driver
a = set([value for key, value in d.items() if key in Interest])
# if both have the same values, return true
if a == b:
return True; # if found equal, return true
return False; #otherwise, return false if non of the dictionaries have these details
# you can use it like that
if checkAllInList(driver_details): # check a duplicate is found
print("this is a duplicate value")
else: # no duplicate found
driver_list.append(driver_details)
I am trying to make a book selling system and I am trying to take the book's name from input and find the quantity of the book.But system takes the whole row instead of taking a single column.How can I solve this ?
import sqlite3
print("------------------------------------------")
print("Welcome to the bookshop management system.")
print("------------------------------------------")
print("[1] Add Book")
print("[2] Search for a book")
print("[3] Sell a book")
print("[4] Change stocks")
connect=sqlite3.connect("librarydatabase.db")
cursor=connect.cursor()
Inserter="INSERT INTO books VALUES('booknamevalue','writervalue','DateOfReleasevalue','Quantityvalue','Pagevalue')"
operation=input("Please enter an operation:")
if operation=="1":
bookname=input("Please enter the book's name")
writername=input("Please enter the writer's name:")
DateOfReleaseinput=input("Please enter the Date of release:")
Quantityvalue=input("Please enter the Quantity of the book:")
Pagevalue=input("Please enter the Page count of the book:")
Inserter1=Inserter.replace("booknamevalue",bookname)
Inserter2=Inserter1.replace("writervalue",writername)
Inserter3=Inserter2.replace("DateOfReleasevalue",DateOfReleaseinput)
Inserter4=Inserter3.replace("Quantityvalue",Quantityvalue)
Inserter5=Inserter4.replace("Pagevalue",Pagevalue)
cursor.execute(Inserter5)
connect.commit()
Booksellersearcher="SELECT Quantity FROM Books WHERE Bookname='Booknamevalue'"
#Will be made correctly
if operation=="3":
Bookname2=input("Please enter the name of the book:")
Booksellersearcher2=Booksellersearcher.replace("Booknamevalue",Bookname2)
cursor.execute(Booksellersearcher2)
BookQuantity=cursor.fetchone()
if BookQuantity==0:
print("No Stock On this Book")
operation=input("Please enter an operation:")
else:
print("There are"+" "+str(BookQuantity)+"books"+" "+"of"+" "+Bookname2)
operationinput=input("Do you wanna sell ?(Y/N)")
if operationinput=="Y":
SellingQuantityInput=int(input("How many Books do you wanna sell ?"))
NewQuantity=BookQuantity-SellingQuantityInput
print(NewQuantity)
else:
operation=input("Please enter an operation:")
Booksearcher="SELECT * FROM Books WHERE Bookname='Booknamevalue'"
if operation=="2":
Booknameinput2=input("Please enter the name of the book:")
Booksearcher2=Booksearcher.replace("Booknamevalue",Booknameinput2)
cursor.execute(Booksearcher2)
Bookvalues=cursor.fetchall()
print(Bookvalues)
BookQuantitychanger="UPDATE Books SET Quantity='Quantityvalue' WHERE Bookname='Booknamevalue'"
if operation=="4":
Booknameinput3=input("Please enter the name of the book:")
BookQuantityinput=int(input("Please enter the quantity of the book:"))
BookQuantitychanger2=BookQuantitychanger.replace("Quantityvalue",str(BookQuantityinput))
BookNamereplacer=BookQuantitychanger2.replace("Booknamevalue",Booknameinput3)
cursor.execute(BookNamereplacer)
connect.commit()
print("Book quantity changed successfully!")
I will start with your question, SELECT on a table will return rows, which are put in tuples, even you select a single columns it returns the rows containing just this column, but those are still rows, and so tuples.
But now please read the following.
Using string replace or any other other string templating for any SQL statement is leaving it wide open for SQL injection, what if the user inputs ' ; DROP TABLE books ; -- in the Booksearcher statement ?
You end up with
SELECT * FROM Books WHERE Bookname='' ; DROP TABLE books ; --'
which will destroy you books table.
Please go through the SQLite3 tutorial to see SQL parameterisation.
Your SQL statement is SELECT * which is why you get all columns.
Change your SQL statement to the one below:
Booksearcher="SELECT Quantity FROM Books WHERE Bookname='Booknamevalue'"
But your code is a bit unreadable.
You are using a lot of replacements and for each you're using a new variable. Use f-strings instead.
Your variable names are capitalized. In python that's used to define classes/objects.
Your if statements should be if/elif instead.
There is no main loop, so your code only executes once.
You have what I would call main menu prints inside your submenus. Instead you should go back to the main menu.
Little Bobby Tables
I did a quick rewrite of your code because I'm a bit bored. See below
import sqlite3
connect = sqlite3.connect("librarydatabase.db")
cursor = connect.cursor()
while True:
print("------------------------------------------")
print("Welcome to the bookshop management system.")
print("------------------------------------------")
print("[1] Add Book")
print("[2] Search for a book")
print("[3] Sell a book")
print("[4] Change stocks")
print("[0] Exit")
operation = input("Please enter an operation:\n")
if operation == "1":
bookname = input("Please enter the book's name:\n")
writername = input("Please enter the writer's name:\n")
dateofrelease = input("Please enter the Date of release:\n")
quantity = input("Please enter the Quantity of the book:\n")
pagecount = input("Please enter the Page count of the book:\n")
cursor.execute(f"INSERT INTO books VALUES('{bookname}','{writername}','{dateofrelease}','{quantity}','{pagecount}')")
connect.commit()
elif operation == "2":
bookname = input("Please enter the name of the book:\n")
cursor.execute(f"SELECT Quantity FROM Books WHERE Bookname='{bookname}'")
books = cursor.fetchall()
print(books)
elif operation == "3":
bookname = input("Please enter the name of the book:\n")
cursor.execute(f"SELECT Quantity FROM Books WHERE Bookname='{bookname}'")
bookquantity = cursor.fetchone()
if bookquantity == 0:
print("No Stock On this Book")
# go to the start of the while loop
continue
else:
print(f"There are {bookquantity} books of {bookname}")
operationinput = input("Do you wanna sell ?(Y/N):\n")
if operationinput.upper() == "Y":
sellingquantity = int(input("How many Books do you wanna sell ?\n"))
newquantity = bookquantity - sellingquantity
print(newquantity)
else:
continue
elif operation == "4":
bookname = input("Please enter the name of the book:\n")
bookquantity = int(input("Please enter the quantity of the book:\n"))
cursor.execute(f"UPDATE Books SET Quantity='{bookquantity}' WHERE Bookname='{bookname}'")
connect.commit()
print("Book quantity changed successfully!")
elif operation == "0":
# exit while loop
break
else:
print("Operation not recognized.")
I am currently creating a main menu that acts like a bank account.
def main_menu():
print("Main Menu")
print("0 - Quit")
print("1 - Open Account")
print("2 - Check Balance")
print("3 - Close Account")
loop = True
while loop:
main_menu()
choice = input("Enter your choice: ")
choice = int(choice)
if choice == 0:
exit(loop)
elif choice == 1:
name_on_account = input("Name on account: ")
balance = float(input("Enter Initial Balance: "))
print("---Account successfully created---")
print("Account number:", account_no())
print("Name on account:", name_on_account)
print("Balance:", balance)
print("Account opened on:", now)
cur.execute("""
INSERT INTO account(name_on_account, balance) VALUES
("%s", "%s");""", (name_on_account, balance))
connection.commit()
elif choice == 2:
print("Checking account balance")
account_number = input("Enter account number: ")
print("---Checking account balance---")
print("Account number:", account_number)
cur.execute("""SELECT * from account;
""")
account_no1 = cur.fetchone()
for i in account_no1[0]:
if account_number == i:
cur.execute("""select name_on_account from account where account_no = "%s";
""", (account_number,))
name1 = cur.fetchone()
print(name1)
name2 = ''.join(map(str,name1))
name3 = int(name2)
print("Name on account:", name3)
cur.execute("""select balance from account where account_no = "%s";
""", account_number)
balance1 = cur.fetchone()
balance2 = ''.join(map(str,balance1))
balance3 = int(balance2)
print("Balance:", balance3)
cur.expecute("""select account_open_date from account where account no = "%s";
""", account_number)
date1 = cur.fetchone()
date2 = ''.join(map(str, date1))
date3 = int(date2)
print("Account opened on:", date3)
connection.commit()
else:
print("Error: Invalid account number")
I'm not worried about option 3 as of right now, but I am having trouble with option 2.
When a person pick option 1, they will input their name and the amount of money deposited in their bank account.
This information will be stored in the mysql table account(account_no, name_on_account, balance, account_open_date, account_status).
This means that account_no is auto-incremented, account_open_date is default as curdate(), and account_status is default to be "open").
In option 2 however, when a person input their account number; it should return back all of their information how it is displayed in the option 1.
What I am having trouble with is, how do you efficiently iterate over the person's information using fetchone() and be able to get the specific column information with (account_no = account_number) (if you do have a better suggestion on a better way to implement this, please comment below)
This is the error message that I get:
Traceback (most recent call last):
File "(deleted for privacy purposes)"
for i in account_no1[0]:
TypeError: 'int' object is not iterable
Thank you for the help!
pymysql (and most other python mysql clients) is returning a tuple when you invoke fetchone(), and each entry in the tuple matches up to the datatypes defined in the table that you're querying. So let's look at your code:
elif choice == 2:
print("Checking account balance")
account_number = input("Enter account number: ")
print("---Checking account balance---")
print("Account number:", account_number)
cur.execute("""SELECT * from account""")
account_no1 = cur.fetchone()
for i in account_no1[0]:
Here you're querying all columns and all rows from the account table, reading the first row, and then iterating over whatever is in the first column of that row. But that's probably just an id column, which is probably why you're getting the error that you're getting: integers are not iterable. That'd be like writing for i in 10, Python doesn't understand what that means
If you want to iterate over all of the returned rows, you can do that like this:
cur.execute("""SELECT * from account;
""")
for row i in cur.fetchall():
# Each iteration "row" is a tuple of values corresponding to the table's columns
That's kind of silly though. You'd returning all of the rows from the database and then iterating over them and looking for a specific account number. Why not just do that as part of your query?
nrows = cur.execute("SELECT * from account where account_no=%s", (account_number,))
if nrows == 0:
# Account number not found, do something
else:
row = curs.fetchone()
# row now contains all of the values from the discovered
Note that you don't need to put quotation marks around %s placeholders, and you don't need semicolons. The client does all of this conversion for you.
Also note that you should not select * from tables. What if the table definition changes to include more columns? Just select the handful of columns that you actually need, then if more columns are added to the table later your code won't need to be changed at all and you won't be requesting more data than you need. So more like:
nrows = cur.execute("SELECT name, balance, date_opened from account where account_no=%s", (account_number,))
if nrows > 0:
name, balance, date_opened = curs.fetchone()
First of all, I would like to apologize to anyone if there was a similar topic, but I've been looking for a solution on this for hours now and couldn't find anything. Perhaps I don't know exactly how to ask the question. I am quite new to python and programming in general.
So my issue is the following. I am currently working on my first little "project" that is not just following a guide or an example program. What I am trying to do is create a list string from user input bit the list must have an integer value this is what I am trying:
s1 = []
product = []
menu = 1
while menu > 0:
print("1. Add employee.")
print("2. Add a product.")
print("3. Add a sale")
print("4. quit")
action = int(input("what would you like to do? Select a number: "))
if action == 1:
name = input("Employee name: ")
s1.append(name)
elif action == 2:
temp = input("Select the name of the product: ")
value = int(input("What is the price of the product: "))
int_temp = temp
product.append(int_temp)
temp = value
elif action == 4:
menu = -1
I also tried the following:
temp = input("Select the name of the product? ")
product.append(temp)
value = int(input("What is the price of the product? "))
product[-1] = value
But then it just replaces the string of the product with the integer of the input I can't seem to make it a list of strings that can be referenced later in a calculation. I hope I was clear enough in my explanation of my problem and goal.
Based on your comments i think you can use a dictionary instead of a list if you want to have a mapping of product name and product price. So the code would look like below
employees = []
products = {}
menu = 1
while menu > 0:
print("1. Add employee.")
print("2. Add a product.")
print("3. Add a sale")
print("4. quit")
action = int(input("what would you like to do? Select a number: "))
if action == 1:
name = input("Employee name: ")
employees.append(name)
elif action == 2:
product_name = input("Select the name of the product: ")
product_price = int(input("What is the price of the product: "))
products[product_name] = product_price
elif action == 4:
menu = -1
Then later in your code you can simply do like this.
sales = products['apples'] * 100
or
sales = products.get('apples', 0) * 100
Hope this helps !!
Your code contains some errors, which I have mentioned below. Remove them and try again
Remove print from your input statements:
Like change this line:
name = input(print("Employee name: "))
to this:
name = input("Employee name: ")
Before this line of code:
product.append(int_temp)
make sure the product list is initiated like:
product = list()
And this line below:
product[-1] = value
will change the last value in the product list since -1 will refer to the last index, -2 will refer to second last and so on.
Trying to create program to answer this question:
[ ] The records list contains information about some company's employees
each of the elements in records is a list containing the name and ID of an employee.
Write a program that prompts the user for a name and return the ID of the employee if a record is found
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
This is my code, so far:
ui = input('Enter employee name: ')
for row in records:
if row[0] in ui:
print(row[1])
else:
print('Employee not found!')
ui = input('Enter employee name: ')
I cannot seem to find a way to check if 'ui' is in the records list.
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
user_name = 'colette' # User input
for i in range(0,len(records)):
# Here I make User name and Name in Recored in lower case so it can match perfectly
if user_name.lower() in records[i][0].lower():
print(records[i])
else:
print("employee not found")
Associate the else block with the for loop instead of the if statement
ui = input('Enter employee name: ')
for row in records:
if row[0] == ui:
print(row[1])
break
else:
print('Employee not found!')
But, if you convert the nested list to a dict, it would be much easier to get the 'id'
ui = input('Enter employee name: ')
d = dict(records)
print(d.get(ui, 'Employee not found!'))
You can use list comprehension to do it -
[i for i in records if ui in i]
This will give you a list of list of employee you are trying to find else empty list.
For ex-
ui = 'Colette'
O/P -
[['Colette', 22347]]
You could do something like -
ui = input('Enter employee name: ')
found = [i for i in records if ui in i]
if found:
for emp in found:
print(emp[1])
else:
print("Employee not found")
This should take care of it, Do keep in mind when comparing two strings, python doesn't automatically convert uppercase to lowercase so its important if you intend to compare a string that you convert both the string in either lower or uppercase
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
ui = str.lower(input('Enter employee name: '))
names_to_compare=[t[0].lower() for t in records]
if ui in names_to_compare:
print(records[names_to_compare.index(ui)][1])
else:
print("Employee not in records")