gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:35:20 24 4
gpt4 key购买 nike

我想在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com