简体   繁体   中英

How to skip blank line while taking input from user in python?

I want to skip blank line (no value entered by user). I get this error.

 Traceback (most recent call last):
  File "candy3.py", line 16, in <module>
    main()
  File "candy3.py", line 5, in main
    num=input()
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

My code is:

def main():
    tc=input()
    d=0
    while(tc!=0):
        num=input()
        i=0
        count=0
        for i in range (0, num):
            a=input()
            count=count+a
        if (count%num==0):
            print 'YES'
        else:
            print 'NO'
        tc=tc-1     
main()

Use raw_input, and convert manually. This is also more save. For a full explaination, see here . For example, you could use the code below to skip anything which is not an integer.

x = None
while not x:
try:
    x = int(raw_input())
except ValueError:
    print 'Invalid Number'

The behaviour you're getting is expected, read the input docs.

input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised

Try something like this and the code will be capturing the possible exceptions produced by input function:

if __name__ == "__main__":
    tc = input("How many numbers you want:")
    d = 0
    while(tc != 0):
        try:
            num = input("Insert number:")
        except Exception, e:
            print "Error (try again),", str(e)
            continue

        i = 0
        count = 0
        for i in range(0, num):
            try:
                a = input("Insert number to add to your count:")
                count = count + a
            except Exception, e:
                print "Error (count won't be increased),", str(e)

        if (count % num == 0):
            print 'YES'
        else:
            print 'NO'
        tc = tc - 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM