尝试转换列表或删除列表编号周围的引号

该程序是数字猜测。它生成4个数字,并允许用户进行猜测。每次猜测之后,它将显示正确的数字数量以及它们所在的位置。运行它不会产生语法错误,但是即使所有数字正确,它也都表示没有错误。我相信这是因为数字变量没有引号,而猜测列表却没有。任何帮助表示赞赏,谢谢!

from random import randint

    number = [(randint(0,9)),(randint(0,9))]



    while True:
        guess_int = (int(input('Guess a 4 digit number: ')))
        guess_str = (str(guess_int))
        guess = (list(guess_str))

        numcorrect = 0

        if guess == number:
            print('Correct!')

        elif number[0] == guess[0]:
            numcorrect = numcorrect + 1
            print('You got the first number correct')
        elif number[1] == guess[1]:
            numcorrect = numcorrect + 1
            print('You got the second number correct')
        elif number[2] == guess[2]:
            numcorrect = numcorrect + 1
            print('You got the third number correct')
        elif number[3] == guess[3]:
            numcorrect = numcorrect + 1
            print('You got the forth number correct')

        if numcorrect != 0:
            print('You got',numcorrect,'numbers correct')

        if numcorrect == 0:
            print('You got no numbers correct')
steven35 回答:尝试转换列表或删除列表编号周围的引号

通过其他方式修复程序。

from random import randint

number = [(randint(0,9)),(randint(0,9))]

print(number)

while True:
    guess_list_str = list(input('Guess a 4 digit number: '))
    guess = [int(g) for g in guess_list_str] # This is how you get rid of the quotes

    numcorrect = 0

    if number[0] == guess[0]:
        numcorrect = numcorrect + 1
        print('You got the first number correct')
    if number[1] == guess[1]:
        numcorrect = numcorrect + 1
        print('You got the second number correct')
    if number[2] == guess[2]:
        numcorrect = numcorrect + 1
        print('You got the third number correct')
    if number[3] == guess[3]:
        numcorrect = numcorrect + 1
        print('You got the forth number correct')

    if numcorrect != 0:
        print('You got',numcorrect,'numbers correct')

    if numcorrect == 0:
        print('You got no numbers correct')

    if guess == number:
        print('Correct!')
        break  # Added code
,

您的number变量是整数列表,而guess是字符串列表,您必须先转换一个,我建议这样做:

guess_int = int(input('Guess a 4 digit number: '))
guess_str = str(guess_int)
guess = list(map(int,guess_str))

另一件事是,根据该问题背后的逻辑,您应该重新考虑使用elif,因为如果触发了第一个条件,则其他条件虽然有机会,但将被忽略。因此您应该使用if来在逻辑上正确。

第三个要点是,这应该以某种方式停止,或者至少在解决一个问题之后,应该刷新的数字应该刷新。如果收到正确答案,请尝试结束此操作或续订该号码。

本文链接:https://www.f2er.com/3169699.html

大家都在问