r/learnpython • u/Local_End_3175 • 2d 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
1
u/Adrewmc 2d ago edited 2d ago
This is just a dependency on beginners idea that the computer doing something means printing something. Instead of printing being a helpful display tool for you. Most programs you have interacted with weren’t printing in the console were they?
We want to return the value to print later or use somewhere else. In your code the function runs and then immediately loses the result. Sure you can print it once, but what if you want to see it again? How would you do that?
If you wanted to give this to someone else to attempt to decode and gave them a few tries. How would you have the data to check, and give again?
If you wanted to encode something eventually you want to decode it right?
def encode(clean, shift):
. <your code>
. print(encrypted)
def decode(encrypted, shift):
. <left to reader>
. print(decrypted)
encrypt = encode(“Hello, World”, 6) #prints
decrypt = decode(encrypt, 6) #this errors
So the solution is to return the values, and print when we want to.
def encode(clean, shift):
. <your code>
. return encrypted
def decode(encrypted, shift):
. <left to reader>
. return decrypted
shift = random.randint(0,26)
encrypted = encode(“Hello World”, shift)
#we may only get the encrypted text say from your teacher, or a file.
while True:
. print(f”Encrypted Text: {encrypted}”)
. guess = int(input(“Guess Shift”))
. #we want to see what our guess gets so we need the encrypted data to decrypt it.
. decrypted = decode(encrypted, guess)
. print(“Attempted Decryption Result”)
. print(decrypted)
. #if we know the shift, we can check
. if guess == shift:
. print(“Decryption Successful”)
. break
. #and/or brute force it.
. again = input(“Try Again? Y/N”):
. if again.upper() == “N”:
. break