带if语句的While循环

2024-09-28 05:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的一个类创建一个猜谜游戏,但是 “无效语法”错误不断出现。以下代码的任何解决方案 非常感谢!你知道吗

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")

Tags: 代码import游戏number错误语法random解决方案
3条回答

这行缺少括号:

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

应该是:

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

误差是由于压痕不均匀造成的。您不需要在猜测输入之后缩进if。 还有guess输入中缺少的括号

此行缺少右括号:

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.

相关问题 更多 >

    热门问题