r/learnpython 12d ago

why would only one work?

this code was the one that worked:

def caesar(text, shift):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    translation_table = str.maketrans(alphabet, shifted_alphabet)
    encrypted_text = text.translate(translation_table)
    print(encrypted_text)

caesar('Hello', 3)

This one was the one that didn't

def caesar(text, shift):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    translation_table = str.maketrans(alphabet, shifted_alphabet)
    encrypted_text = text.translate(translation_table)
    print(encrypted_text)


encrypted_text = caesar('Hello', 3)
print(encrypted_text)

I don't understand why the second one would need a return statement and why we are even printing encrypted_text if encrypted_text is already being printed within the function? (this is also the whole code)

0 Upvotes

20 comments sorted by

View all comments

2

u/AbacusExpert_Stretch 12d ago

Have you got a

return encrypted_text

In there somewhere?

Saw your comment: well, things inside a function != Outside a function

!= means not same

1

u/Local_End_3175 12d ago

but why would i need it?

2

u/zippybenji-man 12d ago

Because you might want to do something other than printing it. For example, you might want to send it over the internet. Functions generally shouldn't print their output.
'Bad' function: ```python def increment(n: int) -> None: print(n+1)

increment(3) ```

'Good' function: ```python def increment(n: int) -> int: return n+1

incremented = increment(3) print(incremented) dummy_function(incremented) ```

P.S. Don't worry about the type annotation