如何简化这个?

时间:2017-11-07 19:59:16

标签: python python-3.x

我需要简化这个以获得占用更少空间的东西。任何帮助赞赏。这是一个我正在努力将一个句子变成“秘密代码”的项目。

a = translate[0] #gets a letter from the sentence entered
aa = values[a] #assigns a value (a=1,b=2,etc...) to the letter
print(aa+16) #adds 16 to the letter's value and prints it.


a = translate[1]
aa = values[a]
print(aa+16)

a = translate[2]
aa = values[a]
print(aa+16)


a = translate[3]
aa = values[a]
print(aa+16)

a = translate[4]
aa = values[a]
print(aa+16)

a = translate[5]
aa = values[a]
print(aa+16)

a = translate[6]
aa = values[a]
print(aa+16)

a = translate[7]
aa = values[a]
print(aa+16)

a = translate[8]
aa = values[a]
print(aa+16)

a = translate[9]
aa = values[a]
print(aa+16)

a = translate[10]
aa = values[a]
print(aa+16)

a = translate[11]
aa = values[a]
print(aa+16)

a = translate[12]
aa = values[a]
print(aa+16)

a = translate[13]
aa = values[a]
print(aa+16)

PS:如果有人能告诉我如何制作它以便输入单词的长度不需要设置(即现在代码仅在输入14个字母的单词时才有效)以及我如何可以为空格分配值(“”)我很感激。

2 个答案:

答案 0 :(得分:2)

你应该使用循环。

for x in range(14):
    a = translate[x]
    aa = values[a]
    print(aa+16)

这是计算机科学中一个非常基本的结构,我建议你在开展一个大项目之前,先发展一个更强的基本编程思想。尝试像codecademy这样的网站,您可能会发现您不再需要提出这样的简单问题。虽然记录在案:

word = input() #the word you read in
for x in range(len(word)): #this will allow you to read words of arbitrary length
    a = translate[x]
    aa = values[a]
    print(aa+16)

答案 1 :(得分:2)

示例代码段(使用ord检索字符的ascii值,ord('a')= 97,ord('A')= 65,依此类推):

translate = input("Enter some text: ")
output = ""
for char in translate:
  output += str(ord(char) + 16)

print(output)

执行输出:

Enter some text: This is a sample text.
1001201211314812113148113481311131251281241174813211713613262