inaccurately reading from file logic error Python [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hi I have the following text file on which I am using a csv reader:
number,obstacle,location,message
1,gobacktostart,8,Sorry but you've landed on a dangerous number, back to the start for you!
2,movetosquare42,matrix[1][0],The meaning of life is 42 or so they say, and that's where you're headed
I wish to (at the end) retrieve the number 8 from the row that starts 1,gobacktostart,8....etc.
My code is:
def gobacktostart():
with open("obstacles.txt","r") as f:
idnumber="1"
fReader=csv.reader(f)
for row in fReader:
for field in row:
if field==idnumber:
print(row[3])
player1position==row[2]
print(player1position)
and the undesired output however, is:
>>>
Sorry but you've landed on a dangerous number
1
>>>
I do need to read the value into the variable player1position in order to pass it on to another function at a different part of the program.
Any thoughts on solving this logic error? Why is it printing "1", when row[2] refers to the 8. Also, Row[3] seems to execute properly in the previous line....

You are checking for equality not assignment in player position == row[2]

Related

I'm getting a string in my list which should be a list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm reading a csv file from my python code and expecting it to return a list of lists but I'm getting a list which contains a str. Can somebody tell me how I can convert it into a list thanks.
This is the code which is reading my csv file from my local directory.
with open('/home/developer/Desktop/csv/JE_csv/JP_Preisliste_GreenHome_Select_ab_29-10.2021.csv', encoding='utf-8-sig') as csv_data:
PriceListGetAG = list(csv.reader(csv_data, delimiter=';'))
for elem in range(0, len(GreenHomeSelect_PriceListGetAG), 1):
print(PriceListGetAG[elem])
This is what I'm getting.
["'14844', '26.10.2021', 'JP_C24_002', 'GreenHome Select', '01067'"]
This is what my expected output should be.
['14844', '26.10.2021', 'JP_C24_002', 'GreenHome Select', '01067']
I think your delimeter is comma. Change your parameter like this.
delimiter=','

Why is there a traceback and indexerror in my code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Currently I am learning Python from the book 'The Coders Apprentice' and I have stumbled upon an exercise which I have the feeling that I have nearly solved, but I get an error when I execute the program.
This is the exercise:
Write a program that takes a string and produces a new string that contains the exact characters that the first string contains, but in order of their ASCII-codes.
For instance, the string "Hello, world!" should be turned into " !,Hdellloorw". This is
relatively easy to do with list functions, which will be introduced in a future chapter, but for now try to do it with string manipulation functions alone.
I have added the code below and the error message as a picture.
from pcinput import getString
entString=getString("Enter your string here: ")
yourString=entString.strip()
def positioner(oldPosition):
newPosition=0
x=0
while x<len(yourString):
if ord(yourString[oldPosition])>ord(yourString[x]):
newPosition+=1
x+=1
return newPosition
i=0
y=0
newString=""
while y<len(yourString):
if positioner(i)==y:
newString+=yourString[i]
y+=1
elif positioner(i)<y:
newString+=yourString[i]
if i<len(yourString):
i+=1
else:
i=0
print(newString)
What have I done wrong? I am new to programming.
You are getting an index error because the line if positioner(i)==y: is being called with a value of i equal to the length of yourString. yourString[oldPosition] is then accessing an index which doesn't exist.
This is happening because the loop condition (y<len(yourString)) isn't doing any checking on the value of i, which is the one causing problems.
Some other quick comments:
You can use yourString = input("Enter your string here: ") to replace the first four lines, as I'm not sure what pcinput is - and couldn't find any packages of the same name.
Instead of using the while/x+=1 construct, you could instead use a for x in range(len(yourString)), which is a little neater.

Python variable does not contain any data [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm hoping this is a simple stupid problem. But we have an in-house program that is no longer working. The program is not able to pass the data which is supposed to be contained in a variable using var_name+="".
The variable seemingly contains nothing. when I try to print the contents of this variable to either a string or text doc, we get nothing. The variable in question here is "allData".
The contents of this variable need to be passed to our fax appliance.
def sendFax(destOrg, destFax, cliName, casenum, attachments, errEAddr, comment, destName):
creds=requests.auth.HTTPBasicAuth(user,password)
#OVERRIDE OUTBOUND FAX NUMBER FOR TESTING
destFax='716-631-9804'
print("faxes will be sent to "+destFax)
return
allData=''
allData+='<schedule_fax>\n'
allData+='<cover_page>\n'
allData+='<url>'+prepXMLString(coverPage)+'</url>\n'
allData+='<enabled>true</enabled>\n'
allData+='<subject>'+prepXMLString(cliName)+' - case # '+str(casenum)+'</subject>\n'
allData+='<comments>'+prepXMLString(comment)+'</comments>\n'
allData+='</cover_page>\n'
allData+='<sender>\n'
allData+='<name>'+prepXMLString(webAddr)+'</name>\n'
allData+='<organization>'+prepXMLString(ourOrg)+'</organization>\n'
allData+='<phone_number>'+prepXMLString(ourPhonenum)+'</phone_number>\n'
allData+='<fax_number>'+prepXMLString(ourFaxnum)+'</fax_number>\n'
allData+='<email_address>'+prepXMLString(errEAddr)+'</email_address>\n'
allData+='</sender>\n'
allData+='<recipient>\n'
allData+='<name>'+prepXMLString(destName)+'</name>\n'
allData+='<organization>'+prepXMLString(destOrg)+'</organization>\n'
allData+='<fax_number>'+destFax+'</fax_number>\n'
allData+='</recipient>\n'
That is all screwed up. You're returning on the line with the return keyword which is why nothing is being returned.
You should do all of the concatenation and then return.

How to return the average from a file in Python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This should return the average of all of the values in the file. This is what I have. I get an error, could anyone help me out? Thank you!
def averageValueOnFile(fileName):
with open('fileName.txt') as f:
sum=0
count=0
for line in f:
count+=1
sum+=float(line.split(":")[1])
average=sum/count
print (average)
IndexError: list index out of range
What do the contents of the file look like?
One or more of your lines in the file does not have a : or is simply blank after the colon
Would sum+=float(line.split(":")[0]) work instead?
Your error likely comes from the fact that one of the lines in the file is not formatted as you expect: the split method returns a list with less than two elements.

Code works fine when print statement is present, but throws error when I comment the print [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am having really strange error. I am using Python 2.7 on Linux Mint OS. Here is the code:
with open(edgeClusteringPath) as f:
for line in f:
clustId = str(currCluster)
spl = line.split(" ")
# print spl
for i in spl:
# print i
(first, second) = edgeNodes[int(float(i))]
nodeClusters.setdefault(first, set())
nodeClusters.setdefault(second, set())
nodeClusters[first].add(clustId)
nodeClusters[second].add(clustId)
# print i
currCluster += 1
edgeClusteringPath is a path to a space separated data and edgeNodes is a dictionary with key = edgeId and value = (firstNode, secondNode). The problem occurs in the second for loop. This code gives me error:
> line 34, in <module>
(first, second) = edgeNodes[int(float(i))]
KeyError: 0
But when I uncomment one (or both) of the print i statements, the execution works fine (without error). It is really strange, I do not see how the print statement could affect the remaining code. I could uncomment the print statement, but I do not actually need that printing, so I would rather get rid of that line.
Here is a sample of edgNodes:
87388: (3250, 6041), 87389: (3250, 6045), 87390: (3250, 6046)
It is a huge dictionary, so I extracted only 3 key-value pairs.
Thank you in advance!
Edit:
Now my code works. I had problem with the paths I have been using. I used wrong file to initialize edgeNodes dictionary and it caused the problems. However, I posted the question just to see if anybody had idea how adding one line changes the behavior of the code. I have been using Java for 3 years and never had similar issue. I am new to Python and do not know how it works internally, so I wished to know if anybody has idea about the effect on one line of the other code.
Thank you for your opinions and suggestions!

Categories