需要帮助学校的项目,我在下面的代码行中出现缩进错误:
#First question
while numberofquestions <10:
operations = ['x', '-', '+']
operation = random.choice(operations)
number1 = random.randrange(0,10)
number2 = random.randrange(0,10)
if operation == '+':
answer = number1 + number2
elif operation == '-':
answer = number1 - number2
elif operation == 'x':
answer = number1 * number2
while True:
try:
user_answer = input("What is " + str(number1) + " " + operation + " " + str(number2) + "?")
user_answer = float(user_answer)
except ValueError:
print("Sorry that was an incorrect input, please try again.")
else:
break
if user_answer == answer:
print("Well Done! You got it correct!")
score = score+1
else:
print("Sorry you got that wrong")
print ("***********-*-*-*-Your score so far is-*-*-*-*********** ")
print (score)
numberofquestions = numberofquestions+1
print ("Well done, you have completed your test! Your final score was...")
print (score)
单个错误本身就在行中:
while True:
try:
我得到的错误是&#34; unindent与任何外部缩进级别都不匹配&#34;
这是一个包含我的整个代码的链接,有助于:http://paste.ubuntu.com/17167322/
答案 0 :(得分:2)
这些行:
while True:
try:
user_answer = input("What is " + str(number1) + " " + operation + " " + str(number2) + "?")
user_answer = float(user_answer)
except ValueError:
print("Sorry that was an incorrect input, please try again.")
else:
break
有错误的缩进。
两条user_answer
行有一个额外的缩进,而else
块没有匹配的if
或try/except
块。
答案 1 :(得分:2)
始终将编辑器设置为CONVERT TAB TO WHITESPACE 。
永远不会将标签保存为缩进,大多数处理缩进的解析器都不知道如何处理标签和空格的混合。对于处理缩进语法(python,yaml等)的所有新开发人员来说,这是最常见的问题
我通过将您的代码复制到Notepad ++,尽快发现问题,打开&#34;显示所有字符&#34;。从第67行到第74行,您使用空格作为缩进,而其余的则使用TAB。取决于编辑器,有些人将该功能称为&#34;用空格替换标签&#34;,&#34;将标签保存为空格&#34; ,&#34;将标签翻译为空格&#34;
while True:
try:
....
except ValueError:
print("Sorry that was an incorrect input, please try again.")
###### Here is indentation error culprit, mostly due to tab/space mix.
else:
break