首页 > 解决方案 > 即使我在运行代码后有一个结束条件,我的循环也会无休止地运行

问题描述

我正在为一个项目做一个小型的“策划”游戏,直到我最后一次循环之前似乎运行良好,我以为我有一个结束语句,但它似乎重复运行。我已经坚持了一段时间了,我将不胜感激任何和所有的帮助,谢谢!这是代码:

import random

def generate_code():
    """Create a random code as a list"""

    for i in range(0,4):
        i = random.randint(0,5)
        code.append(i)
    print(code)
 

def make_guess(): 
    """Let's the user input a guess"""

    while len(guess) < 4:
        element = input("your guess, one at the time: " ) 
        if element.isnumeric():
            element = int(element)
            global amountOfGuesses
            if element in range(0,6):
                guess.append(element)
                amountOfGuesses = amountOfGuesses +1
            else:
                print("number has to be between 0 and 5")
        else:
            print("has to be a number between 0 and 5") 

def right_position(guess, code):
    """Calculate how many correkt numbers on right position the guess have"""
    howManyRight = 0

    for i in range(4):
        if guess[i] == code[i]:
            howManyRight = howManyRight +1
    return howManyRight

def wrong_position(guess, code): 
    """Calculate how many numbers are corret but wrong position"""
    howManyWrongPosition = 0
    tempCode = code[:]
    for i in guess:
        if i in tempCode:
            tempCode.remove(i)
            howManyWrongPosition = howManyWrongPosition +1

    howManyWrongPosition = howManyWrongPosition - right_position(guess, code)
    return howManyWrongPosition

code = []
guess = []
wrongPosition = []
rightPosition = []
codeCopy = code.copy()
amountOfGuesses = 0

print("Welcome to Mastermind.\nYou get seven guesses to gues a random 4 digit code with 6 different numbers between 0 and 5.")
generate_code()
while amountOfGuesses <= 7:
    make_guess()
    print("you have", right_position(guess, code), "right numbers on the right position")
    print("you have", wrong_position(guess, code), "numbers on that is right but on the wrong posiotion")
    if guess[:] == code[:]:
        print("Congratulation you won!!! you used", amountOfGuesses, "guesses.")

标签: pythonloops

解决方案


据我了解,您希望尝试一次输入 4 个数字,所以我也解决了这个问题。你得到一个无限循环的原因是你最后没有跳出循环。您还应该清除guess 数组,否则make_guess() 中的for 循环将由于长度为4 而跳过(以防猜测错误并想重试)。

固定代码(假设一次尝试输入4个数字):

import random

def generate_code():
    """Create a random code as a list"""
    for i in range(0,4):
        i = random.randint(0,5)
        code.append(i)
    print(code)
 

def make_guess(): 
    """Let's the user input a guess"""
    global amountOfGuesses
    while len(guess) < 4:
        element = input("your guess, one at the time: " ) 
        if element.isnumeric():
            element = int(element)
            if element in range(0,6):
                guess.append(element)
            else:
                print("number has to be between 0 and 5")
        else:
            print("has to be a number between 0 and 5") 
    amountOfGuesses = amountOfGuesses +1

def right_position(guess, code):
    """Calculate how many correkt numbers on right position the guess have"""
    howManyRight = 0

    for i in range(4):
        if guess[i] == code[i]:
            howManyRight = howManyRight +1
    return howManyRight

def wrong_position(guess, code): 
    """Calculate how many numbers are corret but wrong position"""
    howManyWrongPosition = 0
    tempCode = code[:]
    for i in guess:
        if i in tempCode:
            tempCode.remove(i)
            howManyWrongPosition = howManyWrongPosition +1

    howManyWrongPosition = howManyWrongPosition - right_position(guess, code)
    return howManyWrongPosition

code = []
guess = []
wrongPosition = []
rightPosition = []
codeCopy = code.copy()
amountOfGuesses = 0

print("Welcome to Mastermind.\nYou get seven guesses to gues a random 4 digit code with 6 different numbers between 0 and 5.")
generate_code()
while 1:
    make_guess()
    print("you have", right_position(guess, code), "right numbers on the right position")
    print("you have", wrong_position(guess, code), "numbers on that is right but on the wrong posiotion")
    if guess == code:
        print("Congratulation you won!!! you used", amountOfGuesses, "guesses." if amountOfGuesses > 1 else "guess.")
        break
    elif amountOfGuesses > 7:
        print(f"You have lost by using {amountOfGuesses} tries!")
        break
    guess = []

推荐阅读