Reputation: 9
This code is example code from a book on python. It is a simple program to enter integers and display the sum, total count, and average of the integers. However, when I try to run the code, I receive a syntax error at line 18, the colon. This code looks perfectly fine to me. Any ideas?
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)
When i try and run this, I get an error:
File "./intproj.py", line 18
else:
^
SyntaxError: invalid syntax
I am using IDLE as an IDE with python 3.2.2 on Ubuntu 11.10
updated code:
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)
and now get the error:
File "./intproj.py", line 18
else:
^
SyntaxError: invalid syntax
Fixed code:
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)
Thanks!
Upvotes: 0
Views: 4132
Reputation: 45662
line 9 seems to missing a )
change:
line = input("integer: "
into
line = input("integer: ")
The except
line need to be indented to match the try
and the lines:
total += number
count += 1
needs to be indented as well otherwise, the if
and the else
statements don't line up. I.e. code should be something like this:
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)
Upvotes: 6
Reputation: 49812
The lines starting with total +=
and count +=
need to start with eight spaces instead of four.
Upvotes: 0
Reputation: 73
In addition to the closing parenthesis issue, your line that says except ValueError as err:
is not indented enough (its indentation level should match that of the try
statement). That should fix the line 18 else
error you mentioned above.
Upvotes: 0
Reputation: 798676
You forgot to close your input()
call on the previous line.
Upvotes: 1