Kris Kris - 2 months ago 9
Python Question

Detect the input number of signs in python and use it in a loop for encryption

I am writing a very easy encryption program. I just shift the ASCII order number of a sign with a key. My code looks as following:

#Type in sign or text and key
clear_text = input("Text? ")
key = int(input("Key? "))

# saves ASCII order number of the sign
ord_number = ord(clear_text)

#shift ASCII odernumber with the key -> encryption
shift_ord_number = ord_number + key
key_ord_number = chr(shift_ord_number)
print(key_ord_number)


I want to advance this code by being able to type in a whole sentence. For this I somehow must detect how many signs the user has typed in. How would that be possible? And what loops would you recommend?

Answer

You want to use a string for your sentence, from which you can extract individual characters to do your encryption on. In fact, clear_text is already a string, but (presumably) since you only entered a single character, it is only 1 character long.

To get the length of a string, you can use len(clear_text). You can also iterate over the characters of a string using

for char in clear_text:
    ord_number = ord(char)
    shift_ord_number = ord_number + key
    key_ord_number = chr(shift_ord_number)
    print(key_ord_number)