Python Code Error 3.3.2 - python

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.

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.

Python 3 - IndexError: string index out of range

I'm currently creating a programming language in Python 3.6 and for some reason, the following code produces an IndexError: string index out of range.
When I try to execute the following code in a Windows Batch File:
#echo off
python run-file.py test.ros
pause
But I'm getting the following output:
Traceback (most recent call last):
File "run-file.py", line 16, in <module>
if not(value[1][0] == "!") and ignoreline == False:
IndexError: string index out of range
Press any key to continue . . .
The run-file.py file looks like this:
from sys import argv as args
from sys import exit as quit
import syntax
try:
args[1]
except IndexError:
print("ERROR: No ROS Code file provided in execution arguments")
print("Ensure the execution code looks something like this: python run-file.py test.ros")
with open(args[1]) as f:
ignoreline = False
content = f.readlines()
content = [x.strip() for x in content]
for value in enumerate(content):
if not(value[1][0] == "!") and ignoreline == False:
firstpart = value[1].split(".")[0]
lenoffirstpart = len(value[1].split(".")[0])
afterpart = str(value[1][lenoffirstpart + 1:])
apwithcomma = afterpart.replace(".", "', '")
preprint = str(firstpart + "(" + apwithcomma + ")")
printtext = preprint.replace("(", "('")
lastprinttext = printtext.replace(")", "')")
try:
exec(str("syntax." + lastprinttext))
except Exception as e:
template = "ERROR: An error of type {0} occured while running line {1} because {2}"
message = template.format(
type(e).__name__, str(value[0] + 1), str(e.args[0]))
print(message)
quit(1)
elif content[value[0]][0] == "!!!":
ignoreline = not(ignoreline)
quit(0)
The syntax.py file looks like this:
def print_message(contents=''):
print(contents)
The test.ros file looks like this:
! This is a single line comment
!!!
This line should be ignored
and this one as well
!!!
print_message.Hello World
The problem appears to be in line 16 of the run-file.py file:
if not(value[1][0] == "!") and ignoreline == False:
I've already tried replacing value[1][0] with (value[1])[0] and other combinations with brackets to no avail.
It seems like when I try to print the value it behaves as expected and gives me ! which is the first character of the test.ros file but for some reason, it throws an exception when it's in the if statement.
If you want any more of the source, it's on Github and you can find the exact commit containing all the files here
Update/Solution
Big thanks to Idanmel and Klaus D. for helping me resolve my issue. You can view the changes I've made here
This happens because the 2nd line in test.ros is empty.
You create content in this example to be:
['! This is a single line comment',
'',
'!!!',
'This line should be ignored',
'and this one as well',
'!!!',
'',
'print_message.Hello World']
When you try to access content[1][0], you get an IndexError because it's an empty string.
Try removing the empty lines from content by adding an if to the list comprehenssion:
content = [x.strip() for x in content if x.strip()]

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'

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

Categories