我怎样才能得到两个变量来保持高于和低于猜测的数量?

2024-03-28 23:33:48 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好 我正在创建一个游戏,在这个游戏中,计算机选择一个随机数1-10 然后用户猜测数字,直到他们猜对为止。 我遇到的问题是,当用户输入错误的答案时,应该更新变量high或low,但它只是继续循环,直到用户输入正确的答案。这将导致“高”和“低”始终为0。 有什么想法吗?我知道我的循环方式可能有问题? 任何朝正确方向的推动都将是伟大的

# module to generate the random number
import random
def randomNum():
    selection = random.randint(0,9)
    return selection

# get the users choices
def userGuess():
    correct = True
    while correct:
        try:
            userPick = int(input('Please enter a guess 1-10: '))
            if userPick < 1 or userPick >10:
                raise ValueError
        except ValueError:
            print('Please only enter a valid number 1 - 10')
            continue
        return userPick

# define main so we can play the game
def main():
    correctNum = randomNum()
    guess = userGuess()
    high = 0 
    low = 0
    if guess != correctNum:
            print('uhoh try again!')
            guess=userGuess()
    elif guess > correctNum:
            print('That guess is too high!')
            high = high + 1
    elif guess < correctNum:
            print('That guess is too low')
            low = low + 1
    else:
            print('You win!')
    # the outcome of the game:
    print('Guesses too high:', high)
    print('Guesses too low:',low)
    print('Thank you for playing!')
main()

3条回答
    # module to generate the random number
import random
def get1to10():
    selection = random.randint(1,10)
    return selection
# get the users choices
def userGuess():
    correct = True
    while correct:
        try:
            userPick = int(input('Please enter a guess 1-10: '))
            if userPick < 1 or userPick >10:
                raise ValueError
        except ValueError:
            print('Please only enter a valid number 1 - 10')
            continue
        return userPick
# define main so we can play the game
def main():
    correctNum = get1to10()
    guess = 0
    high = 0 
    low = 0
    # use a while loop to collect user input until their answer is right
    while guess != correctNum:
        guess = userGuess()
        # use if statements to evaluate if it is < or >
        if guess > correctNum:
            print('This is too high!')
            high = high + 1
            continue
        # use continue to keep going through the loop if these are true
        elif guess < correctNum:
            print('this is too low!')
            low = low + 1
            continue
        else:
            break
    

    # the outcome of the game:
    print('           ')
    print('Guesses too high:', high)
    print('Guesses too low:',low)
    print('The correct answer was:', '*',correctNum,'*', sep = '' )
    print('Thank you for playing!')
    print('          -')
main()

我发现这个解决方案可以很好地满足我的需要! 谢谢所有回复这篇文章的人

您可以尝试使用字典:

guesses = {'Higher': [],
           'Lower': [],
           'Correct': False,
           }  # A Dictionary variable


def add_guess(number, correct_number):
    if number > correct_number:
        guesses['Higher'].append(number)
    elif number < correct_number:
        guesses['Lower'].append(number)
    else:
        guesses['Correct'] = True

    return guesses


add_guess(number=5, correct_number=3)  # Higher
add_guess(10, 3)  # Higher
add_guess(2, 3)  # Lower
# Correct is False, and higher has the numbers (10, 5) while lower has the numbers (2)
print(guesses)
add_guess(3, 3)  # Correct should now be True

print(guesses)

当然,这不是全部代码,但应该为您指明正确的方向。在线python词典上有大量的资源

尝试修改main函数:

def main():
    correctNum = randomNum()
    guess = userGuess()
    high = low = 0 # nifty way to assign the same integer to multiple variables
    while guess != correctNum: # repeat until guess is correct
        if guess > correctNum:
            print('That guess is too high!')
            high = high + 1
        else:
            print('That guess is too low')
            low = low + 1
        print('Try again!')
        guess=userGuess()

    print('You win!')
    # the outcome of the game:
    print('Guesses too high:', high)
    print('Guesses too low:',low)
    print('Thank you for playing!')

另外,要小心使用random.randint(0,9):这将给出一个介于0-9之间的数字(包括0和9,但绝不是10)

您想做^{cd3>}

相关问题 更多 >