我想跳过空白行(用户没有输入值)。我得到这个错误。
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
我的代码是:
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()
使用raw_input,并手动转换。这也是比较节省的。有关完整的解释,请参阅此处。例如,您可以使用下面的代码跳过任何非整数。
x = None
while not x:
try:
x = int(raw_input())
except ValueError:
print 'Invalid Number'
你得到的行为是预期的,阅读输入文档。
输入([提示])
如果存在prompt参数,则将其写入标准输出,不带尾随换行符。然后,该函数从输入中读取一行,将其转换为字符串(去掉末尾的换行符),并返回该字符串。当读取EOF时,引发EOFError
尝试这样做,代码将捕获输入函数可能产生的异常:
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