while循环使用if语句python

时间:2015-05-28 12:44:52

标签: python loops while-loop

我正试图为我的一个班级创建一个猜谜游戏但是 “无效语法”错误不断出现。我的以下代码的任何解决方案都会 非常感谢!

import random
goal = random.randint(1,100)
guess = 0
print("\nThe object of this game is to\nguess a number"
      "between 1 and 100")
while guess != goal:
    guess = int(input("Please guess the number: ")
      if guess > goal:
        print("\nToo high, try again.")
      elif guess < goal:
        print("\nToo low, try again.")
      else:
        print("Well done!")
print("\nSee you later")

3 个答案:

答案 0 :(得分:1)

缺少此行的右括号:

guess = int(input("Please guess the number: ")

应该是

guess = int(input("Please guess the number: "))

另外,由于您在while语句后使用了4个空格,但是后续if语句有2个空格,因此缩进不一致

以下适用于我:

In [*]:

import random
goal = random.randint(1,100)
guess = 0
print("\nThe object of this game is to\nguess a number"
      "between 1 and 100")
while guess != goal:
    guess = int(input("Please guess the number: "))
    if guess > goal:
        print("\nToo high, try again.")
    elif guess < goal:
        print("\nToo low, try again.")
    else:
        print("Well done!")
print("\nSee you later")

The object of this game is to
guess a numberbetween 1 and 100
Please guess the number: 1

Too low, try again.

答案 1 :(得分:0)

你错过了这一行的括号:

guess = int(input("Please guess the number: ")

应该是:

guess = int(input("Please guess the number: "))

答案 2 :(得分:0)

Error is because of the non uniform indentation. You dont need to indent the if after the guess input. Also the missing bracket in the guess input