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.
Related
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 1 year ago.
Improve this question
I'm very new to coding and I am learning python alone and this is my code :
from random import *
temp =Randint( 0,70 )
print(temp)
if : temp = 69
print("nice")
You made a few errors
randint is a function so it's first letter should be small case
The for loop syntax was wrong
And we use == for checking equality and = for assignment
You can try the following code below
from random import randint
temp = randint( 0,70 )
print(temp)
if temp == 69:
print("nice")
Your if statement isn't quite right. The colon needs to go at the end of the line, and in an if statement you need a double equals sign (==, which compares two elements) rather than a single equals sign (which assigns a variable). Additionally, you need to indent (put a tab before) lines that are part of a block. You can read more about Python if statements here. The fixed if statement should look like this:
if temp == 69:
print("nice")
Lastly, since Python names are case-sensitive, randint must be in all lowercase.
I hope this is helpful!
A quick thing to remember is that “==“ means two things are equal and “!=“ means if something is not equal.
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!
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 7 years ago.
Improve this question
Hi I've been trying to write a program in python 2.7 that takes a word as its input and outputs the number of letters in a word. At first it was working but something happened and now it keeps returning an error by the first line that is not part of the while loop.
This is a part of the code:
def number_of_letters(input):
nol = input.find(input[-1])
while input[nol:] != input[-1]:
nol = input.find(input[-1], input.find(input[-1] + 1)
nol = nol + 1
print nol
The python interpreter keeps returning a syntax error by whatever I try to put after the while block (in this case 'nol = nol + 1 ')
I've tried playing around with it but nothing worked. PLease help.
By the way if there are any modules that may help with this program that would be great but I'd also like to know why this one isn't working
You are missing a closing paren:
nol = input.find(input[-1], input.find(input[-1] + 1)) #<- add here
If you want to count the number of actual letters you can use str.isalpha:
return sum(ch.isalpha() for ch in inp)
If you don't care what characters are there just use len(inp).
Avoid input as a variable name as it shadows the python function.
Change this
nol = input.find(input[-1], input.find(input[-1] + 1)
to this
nol = input.find(input[-1], input.find(input[-1] + 1))
Notice that parenthesis in the end.
There is a built in function for getting the length of a string in python.
word = "test"
length = len(word)
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.
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 8 years ago.
Improve this question
In this code I ask the user which way they want the text file ordered however, when run the if statement will not work and when run without the if statement it does work. Why will it not work?
way = int(input('Which way would you like the data to be sorted, Alphabetical[1], Ascending[2] Descending[3] or Average[4]'))
classno = str(input('Which class would you like to sort? Please state the entire class name no spaces please with .txt on the end'))
if way=='1':# WORKS with classno but not with if statement
f = open(classno, "r")# omit empty lines and lines containing only whitespace
lines = [line for line in f if line.strip()]
f.close()
lines.sort()# now write the output file
f = open(classno, 'w')
f.writelines(lines) # Write a sequence of strings to a file
f.close()
The other codes which i have not displayed have the same problems and all work without the if statement They all use an if statement no elif ect. if that is any use.
way is an integer, and you're checking for a string, which leads 1 == '1', and that's false.
What you should do is write -
if way == 1:
or remove the int() cast that you're doing on the input, and then you have:
way = input("Message...")
if way == '1':
Change way == '1' to way == 1 so you are checking an int against an int.