python - 希望游戏在 6 次尝试后终止

标签 python python-3.x

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

我申请了一段时间 count_trials <=6。应该是count_trails超过6之后就去else部分吧?但是,它超过 6 并显示如下内容: “伟大的 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 次或更多次尝试后打印“您已经超出了该游戏允许的尝试次数”

最佳答案

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

或使用 for 循环,将 range(1, 7) 作为可迭代对象。

关于python - 希望游戏在 6 次尝试后终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53983189/

相关文章:

Python 设置禁用路径长度限制的优点和缺点?

python - 检测 python 图中的峰值

Python 无法解析带有额外尾随逗号的 JSON

python ,同情 : How to output sympy expression as Python function?

python - 在 Python 中解压字节值

python-3.x - 如何将基于回调的低级代码与高级异步/等待代码桥接?

python - While循环: UnboundLocalError: local variable referenced before assignment

python - Pyinstaller 构建应用程序后设计变得丑陋

python - "Fire and forget"来自 Python 脚本的进程

python - __init__ 方法中的异常处理