每当您回答问题时,我该如何使问题不断重复?

我对python相当陌生,并且有一个随机密码生成器,用户可以在其中键入单词“ generate”(如果有更好的方法,请告诉我)“ generate”以获得一个新单词。它生成一个随机词,将其与一个随机数连接起来,然后再次生成一个随机词,然后将其打印出来。问题是我刚刚复制并粘贴了每次运行的代码,以便能够继续生成新密码。我可以使用什么命令来循环这个问题? 这是我的代码:

value = input("Type 'generate' to generate a new password.\n")
    if value == 'generate':
        line = open("words.txt").read()
        line = line[0:] 

        words = line.split() 
        one = random.choice(words)

        line = open("numbers.txt").read()
        line = line[0:]

        numbers = line.split()
        two = random.choice(numbers)

        line = open("words.txt").read()
        line = line[0:]

        words2 = line.split()
        three = random.choice(words2)
        print('Your new password is '+(one)+(two)+(three))
评论
  • BOX07
    BOX07 回复

    您可以使用while循环重复直到满足特定条件。

    value = input("Type 'generate' to generate a new password or 'quit' to quit.\n")
    while value != 'quit':
        if value == 'generate':
            line = open("words.txt").read()
            line = line[0:] 
    
            words = line.split() 
            one = random.choice(words)
    
            line = open("numbers.txt").read()
            line = line[0:]
    
            numbers = line.split()
            two = random.choice(numbers)
    
            line = open("words.txt").read()
            line = line[0:]
    
            words2 = line.split()
            three = random.choice(words2)
            print('Your new password is '+(one)+(two)+(three))
        else:
            print('Invalid input')
        value = input("Type 'generate' to generate a new password or 'quit' to quit.\n")
    
    

    该程序将一直重复直到用户输入quit,这将中断while循环。