0

There is an error in my code help me to correct it

This is the actual code

message=input("enter the message ") 
alphabet='abcdefghijklmnopqrstuvwxyz ' 
key=5 
encrypt='' 
for i in message:
   position=alphabet.find(i) 
   newposition=key+position 
   encrypt+=alphabet[newposition] 
   print(encrypt)

this is the error

IndexError: string index out of range
2
  • message=input("enter the message ") alphabet='abcdefghijklmnopqrstuvwxyz ' key=5 encrypt='' for i in message: position=alphabet.find(i) newposition=key+position encrypt+=alphabet[newposition] print(encrypt) Commented Sep 12, 2019 at 5:29
  • this is the code Commented Sep 12, 2019 at 5:29

3 Answers 3

1

The error occurs when you enter a w x, y, z or space. position has the value 26 when find has found a space. Now you add 5 to your position which result in 31 and your string alphabet has only a length of 27. So you have to rework the line

newposition=key+position

to get a valid number between 0 and 26. This can be done with modulo (or %) for example. You should convert the input string to lower case (or upper case and replacing your alphabet with upper case letter). Otherwise find doesn´t find any letter in your alphabet:

message="This is a test"
alphabet="abcdefghijklmnopqrstuvwxyz "
key=5
encrypt=""
for i in message.lower(): 
  position=alphabet.find(i)
  newposition=(key+position) % len(alphabet)
  encrypt+=alphabet[newposition]
  print(encrypt)

Which results in

Python 3.7.4 (default, Jul  9 2019, 00:06:43)
[GCC 6.3.0 20170516] on linux
y
ym
ymn
ymnx
ymnxf
ymnxfn
ymnxfnx
ymnxfnxf
ymnxfnxff
ymnxfnxfff
ymnxfnxfffy
ymnxfnxfffyj
ymnxfnxfffyjx
ymnxfnxfffyjxy
Sign up to request clarification or add additional context in comments.

5 Comments

you should switch 26 to len(alphabet), its 27 actually
@Kampi, the error will occur for w, x, y and z as well
@Sid yes I was updating my text just in this moment :).
another drawback to handle, uppercased letters: for i in message.lower():
I add it too. Thanks again.
0

Your problem happens when

newposition = key + position

is larger than the length of your alphabet.

You can remedy your problem using modular arithmetic

newposition = (key + position) % len(alphabet)

Comments

0

This will happen if you have w, x, y, z or a (blank) in your input. Their positions in the string are 22, 23, 24, 25 and 26. respectively.Last position in alphabet is 26. 22 + 5 = 27, which is out of range, thus the error. Same for x, y, z and , which will give 28, 29, 30 and 31 respectively.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.