简单的Python 3.2.2程序中的语法错误

0 python syntax

这段代码是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)
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时,我收到一个错误:

  File "./intproj.py", line 18
    else:
       ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

我在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)
Run Code Online (Sandbox Code Playgroud)

现在得到错误:

  File "./intproj.py", line 18
    else:
       ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

固定代码:

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)
Run Code Online (Sandbox Code Playgroud)

谢谢!

Fre*_*ihl 6

第9行似乎错过了一个 )

更改:

line = input("integer: "
Run Code Online (Sandbox Code Playgroud)

line = input("integer: ")
Run Code Online (Sandbox Code Playgroud)

except行需要缩进以匹配try

和行:

total += number
count += 1
Run Code Online (Sandbox Code Playgroud)

需要缩进以及否则,ifelse语句不排队.即代码应该是这样的:

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)
Run Code Online (Sandbox Code Playgroud)