Python: Printing The Result Of A Function Returns "none"
Solution 1:
You are printing the result of your translate_string
function, which is None
, as there is no explicit return
statement.
Solution 2:
Note that if you have the translation table, you really don't need to implement translation mechanisms. You have them built in string
:
importstring
fromlist="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
tolist = "cdefghijklmnopqrstuvwxyzab"
transtable = string.maketrans(fromlist, tolist)
mycypertext="FCJJM UMPJB"printstring.translate(mycyphertext, transtable) #will print hello world
Solution 3:
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.
Solution 4:
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 instring]
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.
Post a Comment for "Python: Printing The Result Of A Function Returns "none""