python - 希望游戏在 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 次或更多次试验后打印“您已超出此游戏允许的试验次数”
解决方案
您遇到的第一个错误在第 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 循环。
推荐阅读
- vue.js - 在 Heroku 上部署 Vue 应用程序构建时出现意外的语法错误
- angular - 使用 Karma 和 Jasmine NullInjectorError 进行 Angular 8 测试:R3InjectorError(DynamicTestModule)[api -> api]: NullInjectorError: No provider for api
- flutter - 根据 TextField 状态更改 TextField 背景颜色
- c# - 如何使用 asp.net core 3.1/5 mvc 在 razor 视图中使用 * (基于 [Required] 注释)自动标记必填字段标签?
- html - 单击元素时如何实现popover的相同位置
- javascript - Webpack 不处理 CSS 背景图片
- google-sheets - 带有查询索引的数组公式
- python-3.x - np.multiply.reduce 不会抛出 FloatingPointError 但单元素乘法会抛出
- vue.js - Vue(Nuxt)中的音频加载事件
- c# - 在 SwaggerUI 中隐藏/显示控制器(可配置)