Why does this code not work very well? [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
#This will import time, so that I can break between lines
import time
import random
import os
#This will open the file, and will allow me to print it out
words =open("Words.txt", "r+")
print(words.read())
#This sets the different words to variables
x = 0
y = 0
z = 0
grid = 0
for i in words:
list_of_words[x] = i.rstrip()
x = x +1
grid = [words[i:i + 3] for i in range(0, len(words), 3)]
for x,y,z in grid:
print(x,y,z)
#This will close the word file
words.close
I've got the first part to work, but when it comes up to the second part it says I have to have an int in it. This is the error message:
Traceback (most recent call last):
File "C:\Users\Jamie\Documents\Jamie\Homework\Computing\Coureswork\Computer Science Courseword real.py", line 18, in <module>
for x,y,z in grid:
TypeError: 'int' object is not iterable

The error you're getting is because grid is 0 (which you initialized it to), rather than becoming a list when you assign a list comprehension to that name in the first loop.
That loop never does anything because you've already consumed the words file with words.read() near the top of the program. Iterating over the file does nothing, since you're already at the end. In order to read the file again, you either need to close and reopen it, or use words.seek(0) to rewind your position in the file. Or better yet, don't read the whole thing into a string if you don't need to.
Note that even after you fix the issue with reading the file, you'll have other problems. For instance, you've never defined list_of_words, so that will cause an exception. You're also trying to slice the file in the list comprehension you're assigning to grid. That's not legal.

Related

python: csv.writer - commas between numbers in the output [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
i suspect that this is a simple answer, but i cannot figure out the answer. (I did give it due diligence)
i wrote a simple python program to identify prime numbers. the program is function, but i'm receiving strange results in the output. when i have it write a number with multiple digits, each number is comma separated; for example, 13 is added to the document as 1,3. I would like to have a comma after each full number (13,) and don't want commas within the number (1,3 or 1,301). eventually, i want to have each number on its own row (one of the issue that i ran into in my g1 program is that the row became too long around 50mill ;-)
Any thoughts?
#!/bin/python3
import time
import os
import csv
folderLocation = "c:/notNow/"
primeName = "primeNumbers.csv"
# notPrimeName = "noPrimeNumbers.csv"
primePath=folderLocation + primeName
# notPrimePath=folderLocation + notPrimeName
no=13
os.makedirs(folderLocation)
f = open(primePath, "w")
writer = csv.writer(f)
writer.writerow(str(no))
output: 1,3
writerow expects a sequence of items (e.g list). A string is just seen as a sequence of individual characters, try this instead:
writer.writerow([no])

variable assignment errors in python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am getting a variable assignment error and am obviously not understanding something but from my code I don't see why it is happening.
The code:
def something(filename):
with open("tmp/"+filename.stem+".txt", "r") as infile: # opening the tmp file for scraping the data
readfile = infile.readlines() #reads the infile lne by line and returns a list containing the lines
for i, line in enumerate(readfile[1:], 1): # looping over all the lines in the file from position 1 (so skipping 0) to avoid circular feedback
if 'Overview' in line:
start = i
continue
for i, line in enumerate(readfile[1:], 1):
if 'Identified secondary metabolite regions using strictness' in line:
end = i
marker = list(map(lambda s: s.strip('\n'), readfile[start + 1:end])) # stripping the '\n' off every element in the list. map executes a function for each element in a sequence
for i, line in enumerate(readfile[1:], 1): # looping over all the lines in the file from position 1 (so skipping 0) to avoid circular feedback
for location in marker:
The error:
UnboundLocalError: local variable 'marker' referenced before assignment
Should markernot always be assigned within the scope of the function due to the first forloop executing before the second one resulting in markerbeing set?
secondly this seems messy to use two for loops, how can I do this within one for loop?
The point is that marker is assigned in an "if" condition. What about if it's false ?
Try defining marker variable outside of the function. Then use it in the funtion.
refer -> Don't understand why UnboundLocalError occurs
marker is no set when the condition if 'Identified secondary metabolite regions using strictness' in line: is not satisfied. Set marker = [] at the begining.

inaccurately reading from file logic error 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
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]

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!

What does line_spoken do in the program [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Can someone please explain this program, I don't understand where role, line-spoken come from
>>> data = open('sketch.txt')
>>> for each_line in data: // stores each line from the sketch file in each_line
... (role, line_spoken) = each_line.split(':')
... print(role, end='')
... print(' said: ', end='')
... print(line_spoken, end='')
You are looking at a tuple assignment.
The right-hand side expression is expected to have resulted in a sequence of two elements, and these two elements are assigned to the two named targets on the left hand side.
In other words, .split(:) is expected to return two values, and those two values are assigned to the variables role and line_spoken. Most likely, the lines in the file contain text like hamlet:To be or not to be, that is the question\n.
If each_line.split(':') does not return two values, an exception will be raised instead.
role and line_spoken are variables, which are populated with strings read from the file sketch.txt. sketch.txt contains colon-separated pairs of words or phrases, and role and line_spoken get those words/phrases.
The split() function returns a "tuple", which is "unpacked" into your two variables.
(Note that the parentheses around (role, line_spoken) are unnecessary.)

Categories