I have some python code, the translate_string method returns the correct value nevmban
but then after it prints "None".
def secret_translate(letter):
code = ord(letter)-ord('a')
code = (code+13)%26
newCode = chr(code+ord('a'))
return newCode
def translate_string(string):
newMsg = ''
i = 0
while i < (len(string)):
print(secret_translate(string[i]),end='')
i= i+1
print(translate_string("arizona"))
The program prints:
nevmbanNone
I expect it to print nevmban
Where is the "None" coming from?
You are printing the result of your
translate_string
function, which isNone
, as there is no explicitreturn
statement.When you call the print method like this:
You are passing just one character in the function instead of the whole string. It will keep on checking the first character in your while loop:
The above
while
will run only once. And the next function call yourlen(secret)
will be 1.*Of course, ignore what I said if this is what you want.
Note that if you have the translation table, you really don't need to implement translation mechanisms. You have them built in
string
:You print the letters of the translated word as you go, I would recommend returning the translated word from the function instead. The fact that you see None printed behind your translated word is because inside the function you print the word, and outside the function you print the result of the function. The function has no result (no
return
statement) and the default is None. Printing this leads to the None being appended at the end of the string that was already printed inside the function.I would recommend a restructuring of
translate_string
like this:This solution uses a list comprehension to loop over the letters of the input string, no need for an explicit loop with a counter. List comprehensions are very nice, they do need some getting used to. In addition, the function now returns the string instead of printing it inside the function. The None is gone, and you can use the translated string further along in your program, e.g. as input to another function.