Having Trouble Executing While Loop - python

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")

Related

How to compare filename with a string in Python

I'm making a program in which you can store your data and it will have a unique code from which you can load that back. So I've made way to make a unique code by just putting the date and then putting the entry number. For example: The date is 24 April 2021 and it is the first entry of the day then it'll generate the code as 202104241. The "1" at the end means entry number 1. So i want that to change every time you make a new entry in that day. I tried it doing like this but it gives an error. Is there any to do it?
def New_Document():
LUD = 1 # LAST UNIQUE DIGIT
unique = []
date = datetime.date.today()
unique.append(date)
unique_id = str(unique[0])
unique_id = unique_id.replace('-', '')
unique_id = unique_id + str(LUD)
folder = r'E:\\Programming related\\DATASAVER'
destination = r'E:\\Programming related\\DATASAVER\\DATA'
filenames = os.listdir(destination)
print(filenames)
for file in filenames:
if filenames[file] in unique_id:
LUD += 1
unique_id = unique_id + str(LUD)
break
else:
continue
print(f"Your unique id is: {unique_id}")
pickle.dump(unique_id, open(unique_id, 'wb'))
shutil.move(folder, destination)
print("Please choose a NUMBER:")
print("1: New Document")
print("2: Existing Document")
while True:
try:
ask = int(input("Please enter a NUMBER: "))
if ask == 1:
break
elif ask == 2:
break
else:
print("Please enter '1' OR '2'")
continue
except:
print("Please '1' OR '2' NOT a WORD")
if ask == 1:
New_Document()
else:
pass

Comparing tuple values from text file in Python 3

I'm aiming to display records of employees with a salary between 2 user inputted values (in a format specified in my function printTuple(data)). So far I use the function choice2() to open the file, read line by line in a for loop, convert the line (which is a string) to an int, then grab the index of the salary so I can compare it to the 2 inputted values (. After that I take the line as a variable in "record" and go to makeTuple to turn it into a tuple, and then finally print it in my desired format inside printTuple.
When I attempt to run the choice2 function I get an error: "local variable 'myTuple' referenced before assignment". However I need to change the myTuple value to an int before I can compare it with the values the user inputted, so I'm not sure how to fix this.
Here is my program:
def makeTuple (employee):
myTuple = employee.split(" ")
(payroll, salary, job_title, *othernames, surname) = myTuple
return(myTuple)
def printTuple (data):
employee_str = "{:<15} {:20} {:<10} {:<15} £{:>1}"
print(employee_str.format(data[-1]+ ",", " ".join(data[3:-1]), data[0], data[2], data[1]))
def choice1():
op_1 = str(input("Please enter a Pay Roll number: "))
file = open(path)
lines = file.readlines()
for line in lines:
if op_1 in line:
record = line.strip()
myTuple = makeTuple(record)
printTuple(myTuple)
def choice2():
op_2a = int(input("Please enter a lower bound for the Salary :"))
op_2b = int(input("Please enter a higher bound for the Salary :"))
file = open(path)
lines = file.readlines()
for line in lines:
myTuple[0] = int(myTuple[0])
if myTuple[0] >= op_2a and myTuple[0] <= op_2b:
myTuple[0] = myTuple[0]
record = line.strip()
myTuple = makeTuple(record)
print(myTuple)
get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"
try:
f = open(path)
except IOError:
print('The file could not be opened.')
exit()
for line in iter(f):
record = line.strip()
myTuple = makeTuple(record)
printTuple(myTuple)
print("\n\nDisplay full details of an Employee with a given payroll number enter: '1'")
print("Display all employees with a salary within a specified range, enter: '2'")
print("Display the first and last name of all employees with a job title, enter: '3'")
print("Quit Program: '4'")
choice = int(input("Choose an option from 1-4: "))
while choice != 1 and choice != 2 and choice != 3 and choice != 4:
print("Incorrect Value, please choose a number from 1-4")
print("\n\nDisplay full details of an Employee with a given payroll number enter: '1'")
print("Display all employees with a salary within a specified range, enter: '2'")
print("Display the first and last name of all employees with a job title, enter: '3'")
print("Quit Program: '4'")
choice = int(input("Choose an option from 1-4: "))
if choice == 1:
choice1()
if choice == 2:
choice2()
if choice == 3:
choice3()
if choice == 4:
exit()
This is the text file I am reading from:
12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
12349 30000 Wizard Harry Potter
12350 15000 Entertainer Herschel Shmoikel Krustofski
13123 75000 Consultant Zlatan Ibrahimovic
13124 150000 Manager Gareth Southgate
13125 75000 Manager Juergen Klopp
13126 35000 Lecturer Mike T Sanderson
13127 200000 Entertainer Adele Laurie Blue Adkins
13128 50 Timelord Peter Capaldi
13129 250000 Entertainer Edward Christopher Sheeran
13130 32000 Secretary Wilma Flintstone
Any help is appreciated, thanks in advance.
Your error message (local variable myTuple referenced before assignment) points out the required solution. I have:
reordered (record = line.strip() and myTuple = makeTuple(record) to top of loop)
renamed some variables (myTuple is not very descriptive, and is actually a list anyway, better naming makes code much easier to read and reason about)
heavily commenting (I would not normally comment my own code this much, more as indications of what I have done and why)
Here is the updated code for choice2
def choice2():
lower_bound = int(input("Please enter a lower bound for the Salary :")) # Renamed for clarity
upper_bound = int(input("Please enter a higher bound for the Salary :")) # Renamed for clarity
# The following two lines are repeated multiple times, you should probably read
# the file once and store into a list (or better yet a dictionary
# keyed with pay roll number) and pass it into the function.
file = open(path)
lines = file.readlines()
for line in lines:
record = line.strip()
employee_details = makeTuple(record) # Rename muTuple to employee_details
# OR MORE SIMPLY employee_details = makeTuple(line.strip())
# Now we have the variable we can work with it
salary = int(employee_details[0]) # The only thing we do with the tuple is print it, so no need to modify it
if salary >= lower_bound and salary <= upper_bound:
# This does nothing, so deleted - myTuple[0] = myTuple[0]
print(employee_details) # Or more likely you want to use your custom print function printTuple(employee_details)

Python, Pandas - How can I get something printed in a data range?

I suppose to create a function that allows user pick a range and it will print out the number within the range. however, I keep getting empty DataFrame with my code. can anyone help me?
` import pandas as pd
if __name__ == "__main__":
file_name = "sales_rossetti.xlsx"
# Formatting numbers (e.g. $1,000,000)
pd.options.display.float_format = '${:,.0f}'.format
# Reading Excel file
df = pd.read_excel(file_name, index_col = 0, convert_float = False)
print ("Welcome to Rossetti's Sales program\n")
print ("1) Search by State")
print ("2) Search by Jan Sales")
print ("3) Search by Q2 sales")
print ("4) Exit")
my_option = input ("Please select a menu option:")
if (my_option=="2"):
my_columns = ["Name", "City", "State", "Jan"]
your_sales = input("please enter the minimum sale: ")
your_sales = input("please enter the maxium sale: ")
print (df[my_columns][df.Jan>int(your_sales)][df.Jan<int(your_sales)])`
You're overwriting the your_sales variable as you're reusing it, so you should use a different variable name for the min and max params. You then need to generate a proper boolean mask using loc and enclosing your boolean conditions using parentheses and & to and the array of boolean values:
if (my_option=="2"):
my_columns = ["Name", "City", "State", "Jan"]
min_sales = input("please enter the minimum sale: ")
max_sales = input("please enter the maxium sale: ")
print (df.loc[(df.Jan > int(min_sales) ) & (df.Jan < int(max_sales)), my_columns])
the above should work

IndexError: list index out of range when trying to work with a CSV

I am working with a CSV file for a program I am writing but I seem to be getting this error:
Traceback (most recent call last):
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453 Material 2\Task 3\Task 3.py", line 115, in <module>
actionQ()
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453`Material 2\Task 3\Task 3.py", line 111, in actionQ
gtinQuestion()
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453 Material 2\Task 3\Task 3.py", line 80, in gtinQuestion
quantityQuestion() #It will start the quantityQuestion subprogram.
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453 Material 2\Task 3\Task 3.py", line 52, in quantityQuestion
if float(row[3]) >= float(quantity):
IndexError: list index out of range`
I'm not quite sure how to approach it but I have never had this problem before. Initially, quantityQuestion was its own program but I have decided to place it with this other code for accessibility.
As a side note - I am unable to overwrite the third row so that the new stock can be updated in the CSV. (Any help on this is also appreciated).
Code:
import csv
import sys
global totalPrice
totalPrice = 0
addItem = ""
gtinNum = ""
quantity = 0
restart = ""
price = 0
receipt = open("receipt.txt", "w+")
restockTxt = open("restock.txt", "w+")
file = open("ChocolateCSV2.csv", "r")
def restart():
restart = input("Would you like to restart? Y/N")
if restart.lower() == "y":
actionQ()
else:
file.close()
print("Exiting program.")
sys.exit()
def priceSub(): #Defining the restart subprogram
priceQ = input("Would you like to add an item? Y/N") #Asks the user if they would like to add an item.
global totalPrice #Declaring totalPrice and making it global.
totalPrice = int(price) + totalPrice #Setting totalPrice to add the variable price to itself.
if priceQ.lower() == "y": #If statement that checks to see if the user has entered a "y".
gtinQuestion() #If it is true, it will start the gtinQuestion subprogram.
else: #Anything other than a "y" will do the following commands.
global receiptCont #Declaring the receipt content as a global variable.
receiptCont = receipt.read() #Reads the receipt.
receipt.close() #Closes the file.
print(receiptCont) #Prints the content of the receipt.
print("Total Price: " + "%.2f" % round(totalPrice, 2)) #Prints the totalPrice variable rounded to two decimal places.
restart()
def quantityQuestion(): #Defining the subprogram for the quantity.
quantity = input("How much would you like?") #Asks the user how much of the item they would like.
if quantity.isdigit() == False: #If statement to check whether or not the user has entered an integer or not.
quantityQuestion() #If they have not entered an integer, it will ask the question again.
global price #Declaring the variable price as a global variable.
price = "" #Setting price to an empty string.
with open("ChocolateCSV.csv", 'r') as file2:
for row in csv.reader(file2): #Loop that seperates each row in the CSV
if str(gtinNum) in row[0]: #If statement to check if the GTIN given by the user is in the CSV.
if float(row[3]) >= float(quantity):
receipt.write(str(row) + "\n") #If it is in one of the CSV rows, it will write the row to the text file.
receipt.write(str("- Quantity: " + quantity + "\n")) #It also writes the quantity given by the user.
price = float(row[2]) * int(quantity) #The price is the price given by the CSV file multiplied by the quantity.
receipt.write("- Price: " + str("%.2f" % round(price, 2)) + "\n") #The final price (after the multiplication) is written to the text file also.
updateStk = str(float(row[3]) - float(quantity))
row[3] = updateStk
file2w = open("ChocolateCSV2.csv", "w", newline = "")
writeCSV = csv.writer(file2w)
writeCSV.writerows(csvList)
file2w.close()
priceSub() #Starts the restart subprogram.
break #Breaks the loop.
elif float(row[3]) <= float(quantity):
print("There is not enough stock to allow you to purchase this item - Try again u nerd.")
gtinQuestion()
else:
print("The code entered could not be found - Please re-enter") #If it is not in the CSV it will print this error message.
gtinQuestion() #Starts the gtinQuestion subprogram.
def gtinQuestion(): #Defining the gtinQuestion subprogram.
global gtinNum #Declaring the gtinNum variable as global.
gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:") #Setting that variable to the initial question.
if gtinNum.isdigit() == False or len(gtinNum) != 8: #If the code given is not an integer or is not 8 digits long...
print("Please re-enter your GTIN-8 code - Reason: Invalid Code") #It will print this error message and ask the question again.
gtinQuestion()
elif gtinNum.isdigit() == True and len(gtinNum) == 8: #If it is an integer and is 8 digits long...
quantityQuestion() #It will start the quantityQuestion subprogram.
def restockAction():
reader = csv.reader(file, delimiter = ",")
csvList = list(reader)
for row in csvList:
stDiff = float(row[5]) - float(row[3])
if float(row[3]) <= float(row[4]):
restockTxt.write(row[0]+" | "+row[1]+" | "+"Stock Replenished: "+(str(stDiff)+"\n"))
row[3] = row[5]
file2w = open("ChocolateCSV2.csv", "w", newline = "")
writeCSV = csv.writer(file2w)
writeCSV.writerows(csvList)
file2w.close()
else:
restockTxt.write("No (other) stock needs to be replenished.")
restockTxt.close()
restockRead = open("restock.txt", "r") print(restockRead.read())
restart()
def actionQ():
restock = input("What action would you like to perform?:\n Restock (Enter 1)\n Order (Enter 2)")
if restock == "1" or restock == "restock":
print("Restock Action Requested...")
restockAction()
elif restock == "2" or restock == "order":
print("Ordering action Requested...")
gtinQuestion()
else:
actionQ()
actionQ()
CSV File:
12312313 Item 1 0.5 100 25 100
12345670 Item 2 0.2 100 25 100
76543210 Item 3 0.3 100 25 100
34563670 Item 4 0.4 100 25 100

How do I make my program give me the value of a certain cell in a CSV?

I am having problems with trying to make my program find a certain cell in a CSV file. My program will ask you for a 8 digit number. If it is in the CSV file, the row should be written to a text file. It then should proceed to ask the user how much of the product they want to buy. This quantity will then be multiplied to give a final price. The price will be written to a variable named totalPrice.
My initial problem is with the quantity since I cannot retrieve it from the third column of the row of the entered GTIN-8 number in my CSV file.
My code is:
import csv
import sys
import re
import os
addItem = ""
gtinNum = ""
quantity = 0
totalPrice = 0
restart = ""
f = open("ChocolateCSV.csv", "rt")
def restart():
restart = input("Would you like to restart? Y/N")
if restart.lower() == "y":
gtinQuestion()
else:
print(receiptCont)
sys.exit()
def quantityQuestion():
quantity = input("How much would you like?")
def scanGTIN():
global rows
rows = re.split('\n', f.read())
global receiptCont
receiptCont = receipt.read()
for index, row in enumerate(rows):
global cells
cells = row.split(',')
if gtinNum in cells:
receipt.write(receiptCont)
receipt.close()
quantityQuestion()
def gtinQuestion():
global gtinNum
global receipt
receipt = open("receipt.txt", "r+")
gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:")
if gtinNum.isdigit() == False or len(gtinNum) != 8:
gtinQuestion()
elif gtinNum.isdigit() == True and len(gtinNum) == 8:
scanGTIN()
gtinQuestion()
You could just iterate through the lines of the csv file and return a particular column of the row that contains the 8 digit number:
import csv
def get_row(filename, number, column):
with open(filename, 'r') as f:
for row in csv.reader(f):
if str(number) in row:
return row[column+1]

Categories