2017-08-04 12 views
-2

我有多个if语句的问题。我明白我的代码有什么问题,但我找不到解决方案。所以当我运行该程序时,“较高”部分可以工作,但如果我猜“较低”部分则不能。解释者从阅读if语句到elif语句。那不是我想要的。如何在使用elif语句前先检查两个语句。我试过嵌套如果但我似乎无法得到它的工作。 在此先感谢。使更高或更低的游戏运行Python 3的问题。多个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 
+0

你想每次迭代只输入一次吗? –

+0

我是新来的平台,似乎我搞砸了缩进。我修好了 – EnCoder

+0

Coldspeed,我想让它在打印x的值后输入一个数字。如果可能,我希望if语句独立工作。所以如果我选择回答'lower',它应该读取第二个代码块并跳过第一个。但是elif声明造成了一个问题。 – EnCoder

回答

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语句的,一个“坏猜”将结束游戏。如果你想继续获得“糟糕的猜测”,你可以简单地删除break语句。

+0

多数民众赞成在更低的工作,当你错了,你输了 –

+0

从未玩过游戏,TBH :) – Cuber

+0

在英国,我们曾经有一个电视节目,这个游戏可能是主要的游戏,称为布鲁斯的播放你的卡右 –

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 

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

+0

这个效果很好。更简单,更可读。 – EnCoder