开发者

Strange error in python 3.2

The following code is to find the开发者_开发技巧 mean of a given input set of numbers.

#!/usr/bin/env python3
print("Enter some integers")
count = 0
total = 0
while True:
    line = input("integer: ")
    if (line):
        try:
            number = int(line)
        except ValueError as err:
            print(err)
            continue
        total += number
        count += 1
        #print("Post",line)
    else:
        break
if count:
    print('Count is ',count ,'Total is ',total,'Mean is ',total/count)

However, whenever I run the program, the even numbered input gives me an error even though I enter a number. The following is the sample output.

Enter some integers
integer: 4
integer: 5
invalid literal for int() with base 10: 'integer: 5'
integer: 5
integer: 6
invalid literal for int() with base 10: 'integer: 6'
integer:
Count is  2 Total is  9 Mean is  4.5

However, this code works fine if I uncomment the line before the else: statement. Can anyone tell me what is going on here?

Thanks in advance.


Your problem is a question of cut and paste.

The line

number = int(line)

Generates the error

invalid literal for int() with base 10: 'integer: 6'

This means that the line

line = input("integer: ")

Must have recieved the input:

'integer: 6'

And the only way it could have recieved this, is if that is what you inputted. Obviously, you would not be so daft as to type in "integer: 6". Hence the only reason this happens is that you have cut and pasted your previous input without noticing that you got to much when you copied, which is something that happens to me all the time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜