Hyzenthlay
Hyzenthlay

Reputation: 483

Can't figure out for loops

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]

Upvotes: 1

Views: 245

Answers (6)

kindall
kindall

Reputation: 184201

There's only one item in [text]: the whole string that was entered by the user. You probably want for i in text: which will set i to each character of the string.

Also, you've named a list list (which means you've lost access to the built-in name list). 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 print call instead of parentheses, and you're not suppressing line breaks.

So:

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

As others have noted, there are some things built into Python that can make this trivial, but if you're having trouble with for loops, that won't help you learn. :-)

Upvotes: 7

Levon
Levon

Reputation: 143022

There a number of different ways to accomplish what you are trying to do. but focusing on what you have already started and your current code (with some identifiers changed for readability/clarity), then given:

clearList = ['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: ")

Your for-loop should look like this:

for letter in text:            # iterate over the text not [text]
   idx = clearList.index(letter)  # find the index for the given letter in clearList
   print(codedList[idx], end="")  # get the corresponding coded letter with the index

and results in vpyyl.

Note, it is not a good idea to have list as an identifier, Python already uses it for the name of the data structure. I also used a more descriptive identifier for your letter of your input.

--

Since you mentioned having problems with for-loops, here are two tutorials for you: From the Python Wiki and this one form tutorialspoint.

Upvotes: 2

georg
georg

Reputation: 214969

In Python, before you start programming anything, check if there's a built-in function that does the same. With probability 90% there is.

chars = ['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']
coded = ['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']

table = str.maketrans(chars, coded)
coded_text = text.translate(table)

print (coded_text)

Documentation: translate | maketrans

Upvotes: 4

avasal
avasal

Reputation: 14854

for i in [text]:

should be

for i in text:

and i in your case is a character of the string user input-ed..

it should be an integer to work as index

The code you intent should be like..

Note : I have used raw_input instead of input, since input would try to eval user input you will end up with and NameError error

In [214]: import random

In [215]: mylist = ['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']

In [216]: 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']

In [217]: text = raw_input("Enter your text: ")
Enter your text: hello

In [218]: str = []

In [219]: for i in text:
   .....:     j = mylist.index(i)
   .....:     str.append(codedList[j])
   .....:

In [220]: ''.join(str)
Out[220]: 'vpyyl'

And as for the for loop , text contains the word 'hello', the for loop here will iterate every character in the text i.e. first iteration will be over 'h', then 'e' and so on.

the name of the list should never be list, as this name is keyword in python

Upvotes: 2

Theon Lin
Theon Lin

Reputation: 330

I think you are trying to encode your string with another alphabet.

In your code,

for i in [text]:
    i = codedList[i]
    print[i]

You should find the index of the 'i' in original list through the .index(). A workable revision code as below.

for i in text:
    index = list.index(i)
    i = codedList[index]
    print [i]

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

Two problems:

  1. You are using i as both the iteration variable and to hold the encoded-value. This one is harmless, but bad practice.
  2. You are iterating over a single-element array contain text as its one element. Remove the [] around text:

    for i in text:
        print codedList[i]
    

Upvotes: 1

Related Questions