Nested loop printing one letter

Question:

Ive been trying to make a code generator in python lately. Once you input a word, it’ll encode it. But when it prints the new code it only prints 1 random letter. Ive tried using just a while loop and just a for loop but nothing seems to work. The rest of the code works fine but I can’t figure out why it only prints one letter. Sorry if this code isnt the best possible way to about it. Im pretty new to this sort of stuff!

import random
letters_lower = ("a", "b", "c", "d", "e", "f")

def encode():
    new_code = ""
    user_code = input("What would you like to encode? ")
    for letters in user_code:
        while user_code > new_code:
            new_code + (random.choice(letters_lower))
    print(new_code)
Asked By: firfrelly

||

Answers:

Inside your encode() function, inside the while loop, you are not assigning the concatenation to any variable and the while loop therefore do nothing. You need to assign in to a new variable or updating it (i.e., new_code = new_code + ... or equivalently new_code += ... ) to be used later on when you return the output of your function.

import random
letters_lower = ("a", "b", "c", "d", "e", "f")

def encode():
    new_code = ""
    user_code = input("What would you like to encode? ")
    for letters in user_code:
        while user_code > new_code:
            new_code = new_code + (random.choice(letters_lower))
    print(new_code)

new_code = encode()
Answered By: Mohammad Tehrani
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.