0

here is my code:

import time

ed = input('Encrypt (e) or decrypt (d)? ')

chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
charsLen = len(chars)

def numberToStr(num):
    s = ""
    while num:
        s = chars[num % charsLen] + s
        num //= charsLen

    return(s)
def strToNumber(numStr):
    num = 0
    for i, c in enumerate(reversed(numStr)):
        num += chars.index(c) * (charsLen ** i)

    return(num)

def enc():
    key = input('What is your key? (Alphanumeric and space) ')
    ID = int(input('What is your ID? (0-9, 3+ digits) '))
    inp = int(strToNumber(input('What do you want to encrypt? ')))
    keyAsNum = int(strToNumber(key))
    enc.asint = inp ** 2
    enc.asint = enc.asint * ID
    enc.asint = enc.asint - keyAsNum
    enc.astext = numberToStr(int(enc.asint))
    return(enc)


def dec():
    key = input('What is your key? (Alphanumeric and space) ')
    ID = int(input('What is your ID? (0-9, 3+ digits) '))
    inp = int(strToNumber(input('What do you want to decrypt? ')))
    keyAsNum = int(strToNumber(key))
    message = inp + keyAsNum
    message = message // ID
    message = math.sqrt(message)
    message = numberToStr(message)
    return(message)

if ed=='e':
    crypt = enc()
    print('crypt.asint:\n' + str(crypt.asint) + '\ncrypt.astext:\n' + crypt.astext)
elif ed=='d':
    crypt = dec()
    print(crypt)

time.sleep(10)

and here is the error: File "stdin", line 5, in module

File "stdin", line 9, in dec

File "stdin", line 4, in numberToStr

TypeError: string indices must be integers

I cannot figure out why it is throwing this error and cannot find anything on google.

1
  • Even if, for whatever reason, that question doesn’t appear at all, there are pages and pages of relevant information. Did you not find any of that information? Commented Mar 14, 2020 at 3:47

2 Answers 2

2

The traceback tells you exactly what is wrong. You are doing

s = chars[num % charsLen] + s

but you don't know for sure that num is an int because, previously, you do:

message = math.sqrt(message)
message = numberToStr(message)

What type does math.sqrt return?

Sign up to request clarification or add additional context in comments.

Comments

0

Well, I am a little bit confused by how you're using the square root function. When I run this:

from math import sqrt
type(sqrt(7)) #I want to recognize the type of what sqrt returns

it returns:

<class 'float'>

So that makes sense if you're trying to index your chars using a non-int value.

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.