I’m trying to create a secret coding program but am having trouble with for loops (I’ve never really understood them). Here is what I have to far, I’m trying to get the users input, the convert each word of the users text into the coded text, so if someone types in “hello”, it will become “vpyyl”. Can someone please help? Is this even possible?
This is what I have so far, it’s giving an error “list indices must be integers, not str”. I’m pretty sure the for loop is set up wrong as well.
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]
There’s only one item in
[text]: the whole string that was entered by the user. You probably wantfor i in text:which will setito each character of the string.Also, you’ve named a list
list(which means you’ve lost access to the built-in namelist). And lists are indexed by integers, while you’re trying to access the elements with a string. You probably want to use a dictionary for that, mapping each letter to its coded equivalent.A couple of other problems are that you don’t have any code to handle situations in which something other than a letter is entered (spaces, punctuation) and the letters are all lowercase. Finally, you’re using square brackets in your
printcall instead of parentheses, and you’re not suppressing line breaks.So:
As others have noted, there are some things built into Python that can make this trivial, but if you’re having trouble with
forloops, that won’t help you learn. 🙂