Reputation: 55
Beginner question
Hi,
I'm struggling to figure out a way to encrypt this message. Ideally my program should work like this:
1. Ask for input of a word/message to encrypt. This could include letters and spaces.
2. Generate a number between 2 and 20 (i'll call it x for now)
3. Then randomly select characters of length x to put between each letter of the inputted message.
4. Print said encrypted message.
Issue is when I run the code it prints the same random letter and also does not remove any spaces. It also only uses the same length each time I run the code. Any suggestions on why this happens? Thank you.
import random
chars = 'abcdeifghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
def ranchar():
y = random.randrange(2, 20)
for x in range(2, y):
ok = random.choice(chars)
return ok
phrase = input('Please enter the message you would like to encrypt: ')
print(ranchar().join(phrase))
Output:
tQhQeQ QqQuQiQcQkQ QbQrQoQwQnQ QfQoQxQ QjQuQmQpQsQ QoQvQeQrQ QtQhQeQ QlQaQzQyQ QdQoQg
Process finished with exit code 0
Upvotes: 2
Views: 634
Reputation: 52008
The main problem with your code is that you are not accumulating the random characters into a string or list. Instead, you are continually overwriting the random choice so that only the choice in the last pass through the loop is retained. The easiest fix is to eliminate the loop completely and use random.choices
rather than random.choice
.
Here is one solution (incorporating Reti43's helpful suggestion to use string.ascii_letters
):
import random,string
chars = string.ascii_letters
def randstring():
y = random.randrange(2, 20)
return ''.join(random.choices(chars,k=y))
phrase = input('Please enter the message you would like to encrypt: ')
encrypted = randstring().join(phrase)
print(encrypted)
For example, one run of it with the phrase "hello world" produced
hlrTZhKdelrTZhKdllrTZhKdllrTZhKdolrTZhKd lrTZhKdwlrTZhKdolrTZhKdrlrTZhKdllrTZhKdd
Pedantic point: this isn't encryption at all so much as a simple form of steganography.
Upvotes: 3
Reputation: 36
Here is my solution:
import random
chars = 'abcdeifghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
def ranchar(phrase):
output = []
for v in phrase:
output.append(v)
output.append(random.choice(chars))
return output
phrase = input('Please enter the message you would like to encrypt: ')
print(''.join(ranchar(phrase)))
You only give the join() function one character, so it'll only combine the 'q' to the prase.
Here is my output:
Please enter the message you would like to encrypt: the quick brown fox jumps over the lazy dog
tZhLeb DqDuHiacqkC SbdrqoWwAnO BfpoWxi HjnuVmZpEsM DoDvmedrY KtihpeT GlkaFzlyV Zdpocgi
Upvotes: 1