我正在编写一个文本到二进制程序,但是当我执行它时它只打印一个二进制字母

时间:2017-03-25 15:33:27

标签: python binary

我正在使用python创建一个文本到二进制翻译器,我检查了一切,它似乎没有问题但是当我执行它时,程序只打印文本的第一个字母。这是代码:

if beep == 1:
letter = letter + 1
if letter > length:
    beep = 2
if list1[letter] == "a":
    print abinary   
elif list1[letter] == "b":
    print bbinary

elif list1[letter] == "c":
    print cbinary

elif list1[letter] == "d":
    print dbinary

elif list1[letter] == "e":
    print ebinary

elif list1[letter] == "f":
    print fbinary
elif list1[letter] == "g":
    print gbinary
elif list1[letter] == "h":
    print hbinary
elif list1[letter] == "i":
    print ibinary
elif list1[letter] == "j":
    print jbinary
elif list1[letter] == "k":
    print kbinary
elif list1[letter] == "l":
    print lbinary
elif list1[letter] == "m":
    print mbinary
elif list1[letter] == "n":
    print nbinary
elif list1[letter] == "o":
    print obinary
elif list1[letter] == "p":
    print pbinary
elif list1[letter] == "q":
    print qbinary
elif list1[letter] == "r":
    print rbinary
elif list1[letter] == "s":
    print sbinary
elif list1[letter] == "t":
    print tbinary
elif list1[letter] == "u":
    print ubinary
elif list1[letter] == "v":
    print vbinary
elif list1[letter] == "w":
    print wbinary
elif list1[letter] == "x":
    print xbinary
elif list1[letter] == "y":
    print ybinary
elif list1[letter] == "z":
    print zbinary
else:
    print "error."

任何人都知道发生了什么,我很清楚,但我无法在任何一本书中找到这一点。

2 个答案:

答案 0 :(得分:0)

如果您希望代码多次运行,则需要使用循环:

while beep == 1:
     if list1[letter] == "a":
         print abinary

     ...
     letter = letter + 1
     if letter >= length(list):
          beep = 2

使用for-loop来迭代列表中的所有字母,您甚至可以做得更漂亮:

for letter in list1:
    if letter == "a":
        print abinary
    ...

而不是链接很多精灵,你应该将字母的二进制表示存储在dictionary中:

binary_letters = {
    "a": "01100001",
    "b": "01100010",
    ...
    "z": "01111010"
    }

这将简化循环:

for letter in list1:
    print binary_letters[letter]

答案 1 :(得分:0)

你可以按如下方式实现它的for循环,甚至可以将字母转换为二进制字符串:

letter="k"
for n in range(97,123):
    if ord(letter)<97 or ord(letter)>123:
        #if character is not between 97-123 (a-z) print an error message
        print("Error:Not in range")
        break
    #print(n)
    if n==ord(letter):
        #print the binary string if character is between the codes 97-123 (a-z)  
        print(format(ord(letter),'b'))