Related
I am a new learner in python trying to understand the logic and the solution of this problem.Exercise says to create an order app for a coffee shop .
import uuid # GET A RANDOM ID FOR THE CUSTOMER
from datetime import date # GET CURRENT DATE
from csv import DictWriter
inlist = -1
length = 0
Total_Amount = 0.0
CustomerList = []
AddressList = []
Today_Key = date.toordinal(date.today())
Today_Date = date.today()
Print_Today = Today_Date
Customers = {}
Dates = {}
FirstEmployeeAccountUsername = "coffee1"
FirstEmployeeAccountPassword = "coffeeshop1"
SecondEmployeeAccountUsername = "coffee2"
SecondEmployeeAccountPassword = "coffeeshop2"
ThirdEmployeeAccountUsername = "coffee3"
ThirdEmployeeAccountPassword = "coffeeshop3"
print("Welcome to our coffee shop!")
print("Login")
# EMPLOYEE LOGIN PROCESS STARTS
LoginEnter = True
while LoginEnter:
username = input("Username: ")
password = input("Password: ")
if username == FirstEmployeeAccountUsername and password == FirstEmployeeAccountPassword or username == SecondEmployeeAccountUsername and password == SecondEmployeeAccountPassword or username == ThirdEmployeeAccountUsername and password == ThirdEmployeeAccountPassword:
print("Login Successful")
LoginEnter = False
else:
print("Invalid Login. Try again")
# EMPLOYEE LOGIN PROCESS ENDS
# PROCESS AFTER ORDER PLACEMENT STARTS
process1 = True
process2 = True
while process1:
while process2:
Customer_Name = input("Customer's Name:")
CustomerList.append(Customer_Name)
Customers_Address = input("Customer's Address:")
AddressList.append(Customers_Address)
if Today_Key not in Dates:
Dates[Today_Key] = {}
if Customer_Name not in Dates[Today_Key]:
Dates[Today_Key][Customer_Name] = 1
else:
Dates[Today_Key][Customer_Name] += 1
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Address'] = Customers_Address
Customers[Customer_Name]['ID'] = uuid.uuid1()
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
print(Customer_Name, "has ordered {} time(s)".format(Customers[Customer_Name]['Orders']))
if Customers[Customer_Name]['TotalAmount'] == 0:
print("This is the first time", Customer_Name, "orders")
else:
print(Customer_Name, "has spent", Customers[Customer_Name]['TotalAmount'], "in total")
print("Current Date is: {}".format(Today_Date))
Order_Price = float(input("Total amount of order:"))
Total_Amount = Order_Price + Total_Amount
if Print_Today != Today_Date:
print("Total amount of orders today is: ", float(Total_Amount))
answer1 = input("Send another order? (Y/N)").lower()
if answer1 == "y":
process2 = True
else:
process2 = False
LengthCustomersList = len(CustomerList)
length += 1
inlist += 1
file = open('CustomerNames.txt', 'w')
file.write(str(CustomerList[0:]) + '\n') # TAKE CARE FOR DUPLICATE NAMES FROM SAME ADDRESS
file.close()
file1 = open('Orders_Per_Users.txt', 'a')
file1.write(Customer_Name + " has ordered " + str(
Customers[Customer_Name]['Orders']) + " times in total\n") # FIX DUPLICATES SAME NAME SAME ADDRESS
file1.close()
with open('data_entered.csv', 'a') as f:
csv_writer = DictWriter(f, fieldnames=['Customer Name', 'Customer Address', 'Customer ID', 'Total Orders',
'Total Amount'])
csv_writer.writeheader()
csv_writer.writerows([{'Customer Name': CustomerList[inlist], 'Customer Address': AddressList[inlist],
'Customer ID': Customers[Customer_Name]['ID'],
'Total Orders': Customers[Customer_Name]['Orders'],
'Total Amount': Customers[Customer_Name]['TotalAmount']}])
if int(length) == int(LengthCustomersList):
process1 = False
My idea is to do something like an if statement so when the same Customer ID and the same CustomerName show up in the .csv file , one of them gets deleted, so the file does not contain any duplicates like those in the screenshot above.
I am not sure we are going to eventually solve your question but I wanted to give you some inputs that you can use to fix your code.
Use of variable Today_Date and Print_Today in your code
Today_Date = date.today()
Print_Today = Today_Date
if Print_Today != Today_Date:
These two lines are set to the same value. Later on in the code, you are checking if the are not equal. I checked Print_Today and Today_Date for reassignment. None occurs. So how do you expect these two variables to have different values?
If this program runs for infinite number of days, it will still NOT change the value of these two variables. The reason is they were defined at the beginning of the program and never changed. You may want to look into it.
The use of Today_Key in Dates dictionary in your code.
Today_Key = date.toordinal(date.today())
Dates = {}
You are using Today_Key to count the number of times a customer name was entered. I don't see a point in having Today_Key as the key unless you plan to have more than one key in the dictionary. This was set at the beginning of the program and never changed. So what do you intend to do with this key? I don't think you should have that as key. Instead you should just keep track of the customer names. Also, you are not printing or writing this information into a file. Are you intending to use this later in the program? I dont see the value and it may just be using up memory space and processing time.
Use of multiple names for Username & Password.
You have created 6 variables to store username & password. In other places, you are using dictionary. So why are you not taking advantage of the dictionary here?
FirstEmployeeAccountUsername = "coffee1"
FirstEmployeeAccountPassword = "coffeeshop1"
SecondEmployeeAccountUsername = "coffee2"
SecondEmployeeAccountPassword = "coffeeshop2"
ThirdEmployeeAccountUsername = "coffee3"
ThirdEmployeeAccountPassword = "coffeeshop3"
Instead of these, can't you just define a dict variable and check for the value as shown below?
UserLogin = {"coffee1":"coffeeshop1", "coffee2": "coffeeshop2", "coffee3": "coffeeshop3"}
username = password = ''
while True:
username = input("Username: ")
password = input("Password: ")
if (username in UserLogin) and (UserLogin[username] == password):
print("Login Successful")
break
else:
print("Invalid Login. Try again")
For your customer name counter portion, try this. I dont think you are actually doing anything with the counter. If you are, this code is much simpler.
CustomerCounts = defaultdict(int)
while True:
Customer_Name = input("Customer's Name:")
CustomerList.append(Customer_Name)
Customers_Address = input("Customer's Address:")
AddressList.append(Customers_Address)
CustomerCounts[Customer_Name] += 1
similarly, try using defaultdict and reduce a lot of code you have written. In the end, there is lot of code optimization and logic corrections you can do. However, it does not solve the infinite loop situation.
I am attempting to create a coronavirus temp scan compare program. I want to open an excel file and create a small database each day of scanned employees. When I execute I am just getting the first input prompt and my excel spreadsheet is not opening. My goal was to have each line of code under the while statement nested and would continue to loop until the program operator ended the loop. My code is below. Any help is appreciated.
from datetime import date
from xlwt import Workbook
# Workbook is created
wb = Workbook()
# add sheet
sheet1 = wb.add_sheet('Temperature Scans')
sheet1.write(0, 0, 'First Name')
sheet1.write(0, 1, 'Last Name')
sheet1.write(0, 2, 'Date')
sheet1.write(0, 3, 'Temperature')
Normal = 98.6
Recording = input("Are you Recording Temperature Today? 1 if yes; 0 if no: ")
while Recording == 1:
Employee_First = input("Enter First Name: ")
Employee_Last = input("Enter Last Name: ")
Temp = float(input("Input Scanned Temperature (Example if 99 degrees enter 99): "))
if Temp > Normal:
print("Elevated Temperature Detected! Entrance Not Permitted")
else:
print("Temperature Within Acceptable Limits. Entrance Permitted")
Date = today.strftime("%m/%d/%y")
for i in range(0, 15000):
sheet1.write(i+1, 0, Employee_First)
sheet1.write(i+1, 1, Employee_Last)
sheet1.write(i+1, 2, Date)
sheet1.write(i+1, 3, Temp)
Day = today.strftime("%d")
Month = today.strftime("%m")
Year = today.strftime("%y")
wb.save(Month, _ , Day, _ , Year, 'Temp Scans.xlsx')
break
continue
The input statement will only take input as a string, it is up to you to convert it into different formats:
Recording = input("Are you Recording Temperature Today? 1 if yes; 0 if no: ")
while Recording == '1':
# do something
Change this of your code:
Recording = input("Are you Recording Temperature Today? 1 if yes; 0 if no: ")
To:
try:
Recording = int(input("Are you Recording Temperature Today? 1 if yes; 0 if no: "))
except:
print("Please enter a valid number (either 1 or 0)")
in order to make sure that you enter the while loop:
...
while Recording == 1:
Employee_First = input("Enter First Name: ")
...
Since the input() will always return a string variable and you are making the comparison on the while loop with an integer.
EDIT
Here is a mofification of the code you provided using the openpyxl library. The code below will interactively ask for the employee's first name, last name and temperature and finally overwrite the temperaturescans.xlsx file (or create it if it doesn't exist and you run the python script for the first time).
from openpyxl import Workbook
from datetime import datetime
#Create workbook
wb = Workbook()
# grab the active worksheet
ws = wb.active
# Fill up the headers on the first row
ws['A1'] = 'First Name'
ws['B1'] = 'Last Name'
ws['C1'] = 'Date'
ws['D1'] = 'Temperature'
#Define some constant values
normal_temperature = 98.6
date = datetime.today().strftime('%m/%d/%y')
try:
recording = int(input("Are you Recording Temperature Today? 1 if yes; 0 if no: "))
except:
print('Please enter a number: either 1 or 0')
while recording == 1:
#Get employees First Name
employee_first = input('Enter First Name:')
#Get employees Last Name
employee_last = input('Enter Last Name:')
#Get temperature
try:
temperature = float(input('Input Scanned Temperature (example if 99 degrees enter 99):'))
except:
print('Please enter a valid value for the temperature (99.2, 98.6)')
#Check if the employee has a fever
if temperature > normal_temperature:
print('Elevated Temperature Detected! Entrance Not Permitted')
else:
print("Temperature Within Acceptable Limits. Entrance Permitted")
#Add the employees row to the sheet
ws.append([employee_first,employee_last,date,temperature])
try:
recording = int(input("Are you Recording Temperature Today? 1 if yes; 0 if no: "))
except:
print('All recordings have been made. Saving the file.')
#Save the file
print('Check the temperaturescans.xlsx file for the results.')
wb.save("temperaturescans.xlsx")
I'm writing some python code that works out a person's total pay.
I am able to do this by getting the user to input their pay, however I would like them just to be able to enter their name and then the name is searched in position 0 of a list (Eg. 0,1 0,2 0,2 etc).
I have tried using a tuple but it is not callable and the dictionary and list would not work for me either.
counter = 0
valid = 0
employeelist = [["thomas","2","500"], ["jake","1","750"]]
while True:
while True:
try:
name = str(input("Name:"))
except ValueError:
print("Error")
continue
else:
break
while True:
if name == employeelist[counter,0]:
print(employeelist[counter])
break
valid = 1
elif counter = 3:
print("invalid name")
break
else:
counter = counter + 1
if valid == 1:
break
months = employeelist[counter,1]
pay = employeelist[counter,1]
totalpay = int(months) * int(pay)
Edit:
I do no longer have the code with the dictionary, however I just edited the code from [counter,1] and [0,1] to [counter][1] and is working fine thank you :D
The code below is for your inner loop
employeelist = [["thomas","2","500"], ["jake","1","750"]]
name = ""
while True:
try:
name = input("Name:")
break
except:
print "Error"
position = -1
for i, element in enumerate(employeelist):
if element[0] == name:
position = i
break
if position == -1:
print "Invalid Name"
else:
totalpay = int(employeelist[position][1]) * int(employeelist[position][2])
Your code have multiple bugs. First, valid=1, is set after breaking the loop -meaning valid=1,is never set. You also are checking elif counter = 3 this way, you should rather use two equality signs, like this: elif counter == 3
The error you are getting, that list indices must be integers or slices, not tuple, you are having because you are accessing a multidimensional array the wrong way. Instead of name == employeelist[counter, 0], it should be name == employeelist[counter][0].
Your way of iterating through the array is possible, but its rather simpler using a for loop.
Try this way.
for employees in employeelist:
if name == employees[0]:
print(employee)
valid = 1
break
If it iterated through the hole employeelist, without the if-block running, valid = 1, would never been set.
Working code:
counter = 0
valid = 0
employeelist = [["thomas","2","500"], ["jake","1","750"]]
while True:
while True:
try:
name = str(input("Name: "))
except ValueError:
print("Error")
continue
else:
break
for employees in employeelist:
if name == employees[0]:
print(employees)
valid = 1
break
if valid == 1:
break
months = employeelist[counter][1]
pay = employeelist[counter][2]
totalpay = int(months) * int(pay)
print(totalpay)
I will try to simplify this is as much as possible , My code is designed for a user to enter multiple products from a data base using a barcode , resulting in my program outputting in the name of the products they ordered and the total price of the products.
However my expected output of the code when it is first run is
GTIN = int(input("input your gtin-8 number: "))
return GTIN # Breaks the loop and returns the value
except:
print ("Oops! That was not a valid number. Try again")
However this code is first run at the end of the code as the starting line for some reason.
continue_shopping=int(input("press 0 to stop shopping and print your reciept or press 1 to continue shopping"))
if continue_shopping != 0 and continue_shopping != 1:
print("make sure you enter a valid number")
I would appreciate any helpful input or criticism for my code.
If you are interested here is the code as an entity on its own. Thank you for any help
import csv
import locale
from decimal import *
total_price = []
locale.setlocale( locale.LC_ALL, '' )
def read_csv_file():
global total_price
""" reads csv data and appends each row to list """
csv_data = []
with open("task2.csv") as csvfile:
spamreader = csv.reader(csvfile, delimiter=",", quotechar="|")
for row in spamreader:
csv_data.append(row)
return csv_data
def get_user_input():
global total_price
""" get input from user """
while True:
try:
GTIN = int(input("input your gtin-8 number: "))
return GTIN # Breaks the loop and returns the value
except:
print ("Oops! That was not a valid number. Try again")
def search_user_input(product_data):
global total_price
repeat=""
# Pass the csv data as an argument
""" search csv data for string """
keep_searching = True
while keep_searching:
gtin = get_user_input()
for row in product_data:
if row[0] == str(gtin):
product = row[1]
price = round(float(row[2]),2)
return(product, price)
while True:
try:
repeat = input("not in there? search again? If so (y), else press enter to continue")
break
except:
print("please make sure you enter a valid string")
if repeat != 'y':
keep_searching = False
return None
def quantity():
fileOne = open('receipt.csv', 'a')
writer = csv.writer(fileOne)
global total_price
product_data = read_csv_file()
matches = search_user_input(product_data)
if matches: # Will not be True if search_user_input returned None
print("apple")
product, price = matches[0], matches[1]
order = int(input("How much of {} do you want?".format(product)))
TWOPLACES = Decimal(10) ** -2
subt = order * pricea
subtotal = Decimal(subt).quantize(TWOPLACES)
values = [str(product), str(price), str(subtotal)]
print('values are ',values)
writer.writerows((values,))
total_price.append(order * price)
continue_shopping=int(input("press 0 to stop shopping and print your reciept or press 1 to continue shopping"))
if continue_shopping != 0 and continue_shopping != 1:
print("make sure you enter a valid number")
if (continue_shopping == 0):
fileOne.close()
fileTwo = open("receipt.csv" , "r")
reader = csv.reader(fileTwo)
for row in reader:
if row != None:
print(row)
elif continue_shopping==1:
quantity()
quantity()
when you create a function (that's what def does), it won't do anything until you instantiate the function. so, for instance, if you want to run the read_csv_file() function before you do ask whether the person is done shopping, you have to do this. (or something similar)
#all your functions are above this snippet.
read_csv_file()
continue_shopping=int(input("press 0 to stop shopping and print your reciept or press 1 to continue shopping"))
I hope this helps!
I am fairly new to python and I need to make a program to ask 10 questions, save the score into a file and allow someone to read the scores in from the file.
My problem: I need to check if the person who has done the quiz already has a record in the file, and if so, I need to add their score to the end of their record.
The records should look like this:
name,score,score,score,score,
etc so they can be split using commas.
I am also looking for the simplest answer, not the most efficient. Also, if you could comment the code, it would make it much easier. Here is my code so far:
import random
import math
import operator as op
import sys
import re
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
while True:
try:
user_answer = int(input("Your answer: "))
except ValueError:
print("Only enter numbers!")
continue
else:
break
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
print("1. Are you a student?")
print("2. Are you a teacher?")
print("3. Exit")
while True:
try:
status = int(input("Please select an option:"))
except ValueError:
print("Please enter a number!")
else:
if status not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
if status == 1:
username=input("What is your name?")
while not re.match("^[A-Za-z ]*$", username) or username=="":
username=input(str("Please enter a valid name (it must not contain numbers or symbols)."))
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
while True:
try:
users_class = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
print("Please enter a number!")
else:
if users_class not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
if users_class == 1:
class1 = open("Class1.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class1.write(newRecord)
class1.close()
elif users_class == 2:
class2 = open("Class2.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class2.write(newRecord)
class2.close()
elif users_class == 3:
class3 = open("Class3.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class3.write(newRecord)
class3.close()
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
EDIT:
Add this function before your "test" function:
def writeUserScore(file, name, score):
with open (file, "r") as myfile:
s = myfile.read()
rows = s.split("\n")
data = {}
for row in rows:
tmp = row.split(",")
if len(tmp) >= 2: data[tmp[0]] = tmp[1:]
if name not in data:
data[name] = []
data[name].append(str(score))
output = ""
for name in data:
output = output + name + "," + ",".join(data[name]) + "\n"
handle = open(file, "w+")
handle.write(output)
handle.close()
After that, where you have "if users_class == 1:" do this:
writeUserScore("Class1.txt", username, str(correct_answers))
Do the same for the other two else ifs.
Let me know what you think!
Try using a dictionary to hold the existing file data.
Read the file in a variable called "str" for example. And then do something like this:
rows = str.split("\n")
data1 = {}
for row in rows:
tmp = row.split(",")
data1[tmp[0]] = tmp[1:]
When you have a new score you should then do:
if username not in data1:
data1[username] = []
data1[username] = str(correct_answers)
And to save the data back to the file:
output = ""
for name in data1:
output = outupt + name + "," + ",".join(data1[name]) | "\n"
And save the contents of "output" to the file.
PS: If you are not bound by the file format you can use a JSON file. I can tell you more about this if you wish.
Hope that helps,
Alex
First, define these functions:
from collections import defaultdict
def read_scores(users_class):
"""
If the score file for users_class does not exist, return an empty
defaultdict(list). If the score file does exist, read it in and return
it as a defaultdict(list). The keys of the dict are the user names,
and the values are lists of ints (the scores for each user)
"""
assert 0 <= users_class <= 3
result = defaultdict(list)
try:
lines =open("Class%d.txt"%users_class,'r').readlines()
except IOError:
return result
for line in lines:
# this line requires python3
user, *scores = line.strip().split(',')
# if you need to use python2, replace the above line
# with these two lines:
# line = line.strip().split(',')
# user, scores = line[0], line[1:]
result[user] = [int(s) for s in scores]
return result
def write_scores(users_class, all_scores):
"""
Write user scores to the appropriate file.
users_class is the class number, all scores is a dict kind of dict
returned by read_scores.
"""
f = open("Class%d.txt"%users_class,'w')
for user, scores in all_scores.items():
f.write("%s,%s\n"%(user, ','.join([str(s) for s in scores])))
def update_user_score(users_class, user_name, new_score):
"""
Update the appropriate score file for users_class.
Append new_score to user_name's existing scores. If the user has
no scores, a new record is created for them.
"""
scores = read_scores(users_class)
scores[user_name].append(new_score)
write_scores(users_class, scores)
Now, in the last portion of your code (where you actually write the scores out) becomes much simpler. Here's an example of writing some scores:
update_user_score(1, 'phil', 7)
update_user_score(1, 'phil', 6)
update_user_score(1, 'alice', 6)
update_user_score(1, 'phil', 9)
there will be two lines in Class1.txt:
phil,7,6,9
alice,6
We read the whole file into a dict (actually a defaultdict(list)),
and overwrite that same file with an updated dict. By using defaultdict(list), we don't have to worry about distinguishing between updating and adding a record.
Note also that we don't need separate if/elif cases to read/write the files. "Scores%d.txt"%users_class gives us the name of the file.