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

Time:11-26

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:

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)

CodePudding user response:

index() raises a ValueError exception 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.

CodePudding user response:

For

indeksik = alphabet.index(letter)

If letter is not found in alphabet, a ValueError exception is raised.

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

CodePudding user response:

If you use a string, preferably not typing (and possibly mistyping) it yourself, then you can use find and you'll get -1 instead of an error:

>>> from string import ascii_lowercase as alphabet
>>> alphabet.find('c')
2
>>> alphabet.find(' ')
-1
  • Related