希望游戏在6次试用后终止

时间:2018-12-31 03:04:28

标签: python python-3.x

经过6次尝试,我正试图退出游戏。但是,即使经过6次试用,游戏仍在继续。

我应用了一会儿count_trials <= 6。在count_trails超过6之后,它应该转到else部分,不是吗?但是,它超出了6,并显示如下内容: “太棒了!您在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次或更多测试后会打印“您已经超出了此游戏允许的试用次数”

3 个答案:

答案 0 :(得分:2)

您遇到的第一个错误是在第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循环。

答案 1 :(得分:1)

您的程序永远不会退出while循环内部。此外,您在循环开始之前要求输入一个数字。因此,对于6次尝试,您的检查条件应为count_trials<6。尝试一下

while count_trials < 6:
        count_trials += 1
        compare_2_nos(num1, num2)
        num1 = ask_a_number()
        if num1 == num2:
            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")

答案 2 :(得分:1)

while循环因产生此类问题而臭名昭著。

我的建议是使用一个for循环,该循环在所需的确切试验次数上进行迭代,并使用if条件测试是否成功:

for trial in range(1, 7):
    if num1 == num2:
        print ("Great {}! you guessed the number right in {} guesses".format(name, trial))
        break
    compare_2_nos(num1, num2)
    num1 = ask_a_number()
else:
    print ("You have have exceeded the number of trials allowed for this game")

这也意味着您不必保留要继续添加的“计数器”变量,如count_trials