[Tutor] Translate word to number

Dave Angel davea at davea.name
Thu Oct 24 18:33:47 CEST 2013


On 24/10/2013 06:57, ivantham at raspberrypi wrote:

> Hi, I'm new to programming. I'm using python 3 and Debian Linux. My
> name is Ivan. I'm bad in for loops, I can't complete the following code:

Welcome to Python, and to the tutor newsgroup.  This is the right place
to ask this sort of question.  And thanks for using text email instead
of html.

There are a whole bunch of methods of the str type.  You can see them in
the interactive interpreter by typing  help(str)

>
>> input_word = input("Word to translate -->  ")

First thing is to make sure the word is both alphabetic and lowercase:

if input_word.isalpha() and input_word.islower():
    xxxx
else;
     yyyy


>
> How to change this to for loops?
>> a, b, c, d, e, f, g, h = 1, 2, 3, 4, 5, 6, 7, 8                                
>> i, j, k, l, m, n, o, p = 9, 10, 11, 12, 13, 14, 15, 16                         
>> q, r, s, t, u, v, w, x, y, z = 17, 18, 19, 20, 21, 22, 23, 24, 25, 26

Not sure what those equal signs are supposed to represent.  But if you
want to convert "a" to 1, and "b" to 2, etc., look at the ord()
function.

print(ord("c"))

will print a 99.  See if you adjust that to be 3 instead.

>
> How to change the word to number in for loops?
>> for words in input_word:

If you loop through a string, you get characters, not words.  That's
probably what you want, but you'd be better off using a better-named
variable.

Hint.  At any time you're not sure what a function returns, you can test
it in the interpreter.  So try:

>>> for x in "abcd":
...     print(type(x))
...     print(x)

Once you have a letter, you can use the expression you figured out above
to convert it to a number.


>>     words[0] = number[1]      # The loops before in a to z
>>     word += 1                 # Change the word from a to z
>>     number += 1               # And the number to so that 1 = a, 2 = b
>>                               # Then, add the numbers together

None of those make any sense to me.  I'd just build a list of numbers,
and then use the sum() function on it.  Assign the result to the new
variable 'number'.

>
> How to take the output to a .txt file with new line for each word with
> numbers in this format?
>   eg. abc = 6
>   eg. good = 41


>> delimeter = " = "  # for joining the input word and number
>> together
>> line = input_word + delimeter + number  # save as this format

You'll need  str(number), so you get the number into printable form.

>
> Thanks, sorry for my English as English is not the main language that I
> speak.
>

-- 
DaveA




More information about the Tutor mailing list