如果在结束时通过

时间:2018-04-26 09:26:11

标签: python python-3.x

import random
answer = random.randrange(1,100)
guess = 101
while int(guess) != 0 :
    guess = input('Enter a number between 1 and 100 or enter 0 to exit: ')
    guess = int(guess)
    if guess <  answer :
        print('Too low')
    elif guess > answer :
        print('Too high')
    else:
        print('Correct')
print('Game closed')

我必须制作一个随机数字猜谜游戏并关闭你输入的游戏0它应该打印游戏关闭,但它也打印if&lt;因为0总是低于猜测,我将如何得到它不包括if&lt;

2 个答案:

答案 0 :(得分:2)

您需要按照偏好顺序对您的条件进行排名。最高优先级是什么?您希望if guess == answer成为您的首要任务,因为如果是这样的话,则无需检查任何其他内容并且您的计划已完成。你的第二要务是什么?如果键入0,则游戏结束。

换句话说,从更具体的条件开始(不像guess > answer那样广泛。)

重构您的条件语句:

if guess == answer:
    print('Correct')
    break
elif guess == 0:
    print('Game closed')
elif guess > answer:
    print('Too high')
else:
    print('Too low')

您还需要将guess设置为0以摆脱循环(或者只是添加break,因为我已在此处完成)

答案 1 :(得分:1)

稍微重新制定代码:

import random


answer = random.randrange(1,100)

while True :
    guess = int(input('Enter a number between 1 and 100 or enter 0 to exit: '))

    if guess == 0:
        print('Game closed')
        break
    elif guess < answer :
        print('Too low')
    elif guess > answer :
        print('Too high')
    else:
        print('Correct!')
        break