使用 python 函数调整代码


#Passwordgen
#Generate a password
def main():
    #Ask the user to input a long string of words, separated by spaces
    sent = input("Enter a sentance separated by spaces: ")
    #Ask the user to input a position within each word
    #Take the position of that word
    pos = eval(input("Input a position within each word: "))
    words = sent.split(" ")
    wordy = ""                                   
    #loops through the word to take the position of the letter
    for word in words:
        wordy = wordy + word[pos] 
    #Prints out the letters as a password
    print("Your password is: ", wordy)  

main()

我的教授希望我打印出从该短语生成的密码,用于从零开始到用户输入的位置(包括用户输入的位置)。 它应该使用密码(短语,位置)函数来生成密码。

使用字符串格式打印每个密码输出行,如下所示。

例如:

Enter words, separated by spaces: correct horse battery staple
Up to position within each word: 3
Password 0: chbs
Password 1: ooat
Password 2: rrta
Password 3: rstp

到目前为止,代码做得很好,只需要进行一些调整:

#Passwordgen
#Generate a password
def main():
    #Ask the user to input a long string of words, separated by spaces
    sent = input("Enter a sentance separated by spaces: ")
    #Ask the user to input a position within each word
    #Take the position of that word
    pos = int(input("Input a position within each word: "))
    words = sent.split(" ")
    # set a counter variable to count each password generateed
    count = 0
    #loops through the word to take the position of the letter
    for p in range(pos+1):
        # reset wordy for each new password we are generating
        wordy = ""
        for word in words:
            wordy = wordy + word[p]
        #Prints out the letters as a password
        print("Your password {c} is: {pw}".format(c = count, pw = password))
        count += 1
main()

我们需要跟踪我们在每个单词中从哪个位置获取字母,这就是for p in range(pos+1)行所做的(我们pos+1将位置提高到3+1(或4),因为范围上升但不包括值。

另外,正如说明所述,我们需要 "Use string formatting to print each of the password output lines" ,因此参考这些 python3 格式示例,我们可以格式化每个密码的输出以及相关的计数。

希望这对你有帮助,干杯!

最新更新