Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

debugging - Python: How can i improve this code? and what's the bug?

This is a caesar cipher project (my 1st project) and it's really long ??

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def encrypt(txt, shift_n):
  encrypted_txt = ''
  indexes = []
  for char in txt:
    if char not in alphabet:
      indexes += char
    else: indexes.append(alphabet.index(char))
  print(indexes)
  
  for letter_index in indexes:
    if letter_index not in range(0, len(alphabet)):
      encrypted_txt += letter_index 
    else:
      if letter_index + shift_n > len(alphabet) - 1:
        print(f'letterIndex is {letter_index + shift_n}')
        #
        remainder =  len(alphabet) - letter_index
        print(f'Remainder is {remainder}')
        #
        encrypted_txt += alphabet[shift_n - letter_index - 2]
      else: encrypted_txt += alphabet[letter_index + shift_n]
    
  print(encrypted_txt)

def decrypt(txt, shift_n):
  decrypted_txt = ''
  indexes = []
  for char in txt:
    if char not in alphabet:
      indexes.append(char)
    else: indexes.append(alphabet.index(char))
  print(indexes)
  for letter_index in indexes:
    if letter_index not in range(0, len(alphabet)):
      decrypted_txt += letter_index
    else: decrypted_txt += alphabet[letter_index - shift_n]

  print(decrypted_txt)

while True:
  direction = input("Type 'e' to encrypt, type 'd' to decrypt: ")
  text = input("Type your message: ").lower()
  shift = int(input("Type the shift number: "))
  if shift > 26:
    shift %= 26
    print(f'shift: {shift}')

  if direction == 'e': 
    encrypt(text, shift)
  elif direction == 'd':
    decrypt(text, shift)

  is_done = input('Continue? (y/n): ')
  if is_done == 'n': break

test input:

Type 'e' to encrypt, type 'd' to decrypt: e
Type your message: zombie zebra codes
Type the shift number: 10

output:

jywlso jolrk mynoq

I've also encountered bugs and it's usually when i choose the decode option the letters get scrambled up. And if i decrypt it, it doesn't go as expected..

zombie zebha codeg

I'd really appreciate the help??

question from:https://stackoverflow.com/questions/65839330/python-how-can-i-improve-this-code-and-whats-the-bug

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...