I am trying to make an encoding program for a cipher I made and I was unable to concatenate strings, here is my code:
charToBin = {
"a":1,
"b":10,
"c":11,
"d":100,
"e":101,
"f":110,
"g":111,
"h":1000
}
binToWrd = {
1:"Intel",
10:"Info",
11:"Indipendent",
101:"Imposibble",
100:"Info-stolen",
110:"Indian-Ogres",
111:"Initially",
1000:"Infant-Orphan-Ogre-Ogle"
}
endTxt = " "
cipher = " "
def txtToBin():
txt = input(":")
txtArray = txt.split(" ")
for x in range(len(txt)):
endTxt = str(charToBin[txtArray[x]]) " "
print(endTxt)
def binToCip():
codeTxtArr = endTxt.split(" ")
for x1 in codeTxtArr:
for x2 in binToWrd:
cipher = x1.replace(str(x2), binToWrd[x2])
print(cipher)
txtToBin()
binToCip()
It returned this error:
Traceback (most recent call last):
File "main.py", line 40, in <module>
txtToBin()
File "main.py", line 30, in txtToBin
endTxt = endTxt str(charToBin[txtArray[x]]) " "
UnboundLocalError: local variable 'endTxt' referenced before assignment
Can anyone explain why this is happening and how to fix it?
CodePudding user response:
You need to move the initialization of endTxt
inside txtToBin()
:
def txtToBin():
endTxt = " "
txt = input(":")
txtArray = txt.split(" ")
for x in range(len(txt)):
endTxt = str(charToBin[txtArray[x]]) " "
print(endTxt)
CodePudding user response:
Alternatively you could still initialize endTxt
outside just declare it as a global in your function (whether that's good practice is a separate question)
endTxt = " "
def txtToBin():
global endTxt # this could cause you troubles later on
txt = input(":")
txtArray = txt.split(" ")
for x in range(len(txt)):
endTxt = str(charToBin[txtArray[x]]) " "
print(endTxt)
Also just a suggestion in your charToBin
dictionary you don't have to write it down for every letter just use the following code:
def char_to_bin(char):
if char.isalpha():
num = ord(char.lower()) - 96
return f"{num:8b}".strip()
else:
raise KeyError