计数增加太多。输入打印太多次。蟒蛇

时间:2018-11-19 21:46:14

标签: python

def key(shift):
    data = []
    string = input("Please enter the string you wish to decode.\n")
    for i in string:
        if i.strip() and i in ALPHABET:
            data.append(ALPHABET[(ALPHABET.index(i) - shift) % 26])
        else:
            data.append(i)
    output = ''.join(data)
    return output

def run():

    data = []
    count = 0
    shift = 0
    for shift in range (26):
        count +=1
        if key(shift) == "hello world":
            print("Decoded.")
        else:
            print("Not this time!")
        print(count)
        print(key(shift))

当我运行程序时,它应该在计数3处执行“解码”,因为将khoor zruog解码到hello世界需要花费3个转变。此外,输入“请输入您希望解码的字符串”应该打印一次,而不要打印多次。

Please enter the string you wish to decode.
khoor zruog
Not this time!
1
Please enter the string you wish to decode.
khoor zruog
khoor zruog
Please enter the string you wish to decode.
khoor zruog
Not this time!
2
Please enter the string you wish to decode.
khoor zruog
jgnnq yqtnf
Please enter the string you wish to decode.
khoor zruog
Not this time!
3
Please enter the string you wish to decode.
khoor zruog
ifmmp xpsme
Please enter the string you wish to decode.
khoor zruog
Decoded.
4
Please enter the string you wish to decode.
khoor zruog
hello world
Please enter the string you wish to decode.

这是我尝试执行代码时发生的情况。我不知道为什么它递增为0,也不知道为什么它多次问我输入。有人可以帮我吗?

编辑:

def key(shift,string):
    data = []
    for i in string:
        if i.strip() and i in ALPHABET:
            data.append(ALPHABET[(ALPHABET.index(i) - shift) % 26])
        else:
            data.append(i)
    output = ''.join(data)
    return output

def run():
    data = []
    string = input("Please enter the string you wish to decode.\n")
    plaintext = input("Please enter plaintext word.\n")
    count = 0
    shift = 1
    for shift in range (26):
        count +=1
        if plaintext in key(shift,string):
            print(key(shift,string))
            print("The key is: ", count)
            print("Decoded.")
            break
        else:
            print(key(shift,string))
            print("Not this time!")
        print(count)

1 个答案:

答案 0 :(得分:0)

您的字符串

string = input("Please enter the string you wish to decode.\n")

位于在for循环内调用的函数内。这就是为什么您多次获得打印语句的原因!

删除该输入语句,您的已解码问题将得到解决。