这段代码是python上一本书的示例代码。这是一个输入整数并显示整数的总和,总数和平均值的简单程序。但是,当我尝试运行代码时,我在第18行收到语法错误,即冒号。这段代码对我来说非常好。有什么想法吗?
print("type integers, each followed by Enter; or just Enter to finish")
total = 0
count = 0
while True:
line = input("integer: "
if line:
try:
number = int(line)
except ValueError as err:
print(err)
continue
total += number
count += 1
else:
break
if count:
print("count=", count, "total =", total, "mean =", total / count)
当我尝试运行时,我收到错误:
File "./intproj.py", line 18
else:
^
SyntaxError: invalid syntax
我在Ubuntu 11.10上使用IDLE作为IDE使用python 3.2.2
更新代码:
print("type integers, each followed by Enter; or just Enter to finish")
total = 0
count = 0
while True:
line = input("integer: ")
if line:
try:
number = int(line)
except ValueError as err:
print(err)
continue
total += number
count += 1
else:
break
if count:
print("count=", count, "total =", total, "mean =", total / count)
现在得到错误:
File "./intproj.py", line 18
else:
^
SyntaxError: invalid syntax
固定代码:
print("type integers, each followed by Enter; or just Enter to finish")
total = 0
count = 0
while True:
line = input("integer: ")
if line:
try:
number = int(line)
except ValueError as err:
print(err)
continue
total += number
count += 1
else:
break
if count:
print("count=", count, "total =", total, "mean =", total / count)
谢谢!
答案 0 :(得分:6)
第9行似乎缺少)
变化:
line = input("integer: "
到
line = input("integer: ")
except
行需要缩进以匹配try
和行:
total += number
count += 1
也需要缩进,否则if
和else
语句不会排列。即代码应该是这样的:
print("type integers, each followed by Enter; or just Enter to finish")
total = 0
count = 0
while True:
line = input("integer: ")
if line:
try:
number = int(line)
except ValueError as err:
print(err)
continue
total += number
count += 1
else:
break
if count:
print("count=", count, "total =", total, "mean =", total / count)
答案 1 :(得分:1)
您忘记关闭上一行的input()
来电。
答案 2 :(得分:1)
你需要一个结束括号:
line = input("integer: ")
答案 3 :(得分:0)
除了右括号问题之外,显示except ValueError as err:
的行没有足够的缩进(其缩进级别应与try
语句的缩进级别匹配)。这应修复上面提到的第18行else
错误。
答案 4 :(得分:0)
以total +=
和count +=
开头的行需要以八个空格而不是四个空格开头。