无法弄清楚循环

Hyz*_*lay 1 python for-loop python-3.x

我正在尝试创建一个秘密编码程序但是我遇到了for循环的问题(我从来没有真正理解它们).这是我所要做的,我正在尝试获取用户输入,将用户文本的每个单词转换为编码文本,因此如果有人输入"hello",它将变为"vpyyl".有人可以帮忙吗?这甚至可能吗?

这就是我到目前为止,它给出了一个错误"列表索引必须是整数,而不是str".我很确定for循环也设置错误.

import random

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
codedList = ['s', 'q', 'n', 'z', 'p', 'o', 'k', 'v', 'm', 'c', 'i', 'y', 'w', 'a', 'l', 't', 'd', 'r', 'j', 'b', 'f', 'e', 'h', 'u', 'x', 'g']

text = input("Enter your text: ")

for i in [text]:
    i = codedList[i]
    print[i]
Run Code Online (Sandbox Code Playgroud)

kin*_*all 7

只有一个项目[text]:用户输入的整个字符串.您可能想要for i in text:将其设置i为字符串的每个字符.

此外,您已命名一个列表list(这意味着您已失去对内置名称的访问权限list).并且列表由整数索引,而您尝试使用字符串访问元素.您可能希望使用字典,将每个字母映射到其编码的等效字母.

还有一些其他问题是你没有任何代码来处理输入字母以外的东西(空格,标点符号)并且字母都是小写的情况.最后,你在print调用中使用方括号而不是括号,并且你没有抑制换行符.

所以:

code = dict(a='s', b='q', c='n', d='z', e='p', f='o', g='k', h='v', i='m', j='c',
            k='i', l='y', m='w', n='a', o='l', p='t', q='d', r='r', s='j', t='b',
            u='f', v='e', w='h', x='u', y='x', z='g')

# another way to define the dictionary (you don't need both)
alphabet      = "abcdefghijklmnopqrstuvwxyz"
codedalphabet = "sqnzpokvmciywaltdrjbfehuxg"
code          = dict(zip(alphabet, codedalphabet))

# add upper-case versions of all letters to dictionary
for letter, codedletter in code.iteritems():
    code[letter.upper()] = codedletter.upper()

for char in input("Enter your text: "):
    if char in code:
        print(code[char], end="")
    else:
        print(char, end="")    # not an alphabetic character, print as-is
print()                        # we haven't printed a line break; do so now
Run Code Online (Sandbox Code Playgroud)

正如其他人已经注意到的那样,Python中内置了一些可以使这一点变得微不足道的东西,但是如果你遇到for循环问题,那将无助于你学习.:-)