制作更高或更低游戏以使用Python 3的问题。多个if语句

时间:2017-08-04 14:41:46

标签: python python-3.x

我遇到多个if语句的问题。我理解我的代码有什么问题我找不到解决方案。因此,当我运行程序时,“更高”的部分可以正常工作,但如果我认为“较低”则不会。解释器从阅读if语句到elif语句。那不是我想要的。如何在前往elif语句之前先检查if语句。我试过嵌套,但我似乎无法让它工作。 提前谢谢。

# Higher or lower card game

import random

x = random.randint(1, 14)

y = random.randint(1, 14)

print('The number is ', x, '.')

while True:

    print('higher or lower?')
    if input() in {'higher', 'h'} and y >= x:
        print('Good guess the number was ', y)
        x = y
        y = random.randint(1, 14)
    elif y < x:
        print('Bad guess , the number was ', y)
        break
    if input() in {'lower', 'l'} and y < x:
        print('Good guess, the number was ', y)
        x = y
        y = random.randint(1, 14)
    elif y >= x:
        print('Bad guess, the number was ', y)
        break
    continue

2 个答案:

答案 0 :(得分:0)

您可能需要以下内容:

while True:

   print('higher or lower?')
   ans_in = input()

   if ans_in in {'higher', 'h'}:

       if (y >= x):
          print('Good guess the number was ', y)
          x = y
          y = random.randint(1, 14)

       elif (y < x):
          print('Bad guess , the number was ', y)
          break

   elif ans_in in {'lower', 'l'}:

       if (y < x):
          print('Good guess, the number was ', y)
          x = y
          y = random.randint(1, 14)

       elif (y >= x):
          print('Bad guess, the number was ', y)
          break

   continue

请注意,由于break语句,&#34; Bad Guess&#34;将结束比赛。如果你想在获得&#34; Bad Guess&#34;之后继续,你可以简单地删除break语句。

答案 1 :(得分:0)

我猜不行,因为你在每个周期都得到两次输入。

你应该试试这个:

import random

x = random.randint(1, 14)

y = random.randint(1, 14)

print('The number is ', x, '.')

while True:

    print('higher or lower?')
    guess = input()
    if guess in {'higher', 'h'} and y >= x:
        print('Good guess the number was ', y)
        x = y
        y = random.randint(1, 14)
    elif guess in {'higher', 'h'} and y < x:
        print('Bad guess , the number was ', y)
        break
    elif guess in {'lower', 'l'} and y < x:
        print('Good guess, the number was ', y)
        x = y
        y = random.randint(1, 14)
    elif guess in {'lower', 'l'} and y >= x:
        print('Bad guess, the number was ', y)
        break
    else:
        print('Invalid command')
        break
    continue

所以基本上每次迭代你只需要输入一个命令,并根据你构建你的逻辑。