我的第一阶段计算机科学论文就是这么写的。下面的代码是我写的。第16行(while语句)出现语法错误。书中要求我们
1)提示用户输入猜测并将值存储在"guess"变量中,
2)如果猜测大于目标打印…
如果猜测低于目标……打印…
4)如果猜测与目标相同,打印…
不确定如何修复此问题。任何帮助都将不胜感激。代码如下:
#Author: Anuj Saluja
#Date: 17 October 2016
import random
goal = random.randint(1,100)
guess = 0
print ("The object of this game is to")
print ("guess a number between 1 and 100")
print()
inputguess = int(input("Please guess the number: ")
while (guess != goal):
if inputguess > goal
print ("Too high, try again.")
if inputguess < goal
print ("Too low, try again.")
if inputguess == goal:
break
if inputguess == goal:
print ("Well done!")
print ("See you later.")
代码只在while循环之前要求猜测一次。您需要通过再次请求输入来更新while循环中的guess变量。
我想你正在寻找这个。希望这能起作用。
import random
goal = random.randint(1,100)
guess = 0
print ("The object of this game is to")
print ("guess a number between 1 and 100")
inputguess = int(input("Please guess the number: "))
while True:
if inputguess > goal:
inputguess = int(input("Too high, try again: "))
elif inputguess < goal:
inputguess = int(input("Too low, try again: "))
elif inputguess == goal:
print ("Well done!")
print ("See you later.")
break
输入这一行:
inputguess = int(input("Please guess the number: ")
在while循环内。代码只要求用户输入一次,用户输入必须在循环中。
您详细阅读了堆栈跟踪吗?简单地浏览它们是很容易的,但是堆栈跟踪实际上可以提供很多非常有用的信息。例如,消息可能会抱怨它期待一个结束括号。线:
inputguess = int(input("Please guess the number: ")
应该是
inputguess = int(input("Please guess the number: "))
堆栈跟踪显示错误在第16行,因为解释器在那里发现了错误。通常情况下,有bug的代码会出现在给出的代码行之前的最后一行。
也正如其他人所说,为了更新变量,您需要将输入语句放入while循环中。
你还应该考虑用4个空格替换制表符,这样无论你在哪里阅读它都能一致地显示。通常文本编辑器或IDE会有选项卡设置,当你点击选项卡时,它会输入4个空格。在谷歌上快速搜索"{text editor}更改选项卡设置"通常会显示如何更改选项卡设置的结果,其中{text editor}是您正在使用的编辑器/IDE的名称。
您还应该考虑缩进if语句中的代码,因为它可以提高可读性
所以我有人帮助我的女孩,这对任何感兴趣的人来说都是完美的。谢谢大家的帮助。:)谢谢。
goal = random.randint(1,100)
guess = 0
print ("The object of this game is to")
print ("guess a number between 1 and 100")
print()
while guess != goal:
guess = int(input("Please guess the number: "))
if guess > goal:
print ("Too high, try again.")
if guess < goal:
print ("Too low, try again.")
if guess == goal:
break
if guess == goal:
print ("Well done!")
print ("See you later.")