首页 > 解决方案 > 希望游戏在 6 次试验后终止

问题描述

我试图在 6 次试验后退出游戏。然而,即使经过 6 次试验,游戏仍在继续。

我已经申请了一段时间 count_trials <=6。count_trails 超过 6 之后应该会转到 else 部分,不是吗?但是,它超过了 6 并显示如下内容:“Great Prashant!你在 9 次猜测中猜对了这个数字”

from random import randint
#Asking the user a number
def ask_a_number():
    playernumber = int(input('Guess a number: '))
    return playernumber

#Comparing the numbers and giving hints to the player about the right number
def compare_2_nos(num1, num2):
    if (num1 < num2):
        if abs(num1 - num2) > 3:
            print('Your number is too low')
        else:
            print ('Your number is slightly low')
    if (num1 > num2):
        if abs(num1 - num2) > 3:
            print('Your number is too high')
        else:
            print ('Your number is slightly high')

#Running the Guess the number game
name = input('Enter your name: ')
print ('Hi {}! Guess a number between 1 and 100').format(name)
num1 = ask_a_number()
count_trials = 1
num2 = randint(1,100)
while count_trials <= 6:
    while num1 != num2:
        compare_2_nos(num1, num2)
        num1 = ask_a_number() 
        count_trials += 1
    else:
        print ("Great {}! you guessed the number right in {} guesses".format(name, count_trials))
        break
else: 
    print ("You have have exceeded the number of trials allowed for this game")

我希望游戏在 7 次或更多次试验后打印“您已超出此游戏允许的试验次数”

标签: pythonpython-3.x

解决方案


您遇到的第一个错误在第 22 行,您应该放在.format()字符串之后。

而且您正在创建一个“无限循环”,因为您不是每个循环都增加 count_trials 。像这样改变while循环

while count_trials <= 6:
    if num1 != num2:
        compare_2_nos(num1, num2)
        num1 = ask_a_number()
    else:
        print ("Great {}! you guessed the number right in {} guesses".format(name, count_trials))
        break
    count_trials += 1 

或使用range(1, 7)可迭代的 for 循环。


推荐阅读