功能和循环调试

时间:2018-10-22 20:36:30

标签: python python-3.x

这是我编写的代码,它可以完美运行,并且该代码的功能也只有一部分,当涉及到我询问用户是否要再次尝试的部分时(如果他们选择否,那么它就可以了)停止,这是应该发生的。另一方面,如果他们说“是”,他们将收到另一个完全相同的提示:“您想重试吗? (y / n)'。您可以说100次,什么也不会发生,我的目标是让代码从头开始返回并调用该函数。我尝试过休息一下,如果用户说“ y”来尝试退出循环等,但是它没有用,我现在不知道…

此外,如您所见,我有正确的数字,可以进行比较以查看用户猜测的数字是否在生成的列表中,而我对此没有问题。现在有了正确的位置,我不确定该怎么做,目的是要检查两个列表中的数字和位置是否都是名称。

import random

play = True
turnsleft = 1

#this is a function that is in charge of generating a random password
def generatePassword():
    generatePassword = [] #create an empty list
    for i in range(1,6):
        generatePassword.append(random.randint(1,9))
    return generatePassword

'''this is a function that prompts the userfor their guess
the input will be comprimised of 5 different variables to store
the different numbers which will then all be added to the list of user number'''
def getUserGuess():
    getUserGuess = [] #create an empty list
    v1,v2,v3,v4,v5 = input("Please take a guess of the password by entering 5 numbers(comma between each): ").split(",")
    v1,v2,v3,v4,v5 = int(v1), int(v2), int(v3), int(v4), int(v5)
    for i in(v1,v2,v3,v4,v5):
        getUserGuess.append(i)
    return getUserGuess

#this function will compare the cpu generated password to the user inputed numbers list
def reportResult(generatePassword,getUserGuess):
    correctdigits = 0
    correctlocations = 0
    global turnsleft #use the play variable initiated outside the funtion
    global play #use the play variable initiated outside the funtion

    while play is True:
        if getUserGuess == generatePassword:
            print("Congradulations! You have guessed the right password.")
        elif turnsleft == 0:
            print("You will never guess my password! It was " +str(generatePassword()))
            playagain = input("Would you like to play again? (y/n) ")
            if playagain == 'n':
                play = False
        else:
            turnsleft-= 1
            for e in getUserGuess():
                if e in generatePassword():
                    correctdigits+= 1
            for e in getUserGuess():
                if e in generatePassword():
                    correctlocations+= 1
            print(str(turnsleft) +" guesses left.")
            print(str(correctdigits) +" of 5 correct digits.")
            print(str(correctlocations) +" of 5 correct locations.")
    return reportResult

while play is True:
    reportResult(generatePassword,getUserGuess)

1 个答案:

答案 0 :(得分:1)

我相信您只需在“ turnsleft”为0时将“ turnsleft”设置为大于0的某个值即可。

例如:

elif turnsleft == 0:
        print("You will never guess my password! It was " +str(generatePassword()))
        turnsleft = 2 #<-- Reset turns here!
        playagain = input("Would you like to play again? (y/n) ")
        if playagain == 'n':
            play = False

这将使您可以将转数设置为某个值来“开始新游戏”。但这也带来了新的问题。也许您应该编写一个resetGame()来编辑从头开始真正需要的所有变量。

相关问题