Skip to content
Advertisement

Getting TypeError: ‘str’ object is not callable in my script

while running this program I am getting the error “TypeError: ‘str’ object is not callable”. Any ideas?

def caesar_encrypt(text,num):
    i = ""

    for i in text:
        if not i.isalpha():
            i += i
        elif i.isupper():
            i += i(((ord(i) + num - 65) %26) + 65)
        else:
            i += i(((ord(i) + num - 97) %26) + 97)
    return i

s=input("please enter the message: ")
step=int(input("now enter the step "))

encrypted_msg=caesar_encrypt(s, num)
print(encrypted_msg)

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: `

def caesar_encrypt(text,num):
    encoded_msg = ""

    for i in text:
        if not i.isalpha():
            encoded_msg += i
        elif i.isupper():
            encoded_msg += chr(((ord(i) + num - 65) %26) + 65)
        else:
            encoded_msg += chr(((ord(i) + num - 97) %26) + 97)
    return encoded_msg

s=input("please enter the message: ")
step=int(input("now enter the step "))

encrypted_msg=caesar_encrypt(s, step)
print(encrypted_msg)

`

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement