Python: Printing the result of a function returns

2020-05-03 10:05发布

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?

4条回答
Luminary・发光体
2楼-- · 2020-05-03 10:35

You are printing the result of your translate_string function, which is None, as there is no explicit return statement.

查看更多
来,给爷笑一个
3楼-- · 2020-05-03 10:38

When you call the print method like this:

print(underground_code(secret[i]),end='')

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:

while i < (len(secret)):

The above while will run only once. And the next function call your len(secret) will be 1.

*Of course, ignore what I said if this is what you want.

查看更多
ら.Afraid
4楼-- · 2020-05-03 10:40

Note that if you have the translation table, you really don't need to implement translation mechanisms. You have them built in string:

import string

fromlist="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
tolist = "cdefghijklmnopqrstuvwxyzab"
transtable = string.maketrans(fromlist, tolist)

mycypertext="FCJJM UMPJB"
print string.translate(mycyphertext, transtable) #will print hello world
查看更多
Ridiculous、
5楼-- · 2020-05-03 10:40

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:

def translate_string(string):
  translated_letters = [secret_translate(letter) for letter in string]
  return("".join(translated_letters))

trans_string = translate_string("arizona")
print(trans_string)
'nevmban'

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.

查看更多
登录 后发表回答