简体   繁体   中英

How can I make printing a portion of a dictionary print the mathematical value?

When running this code and entering abcdefg... as the text and 1 as the key, I want it to output 12345..., as this is a basic encryption program. However it outputs 1 11 111 1111 etc. What is wrong and how can I fix this.

choice = input("Would you like to encrypt or decrypt? e/n")
text = input("Enter text:   ")
key = input("Enter key:   ")

################################

def encrypt(clear, key):
    Meow = {"a" : 1*key, "b" : 2*key, "c" : 3*key,"d" : 4*key,"e" : 5*key,"f" : 6*key,"g" : 7*key,"h" : 8*key,"i" : 9*key,"j" : 10*key,"k" : 11*key,"l" : 12*key,"m" : 13*key,"n" : 14*key,"o" : 15*key,"p" : 16*key,"q" : 17*key,"r" : 18*key,"s" : 19*key,"t" : 20*key,"u" : 21*key,"v" : 22*key,"w" : 23*key,"x" : 24*key,"y" : 25*key,"z" : 26*key}

    x = 0
    while(x<len(clear)):
         print(Meow[clear[x]])
         x = x + 1

################################

if choice == "e":
    encrypt(text, key)

elif choice == "n":
    print("finish")

else:
    print("Please enter either e or n")

Also, is there an easier way to do the dictionary?

Your key is a string (one character, but still a string). So in practice "1"*3 = "111" . To do what you expect, use key = int(input(...))

input() retun value is a string.

Python implements multiply operator for strings (and other sequences). It works when other side argument is a natural number. Multiplication by n is implemented as replicating whole sequence n times, for example:

assert "abc" * 3 == "abcabcabc"
assert "12" * 4 = "12121212"
assert [1, 2, 3] * 2 = [1, 2, 3, 1, 2, 3]  # it works for lists too!

To get number values you have to convert your string to integer.

s = "12"  # s = input()
i = int(s)
assert i == 12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM