Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use "None" in list when i'm using .index() and object wight not exist in list

I want to write a function that encrypt text using caesar cipher. But I want to let non-letters characters to be the same.
I have list with alphabet and a "questions for user"

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']

direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower()
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))

This is function which should let non-letters to be in code non changed

def encrypt(text, shift):
    text_encrypted = []  # blank text

    for letter in text:  # check every letter
        indeksik = alphabet.index(letter)
        if indeksik == None:
            text_encrypted.append(letter)
        else:
            text_encrypted.append(alphabet[indeksik + shift])

But then I’m getting this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Tracebac k (most recent call last):
  File "C:\Users\mateu\PycharmProjects\Cipher\main.py", line 25, in <module>
    encrypt(text, shift)
  File "C:\Users\mateu\PycharmProjects\Cipher\main.py", line 16, in encrypt
    indeksik = alphabet.index(letter)
ValueError: ' ' is not in list

I know that ' ' is not in list. That’s the point – how I can still append to another list these spaces and other non-alphabetical characters?
(Yes, I know that in this moment it will crash when I will shift letter "beyond z" – but I will work with this later)

>Solution :

index() raises a ValueError exception if there is no such item. if the value is not in the list. You can do something like:

if letter in alphabet:
    # Found the letter
else:
    # Not found

The other possible solution is to handle the exception itself, but I’d probably go with the first one.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading