Undefined thing in my python program - python

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

Related

NameError: name 'variable' is not defined. Already declared variable but still error

I tried to extract data from a text file (cisco switch logs) and convert it to CSV so I can create a table and sort out the data & create graphs out of it. So here is my code:
import pandas as pd
import csv
import time
from datetime import datetime
import os
import glob
import sys
pathh = glob.glob("C:\\Users\\Taffy R. Mantang\\Desktop\\PR logs\\*\\")
#This part of the code opens all the text with the name ISW-1.txt inside the PR logs folder
for x in pathh:
# Detect the line number in text file to know where the row begin
phrase = "Shelf Panel CPUID Power CPU(5s) CPU(1m) CPU(5m) Peak PhyMem FreeMem Mem"
file = open("{0}".format(x) + "\\ISW-1.txt")
for number, line in enumerate(file):
if phrase in line:
sh_pro = number
break
file.close()
#Convert the text file to CSV from the row determined earlier
with open("{0}".format(x) + '\\ISW-1.txt', 'r') as rf:
r = csv.reader(rf, skipinitialspace=True, delimiter=' ')
rows = list(r)
heada = rows[sh_pro]
heada.insert(0, " ")
print(heada)
#to mark the last row
skipprocessor = sh_pro + 4
for i in range(7):
if i == 0:
print(rows[skipprocessor + i])
if i == 2:
sub_heada = rows[skipprocessor + i]
sub_heada.insert(0, " ")
sub_heada.insert(1, " ")
sub_heada.insert(2, " ")
print(rows[skipprocessor + i])
if i == 4:
sub_heada = rows[skipprocessor + i]
sub_heada.insert(0, " ")
sub_heada.insert(1, " ")
sub_heada.insert(2, " ")
print(rows[skipprocessor + i])
if i == 6:
sub_heada = rows[skipprocessor + i]
sub_heada.insert(0, " ")
sub_heada.insert(1, " ")
sub_heada.insert(2, " ")
print(rows[skipprocessor + i])
Previously it worked and it printed the output successfully. However while I was experimenting with exporting the output to an excel table, suddenly there was an error saying:
Traceback (most recent call last):
File "C:\Users\Taffy R. Mantang\PycharmProjects\pythonProject\main.py", line 26, in
heada = rows[sh_pro]
NameError: name 'sh_pro' is not defined
I traced back and undo everything but it still gives the same error.
I tried to remove an indent on line 26, it managed to print(heada). but messed up the if else code down below it and not print out the rest below.
What exactly is the problem? Help :'''((
sh_pro is not defined because you are not hitting the condition if phrase in line:, I would suggest:
for number, line in enumerate(file):
if phrase in line:
sh_pro = number
break
file.close()
#Convert the text file to CSV from the row determined earlier
with open("{0}".format(x) + '\\ISW-1.txt', 'r') as rf:
r = csv.reader(rf, skipinitialspace=True, delimiter=' ')
rows = list(r)
try:
heada = rows[sh_pro]
except NameError:
# error handling
In order to declare sh_pro, the condition if phrase in line: in your for cycle should return True. So if your condition returns False then your interpreter never meets such name as sh_pro. You can try to modify your code in a way that sh_pro is declared before you want to start working with it.
for number, line in enumerate(file):
if phrase in line:
sh_pro = number
break
file.close()

python IndexError list index out of range + how to break a while then also restart the while statement

Please Swipe Your Card: chend151
Traceback (most recent call last):
File "C:\attendance\Attendance 3.py", line 42, in <module>
clcode = dataList[period][d]
IndexError: list index out of range
I get this error when running my code, I can't seem to find what the problem is :/
My Code:
import csv
import datetime
import os
class_ = 'N004'
while (1):
#Day & Time Checker
format = "%H%M%S"
format_ = "%H%M"
today = datetime.datetime.today()
s = today.strftime(format) #Time in 24hour
s2 = today.strftime(format_)
d = datetime.datetime.today().weekday() #Day of week (0-5)
period = -1 #If they scan it outside of the dedicated periods it defaults to a unknown period`
#Period Checker
if "084500" < s < "094000":
period = 0
if "094000" < s < "104000":
period = 1
if "112000" < s < "121500":
period = 2
if "121500" < s < "131500":
period = 3
if "133500" < s < "143000":
period = 4
#Magnetic Card Reader Output & Attendance (Default = 0)
attendance = '0'
eqid = str(input('Please Swipe Your Card: '))
#Class Code Reader
dataList = []
with open(class_+'.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
dataList.append(row)
csvfile.close()
#Class Code
clcode = dataList[period][d]
#CSV Writer
ofile = open('Attendance.csv', "a")
writer = csv.writer(ofile, delimiter=',')
writer.writerow([eqid, period+1, clcode, attendance])
ofile.close()
`#os.rename("J:/attendance/Attendance.csv", "J:/G_DRIVE/Attendance.csv")`
Sorry for the formatting still can't seem to understand how the formatting works for code :c
Also, extra question, in my while statement I want to have an if statement that
`if eqid == "N004":
class_ = "N004"
break
I know indentation is off but how would I break the loop then restart it? so I want if they enter N004 it breaks the loop sets class_ = 'N004' then restarts the while loop and if they don't enter N004 the loop would just continue like normal.
Thank you, hopefully this makes sense.
EDIT: I will try explain what I want, I think I do have more than one question, firstly Thank you for helping. What I want is too have one print statement that asks for the user to swipe their card or insert their username and in the same print statement is asks for them to type the current class they are in (eg N004') , whatever they type gets exported to a csv file, I have that all setup already, but when they type in a class so for example N004 I want the while loop to break so N004 doesnt get exported to a CSV file. I'm not the best at explaining what I want in 300 characters
eqid = str(input('Please Swipe Your Card: '))
if eqid == "N004":
class_ = "N004"
continue
else:
print ("Didn't work")

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'

How to define key in this code 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).

(Python) Why is this index out of range?

The following code is what I have written to read data from a website and store it in a list. The code works, but it also throws a list out of range error regardless. Can anybody explain what I'm doing wrong?
import urllib.request
data_url = "http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data"
aboveFifty = 0
belowFifty = 0
""" The variables for storage """
age = 0
worksFor = ""
college = ""
salary = ""
bools = True
try:
print("Retrieving the data... ")
local_file, headers = urllib.request.urlretrieve(data_url)
print("Data retrieved")
fh = open(local_file, "r")
print("Reading the file... ")
for row in fh:
table = [row.strip().split(" ")]
salary = table[0][14]
if bools == True:
print("Table: ", table)
bools = False
if salary == "<=50K":
belowFifty += 1
elif salary == ">50K":
aboveFifty += 1
except IOError as e:
print("IO Error: ", e)
except IndexError as ie:
print("Index error: ", ie)
print("Above fifty: ", aboveFifty, "Below fifty: ", belowFifty)
fh.close()
The traceback error I get is:
Traceback (most recent call last):
File "C:\Users\Killian\workspace\College\Assignment.py", line 25, in <module>
salary = table[0][14]
IndexError: string index out of range
Your data is corrupt. Specifically, there is a blank line at the end of your data file. You can work with the corrupt data like so:
for row in fh:
table = [row.strip().split(" ")]
if not table:
continue # <-- ignore blank lines
salary = table[0][14]

Categories