[Python-ideas] python3: subtle change to new input()

Mark Summerfield mark at qtrac.eu
Wed Nov 14 09:07:16 CET 2007


Hi,

In Python 3, input() returns an empty string in two situations: blank
lines and EOF. Here's a little program that uses it:

    print("enter numbers one per line; blank line to quit")
    count = 0
    total = 0
    while True:
	line = input()
	if not line: # EOF or blank line
	    break
	n = int(line)
	total += n
	count += 1
    print("count =", count, "total =", total)

If input() returned None on EOF you could write this:

    print("enter numbers one per line; EOF (^D or ^Z) to quit")
    count = 0
    total = 0
    while True:
	line = input()
	if line is None: # EOF
	    break
	elif not line: # Blank line
	    continue
	n = int(line)
	total += n
	count += 1
    print("count =", count, "total =", total)

The advantage of this second approach is that you can accept blank
lines, which is often more convenient if using < on the command line to
read stdin. Furthermore, if you replaced input() with the None returning
one in the first example, it will work just the same as before. So I
think that returning None on EOF gives a subtle improvement without
breaking much.

-- 
Mark Summerfield, Qtrac Ltd., www.qtrac.eu




More information about the Python-ideas mailing list