我试着在6次试验后退出比赛。然而,即使经过6次试验,这场比赛仍在继续。
我申请了一段时间的count_trials <=6,它应该在count_trails超过6之后转到其他部分,不是吗?然而,它已经超过了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次或更多的试验后打印“你已经超过了这个游戏允许的试验次数”。
发布于 2018-12-31 03:16:14
您的程序永远不会从内部退出,而loop.Also,您是在循环starts.So之前要求一个数字,在6次试验中,您的检查条件应该是count_trials<6.Try --这是
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")发布于 2018-12-31 03:27:37
第一个bug出现在第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循环。
发布于 2018-12-31 03:24:24
而循环却以制造这类问题而臭名昭著。
我的建议是使用一个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所示
https://stackoverflow.com/questions/53983189
复制相似问题