local variable referenced before assignment for only some variables - python-3.x

I have tried to understand this by looking in previous threads but I still don't understand why I get this error for only one of two variables in the following piece of code (the code sucks I know):
alfaphet=('abcdefghijklmnopqrstuvxyz')
cryptalfaphet=('defghjiklmnopqrstuvxyzabc')
spaceNumber=[]
textCopy=[]
def crypt():
textCopy=[]
print('print the text that you want to encrypt:')
text=input()
for i in range(len(text)):
for j in range(len(alfaphet)):
if text[i]==alfaphet[j]:
textCopy.append(cryptalfaphet[j])
if text[i]==' ':
spaceNumber.append(i)
for i in range(len(spaceNumber)):
for j in range(len(text)):
if list(range(len(text)))[j]==int(spaceNumber[i]):
textCopy.insert(j, ' ')
textCopy=''.join(textCopy)
print(textCopy)
crypt()
This code works fine, but if I remove the
textCopy=[]
asignment from the beginning of the def-block, I get an error like this:
Traceback (most recent call last):
File "C:/Python33/dekrypt.py", line 26, in <module>
crypt()
File "C:/Python33/dekrypt.py", line 13, in crypt
textCopy.append(cryptalfaphet[j])
UnboundLocalError: local variable 'textCopy' referenced before assignment
My question is why this doesn't happen with the spaceNumber variable. spaceNumber is as far I can see also referenced before asignment with the
spaceNumber.append(i)
asignment? It is referenced before the def-block, but so was the textCopy vaiable right? What is the difference, they're both empty lists from the beginning and I use the .append() method on both, but Python seems to treat them differently!?

You can avoid this error by adding the following line at beginning of your function
def crypt():
global textCopy
...
however, this isn't a python best practice. See this post for further details.

Related

Pydub Split on silence error: UnboundLocalError: local variable 'start_ii' referenced before assignment

I try to get a python code running with the pydub library that should split an audio file on silent parts. The code is pretty short but still I get errors that I can't understand. Thanks a lot for your help:
Complete error message:
Traceback (most recent call last):
File "app.py", line 7, in <module>
chunks = split_on_silence(sound,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pydub/silence.py", line 134, in split_on_silence
chunks.append(audio_segment[max(start_min, start_ii - keep_silence):
UnboundLocalError: local variable 'start_ii' referenced before assignment
Code:
from os import path
from pydub import AudioSegment
from pydub.silence import split_on_silence
sound = AudioSegment.from_mp3("test5.mp3")
chunks = split_on_silence(sound,
# must be silent for at least half a second
min_silence_len=500,
# consider it silent if quieter than -16 dBFS
silence_thresh=-16
)
for i, chunk in enumerate(chunks):
chunk.export("chunk{0}.wav".format(i), format="wav")
You need to adjust your silence_thresh argument. You can start by assigning it the value you get when you call sound.dBFS, then adjust the value till it works or you.

List Addition in python

I am trying to create a function that will add two list such that if list1 is [9,1,2] and list2 is [8,5,3] then the two lists added together would produce a list yielding. ]1,7,6,5] since 912+853= 1765.
The following is the code I have written:
def list_addition(list1,list2):
otlist1=''
otlist2=''
for items1 in list1:
otlist1+= items1
for items2 in otlist2:
otlist2+= items2
strinum = int(otlist1)+ int(otlist2)
return strinum
print(list_addition(['3','6','7'], ['4','9','0']))
I keep getting this error:
Traceback (most recent call last):
File "C:/Users/Chuck/PycharmProjects/arrayaddition/Arrays.py", line 13, in <module>
list_addition(['3','6','7'], ['4','9','0'])
File "C:/Users/Chuck/PycharmProjects/arrayaddition/Arrays.py", line 10, in list_addition
strinum = int(otlist1)+ int(otlist2)
ValueError: invalid literal for int() with base 10: ''
I obviously know my code even if it did work as written wouldn't be complete as I would still need to put in the final codes to convert the integer variable 'strinum' back to a list, but I can't get there if my code is failing to properly add the two converted lists. When I break down the code and write the two for loops separately, convert them to integers and add them everything works perfectly fine. So the code below was good:
list1=['7','9','6']
otlist1=''
for items1 in list1:
otlist1+= items1
print(otlist1)
ist1=['5','7','0']
otlist2=''
for items1 in ist1:
otlist2+= items1
print(otlist2)
print(int(otlist1) + int(otlist2))
But for some reason when I try to put the two for loops inside a single function I get the error. I am a complete newbie to programming and I want to know what I am not understanding about function syntax. Any help will be greatly appreciated.

IndentationError within the timeit function

I want to measure a processing time of a part of my code and I used timeit function for the purpose. However it returns IndentationError from inside of the timeit function.
Here is my code;
for stem, result in zip(stem_dirs, result_dirs):
code_to_measure = '''
print(stem, '\n', result)
subprocess.call(['python', './a.py', "--dir_in", stem, "--dir_out", result])
'''
proccess_time = timeit.timeit(code_to_measure)
print(proccess_time)
Here is the error I get;
Traceback (most recent call last):
File "code_test.py", line 115, in <module>
proccess_time = timeit.timeit(code_to_measure)
File "/usr/local/lib/python3.6/timeit.py", line 233, in timeit
return Timer(stmt, setup, timer, globals).timeit(number)
File "/usr/local/lib/python3.6/timeit.py", line 123, in __init__
compile(stmtprefix + stmt, dummy_src_name, "exec")
File "<timeit-src>", line 3
print(stem, '
^
IndentationError: unexpected indent
However, the timeit function in the code below still runs properly;
# importing the required module
import timeit
# code snippet to be executed only once
mysetup = "from math import sqrt"
# code snippet whose execution time is to be measured
mycode = '''
def example():
mylist = []
for x in range(100):
mylist.append(sqrt(x))
'''
# timeit statement
print(timeit.timeit(setup = mysetup,
stmt = mycode,
number = 10000))
Here is the output of the code;
0.002189640999858966
I am not too sure how to solve the issue. Please advise me if you have any suggestion or solutions on this issue.
Thank you so much in advance.
Bit of a late reply but I ran into the same issue.
It is not possible to simply use triple-quoted strings with newlines in the timeit call. If you want multiple statements in your statement string you can separate them with a ;.
For your code it would look something like this:
for stem, result in zip(stem_dirs, result_dirs):
code_to_measure = f"print({stem}, '\n', {result});subprocess.call(['python', './a.py', '--dir_in', stem, '--dir_out', {result}])"
proccess_time = timeit.timeit(code_to_measure)
print(proccess_time)
(Also adding the variables via format string since timeit runs in an empty environment)
The reason why the timeit call below runs is because it does not actually execute the statements in the function. All it does is create the function, which also explains why it is so ridiculously fast.
The two ways to perform indentation is to either use whitespaces (standard norm is to use 4 whitespaces for one level indentaion), or to use tabs. Make sure you are not mixing them. Stick to one of it.
I might be able to help you more by telling exactly what is the problem if you can share your code with me as a .py file.

Python: When I try to run a code with (line +=) it gives a Typeerror

I am fairly new to python so mostly everything I've tried so far has failed.
Whenever I run this snip of my code to try to make a single string from a sequence,
with open('C:/Users/Arda Turan/Desktop/sequence.txt') as file:
lines = []
for line in file:
line+=(line.rstrip().split(","))
It gives the following error:
"C:\Users\Arda Turan\PycharmProjects\Untitled\venv\Scripts\python.exe"
"C:/Users/Arda Turan/.PyCharmCE2018.1/config/scratches/scratch_1.py"
Traceback (most recent call last):
File "C:/Users/Arda Turan/.PyCharmCE2018.1/config/scratches/scratch_1.py",
line 4, in <module>
line+=(line.rstrip().split(","))
TypeError: must be str, not list
Process finished with exit code 1
Any help would be appreciated.
I suppose, you meant:
for line in file:
lines.append(line.rstrip().split(","))
yes: your lines is an array, try with lines.append()
you're now using "lines" as if it is a string, while you have to use it as array, so use lines.append() instead of +=
if you want to do a "longer" string, change the declaration of lines with lines = '' and use the string catenation += so you'll have a longer string instead of an array of strings
You need to use list.append to append an element into the list. Try the following:
lines = []
with open('C:/Users/Arda Turan/Desktop/sequence.txt') as file:
for line in file:
lines.append(line.rstrip().split(","))

I don't understand the error traceback gives me

I'm currently trying to understand Pyth. I know Python quite well, but I don't get Pyth sometimes.
My code:
DhNKlNFzrKZaY#Nz;Y;hQ
It's just a basic script for reversing string, and traceback gives me ValueError,
ValueError: malformed node or string: <_ast.Name object at 0x7ff2fde45c18>
Despite my Python knowledge I have no idea what does this error mean. Can you show me where is this error coming from?
I assume you are getting an error like this one here:
Traceback (most recent call last):
File "pyth.py", line 771, in <module>
File "<string>", line 3, in <module>
File "/app/macros.py", line 691, in eval_input
File "/app/.heroku/python/lib/python3.4/ast.py", line 84, in literal_eval
File "/app/.heroku/python/lib/python3.4/ast.py", line 83, in _convert
ValueError: malformed node or string: <_ast.Name object at 0x7fac26eb2b70>
First off, you use z and Q inconsistently. With your current code, input should have been taken like this instead:
"abcd"
abcd
When Q is used in a Pyth program, z implicitly jumps to the next line of input, it just skips whatever has been inputted before using Q. Instead, just use:
DhNKlNFzrKZaY#Nz;Y;hz
And the errors should go away.
I am not sure why you would want to perform string reversal that way, though. I use _z if the input is not quoted and _ alone otherwise, since Q is implicit at the end of any Pyth program.

Resources