How to define key in this code python - python

I want my code to record the latest 3 scores for each student and when a 4th one is added it will overwrite the oldest score and replace it with the new one. I need the layout to be:
f,7,8,9
I have created this code but when i run it it asks me to define key. This is my code:
pname = input("What is your name")
correct = input("What is your score")
SCORE_FILENAME = "Class1.txt"
MAX_SCORES = 3
try: scoresFile = open('Class1.txt', "r+")
except IOError: scoresFile = open('Class1.txt', "w+") # File not exists
actualScoresTable = dict()
for line in scoresFile:
tmp = line.replace("\n","").split(",")
actualScoresTable[tmp[0]]=tmp[1:]
scoresFile.close()
if pname not in actualScoresTable.keys():
actualScoresTable[pname] = [correct]
else:
actualScoresTable[pname].append(correct)
if MAX_SCORES < len(actualScoresTable[pname]):
actualScoresTable[key].pop(0)
scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for key in actualScoresTable.keys():
scoresFile.write("%s,%s\n" % (key, ','.join(actualScoresTable[key])))
scoresFile.close()
When i run the code it tells me that 'key' is not defined.
How would i define key?
I have been told that it needs to be a tuple but i dont know how to make it that and for my code to work.
Traceback (most recent call last):
File "C:\Users\Milan\Documents\Python\Task 3 tries\3 scores.py", line 23, in <module>
actualScoresTable[key].pop(0)
NameError: name 'key' is not defined

The Error is in this line:
actualScoresTable[key].pop(0)
You don't define key until after this code.
I think what you want is actualScoresTable[pname].pop(0).

Related

Can not append to file.readline (Attribute Error) - I expected it to be a list

How can I store another value in the pre-existing list todos?
When I try to store the new datum, I have the following error
Traceback (most recent call last):
File "E:\Coding\python projects\project 1\add_or_show.py", line 11, in <module>
todos.append(todo)
^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'append'`
And here it is my code
while True:
action = input("what action you want add or show or exit: ")
match action:
case 'add':
todo = input("Enter the name of a student: ") + '\n'
file = open('pyt.txt', 'r')
todos = file.readline()
file.close()
todos.append(todo)
file = open('pyt.txt', 'w')
file.writelines(todos)
case 'show':
for ind, expand in enumerate(todos):
index = ind + 1
print(f"{index} - {expand}")
print("The length of Class is: ", len(todos))
case 'exit':
print("\n\nyour program exit succaessfully\n\nBye Bye!!!")
break
case 'edit':
num = int(input('Enter number which you want to edit'))
num_n = num-1
edt = todos[num_n]
print(edt)
put = ('Enter the word you want instead of', edt, ': ')
newedt = input(put)
todos[num_n] = newedt
print("Thanks!, Entry edited Successfilly")
case _:
print('Invalid action, please write add or show or exit')
try use this
todos = file.readlines()
file.readlines() is a method of the built-in Python file object that reads all the lines of the specified file and returns them as a list of strings.
file.readline() is a method of the built-in Python file object that reads a single line of the specified file and returns it as a string.

Changing a Field in a Record Gives an IndexError

I have a program to make an address book, and I want to be able to confirm a change to a record before doing so--if I search for the last name "Peterson" and there are two entries, I can choose to change one, both, or neither. I'm trying to use basically the same code to either edit an existing line, or delete it from the program.
I'm new to Python and this is my final project for a class, and I've spent like four days trying to figure out what isn't working. I've been looking through Stack Overflow and haven't found a satisfactory answer to my problem, and I am sure that's because I don't understand Python well enough. We're supposed to use the set up of creating and renaming a temp file, so while I know that's not the most efficient, it's what I'm supposed to do.
This is what I have:
import os
FIRSTNAME = 0
LASTNAME = 1
STREETADDRESS = 2
CITY = 3
STATE = 4
ZIP = 5
TELEPHONE1 = 6
TELEPHONE2 = 7
def modify():
found = False
search = input("Enter an item to search for: ")
new = input("And what should we change it to? ")
addressbook = open("addressbook.txt", "r")
temp_file = open("temp.txt", "w")
line = addressbook.readline()
while line != "":
line = line.rstrip("\n")
lineInfo = line.split("|")
if lineInfo[1] == search:
print("I found it!")
print(format(lineInfo[FIRSTNAME], '15s'),format(lineInfo[LASTNAME], '15s'),format(lineInfo[STREETADDRESS], '20s'),format(lineInfo[CITY], '10s'),
format(lineInfo[STATE], '5s'),format(lineInfo[ZIP], '10s'),format(lineInfo[TELEPHONE1], '15s')," ",format(lineInfo[TELEPHONE2], '10s'))
print()
delete = input("change this one? press y for yes.")
if delete == "y":
found = True
lineInfo[1] = new
temp_file.write(format(lineInfo[FIRSTNAME])+"|")
temp_file.write(format(lineInfo[LASTNAME])+"|")
temp_file.write(format(lineInfo[STREETADDRESS])+"|")
temp_file.write(format(lineInfo[CITY])+"|")
temp_file.write(format(lineInfo[STATE])+"|")
temp_file.write(format(lineInfo[ZIP])+"|")
temp_file.write(format(lineInfo[TELEPHONE1])+"|")
temp_file.write(format(lineInfo[TELEPHONE2])+"|")
temp_file.write("\n")
else:
temp_file.write(line)
temp_file.write("\n")
else:
temp_file.write(line)
temp_file.write("\n")
line = addressbook.readline()
temp_file.close()
os.rename("temp.txt","newaddress.txt")
if found:
print("File has been changed")
else:
print("File was not found")
modify()
Presently when I run it, I get this:
Enter an item to search for: Peterson
And what should we change it to? Patterson
I found it!
Edward Peterson 10 Grand Pl
Kearny NJ 90031 383-313-3003 xxx
change this one? press y for yes.n
I found it!
James Peterson 11 Grand Pl
Kearny NJ 90021 xxx xxx
change this one? press y for yes.y
Traceback (most recent call last):
File "C:\Users\kendr\Desktop\Address Book\Delete Address Book.py", line 53, in <module>
delete()
File "C:\Users\kendr\Desktop\Address Book\Delete Address Book.py", line 22, in delete
if lineInfo[1] == search:
IndexError: list index out of range
Honestly I'm at my wit's end with this assignment, so any and all help would make a huge difference.
Thanks,
K
You need to move line = line.rstrip("\n") to before you check if the line is empty:
line = addressbook.readline().rstrip("\n")
while line != "":
...
line = addressbook.readline().rstrip("\n")
Otherwise you'll read "\n" for the last line, and this will fail the test, so you'll go into the loop body and try to read process this empty line.

Undefined thing in my python program

Its an absolutely abhorrent and awful code, and I have no real idea on how to proceed, I'm rather lost here and this undefined variable is only causing immense stress. The finalists variable is an imported list from a CSV, and for some reason it's undefined, an explanation and steps to fix this would be extremely helpful.
def finalistsOpen():
import csv
with open('Diving championship_Finalists csv file.csv', 'rb') as f:
reader = csv.reader(f)
finalists = list(reader)
print finalists
return finalists
def scoreCalculator(finalists):
scores = []
sortedScores = []
for number in range(5):
print ("Please enter a score for " + finalists[number])
print ("---------------------------------------------------------------------------------------------------------------")
for number in range(5):
scores.append(validation(0,10))
maxScore = scores[0]
minScore = scores[0]
for number in scores:
if number > maxScore:
maxScore = number
elif number < minScore:
minScore = number
scores.remove[minScore]
scores.remove[maxScore]
sumScore = sum[scores]
sortedScores.append(sumScore)
return sortedScores,sumScore
print scores
print sumScore
print sortedScores
finalistsOpen()
scoreCalculator(finalists)
This is the error message:
Traceback (most recent call last):
File "N:\Computing Assignment 2018\Finalist.py", line 40, in <module>
scoreCalculator(finalists)
NameError: name 'finalists' is not defined
finalistsOpen()
needs to be
finalists = finalistsOpen()

Overwrite a value in a specific column with a variable in python text

I am making this program so that the user types in something, which is stored as a variable, and then overwriting a value in a specific column in a text file with the variable. I always get the problem
TypeError: 'int' object is not callable
Here is my code that i need help with.
with open("Base.txt", "r") as f:#opening it as variable f makes it easier to call to later
searchlines = f.readlines()#shortens the function f.readlines() to searchlines. This is easier to reference later
infile = open("Base.txt","r+")#opens the file in reading mode
liness = infile.readlines()#makes the variable liness to be the same as reading lines in the file
liness = ', '.join(liness)#adds commas onto liness, which is equal to new liness
liness = liness.split(" ")#breaks apart the quotations
for i, line in enumerate(searchlines):
if barcode in line:
words = line.split(" ")#sets the word variable to split the line into quotes
howmany =int(input("How many are your buying? "))
quantity=int(words[3])
if howmany < quantity:
with open("Base1.txt","w") as p:
quantity=int(words[3])
update=int(quantity-howmany)
p.write(quantity[update])
break
my whole code is
import sys
import string
x = 0
menu = 0
recipt = open("Recipt.txt","r+")
recipt.seek(0)
recipt.truncate()
recipt.close()
total = 0#Makes the variable total 0, this makes it easier to work with later
while x == 0:
menu = input("What do you want to do?\n 1)Add to the Recipt \n 2)View the Recipt \n 3)Checkout \n")#Gives the user a choice
if menu == "1":
recipt = open("Recipt.txt","a")#opens an empty text file. This will be the receipt
y = 0
while y == 0:
barcode = input("What is the barcode of the item? ")
if len(barcode) == 8:
searchfile = open("Base.txt", "r+")#Opens the premade database file
y = y + 1
else:
print("That barcode is not 8 in length.")
with open("Base.txt", "r") as f:#opening it as variable f makes it easier to call to later
searchlines = f.readlines()#shortens the function f.readlines() to searchlines. This is easier to reference later
infile = open("Base.txt","r+")#opens the file in reading mode
liness = infile.readlines()#makes the variable liness to be the same as reading lines in the file
liness = ', '.join(liness)#adds commas onto liness, which is equal to new liness
liness = liness.split(" ")#breaks apart the quotations
for i, line in enumerate(searchlines):
if barcode in line:
words = line.split(" ")#sets the word variable to split the line into quotes
howmany =int(input("How many are your buying? "))
quantity=int(words[3])
if howmany < quantity:
with open("Base1.txt","w") as p:
update=str(quantity-howmany)
p.write(str(quantity))
break
break
elif howmany==quantity:
update=0
p.write(str(update))
break
elif howmany>quantity:
print("We do not have that many!")
continue
line = line.replace('\n', '')#replaces line with a new line and a space
recipt.write(line + ' ' + howmany)#writes into the new file with the variable line and how many with a space in between
howmany = float(howmany)#turns the howmany variable into a float,decimal
prices = words[2]#prices is equal
prices = float(prices)
totalprice = prices * howmany
totalprice = ("{0:.2f}").format(round(totalprice,2))
recipt.write(" £" + totalprice + "\n")
total = float(total) + float(totalprice)
recipt.close()
elif barcode not in liness:
print("Item not found.")
if menu == "2":
with open("Recipt.txt","r+") as f:
for line in f:
print(line)
recipt.close()
if menu == "3":
recipt = open("Recipt.txt","a")
recipt.write("£"+str(total))
recipt.close()
sys.exit()
The error message.
Traceback (most recent call last):
File "C:\Users\David\Desktop\Task 2 2 Version 2.py", line 37, in <module>
p.write(quantity(update))
TypeError: 'int' object is not callable
if needed. I am trying not to use csv, so please don't respond with that as an answer. I am using python 3.5.
Thanks.
There are a few errors you need to address, i've commented both of them. In both cases they revolve around your variable quantity. quantity is an integer, meaning you cannot do quantity[value], quantity(value), quantity.function
quantity=int(words[3])
if howmany < quantity:
with open("Base1.txt","w") as p:
quantity=int(words[3])
update=int(quantity-howmany)
p.write(quantity[update]) #### quantity is an int, so this is the reason for your initial exception, you cannot index into quantity
break
break
elif howmany==quantity:
update=0
quantity.write(update) ### this is another exception causing bug
break
you cannot call .write() on the variable quantity, as it is an integer
You commented about not knowing what a traceback was, here is an example:
>>> a = 5
>>> a.write(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'write'

Python Code Error 3.3.2

I have recently been practicing my skills at figuring out my own problems but this one problem is persistent. This is the problematic code:
with open('login_names.txt', 'r') as f:
login_name = [line.rstrip('\n') for line in f]
k = input("name: ")
if k in login_name :
print("No errors")
else:
print("You have an error")
else:
print('fail')
#var = login_name.index[random]
check = login_pass[login_name.index[random]]
with open('login_passw.txt', 'r') as p:
login_pass = [line.rstrip('\n') for line in p]
s = input("pass: ")
if s == check :
print("Works")
else:
print("Doesn't work")
f.close()
p.close()
Basically when I run the code it says:
Traceback (most recent call last):
File "C:/Python33/Test.py", line 29, in <module>
check = login_pass[login_name.index[random]]
TypeError: 'builtin_function_or_method' object is not subscriptable
I have tried lots of different suggestions on different questions but none of them have worked for me...
If we assume that login_pass, login_name and random are defined in the namespace that line is in, the only problem you have is that you should write
check = login_pass[login_name.index(random)]
str.index is a function that returns the first index of the argument given in str, so you use () instead of [], which you would use for lists, tuples and dictionaries.

Categories