1

I have some problem with my caesar code.

1) I don't know how to check if a character is a punctuation and print without sum.

2) print the char on the same line but when it's finished return a newline.

3) Iterate through the alphabet with big number return me a punctuation, how can I do to return just a character?

import sys
import string

def main(): 

    if len(sys.argv) != 2:
        print("Usage: caesar.py k")

    else:


        k = int(sys.argv[1])

        if k == 1 or k <= 26:

            text = input("plaintext: ");
            j = len(text)

            for i in range(j):
                #check if is a character
                if text[i].isalpha:
                    if text[i].islower():
                        print(chr(ord(text[i]) + k),end = "")
                    if text[i].isupper():
                        print(chr(ord(text[i]) + k),end = "")
                elif text[i].punctuation():
                    print(text[i])

        else:
            print("You have to introduce a number between 1 and 26")

main()
Seba
  • 617
  • 1
  • 8
  • 33

1 Answers1

1

Try this code:

import string


def encrypt_ceasar(s, shift):
    assert abs(shift) < 26, 'shift is between -25 and 25 (inclusive)'
    encrypted_s = ''
    for char in s:
        if char.isalpha():
            is_upper = char.isupper()
            char = char.lower()
            pos_alphabet = ord(char) - ord('a')
            new_pos = (pos_alphabet + shift) % 26
            encryted_char = chr(ord('a') + new_pos)
            if is_upper:
                encryted_char = encryted_char.upper()
            encrypted_s += encryted_char
        else:
            encrypted_s += char
    return encrypted_s


def decrypt_ceasar(s, shift):
    return encrypt_ceasar(s, -shift)


if __name__ == "__main__":
    s = 'AbC1$de#zy'
    encrypted_s = encrypt_ceasar(s, 3)
    print('s:', s)
    print('encrypted_s:', encrypted_s)
    print('again s:', decrypt_ceasar(encrypted_s, 3))

Output:

s: AbC1$de#zy
encrypted_s: DeF1$gh#cb
again s: AbC1$de#zy
glegoux
  • 3,505
  • 15
  • 32