while running this program I am getting the error “TypeError: ‘str’ object is not callable”. Any ideas?
JavaScript
x
18
18
1
def caesar_encrypt(text,num):
2
i = ""
3
4
for i in text:
5
if not i.isalpha():
6
i += i
7
elif i.isupper():
8
i += i(((ord(i) + num - 65) %26) + 65)
9
else:
10
i += i(((ord(i) + num - 97) %26) + 97)
11
return i
12
13
s=input("please enter the message: ")
14
step=int(input("now enter the step "))
15
16
encrypted_msg=caesar_encrypt(s, num)
17
print(encrypted_msg)
18
Advertisement
Answer
There are a couple of problems with the posted code. First, the call to caesar_encrpyt()
needs to look like caesar_encrypt(s, step)
. Secondly, you have two local variables in that function defined as i
; that one that’s being returned should be changed to a more descriptive name. Lastly, and what’s causing your error, is i += i(((ord(i) + num - 97) %26) + 97)
and i += i(((ord(i) + num - 65) %26) + 65)
. Here i
is a string and as the error suggests, is not callable; instead, this should be calling chr()
to convert that result back to a character.
This is what the fixed code should look like: `
JavaScript
1
18
18
1
def caesar_encrypt(text,num):
2
encoded_msg = ""
3
4
for i in text:
5
if not i.isalpha():
6
encoded_msg += i
7
elif i.isupper():
8
encoded_msg += chr(((ord(i) + num - 65) %26) + 65)
9
else:
10
encoded_msg += chr(((ord(i) + num - 97) %26) + 97)
11
return encoded_msg
12
13
s=input("please enter the message: ")
14
step=int(input("now enter the step "))
15
16
encrypted_msg=caesar_encrypt(s, step)
17
print(encrypted_msg)
18
`