2016-08-12 236 views
0

我想跳過空白行(沒有用戶輸入的值)。我得到這個錯誤。如何在用戶輸入python時跳過空行?

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() 
+0

你運行的Python的版本? – Sam

回答

0

的raw_input使用,並手動轉換。這也更節省。有關完整的說明,請參閱here。例如,您可以使用下面的代碼跳過任何不是整數的東西。

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

非常感謝...幫助。 –

0

您將收到的行爲是,請閱讀input文檔。

輸入([提示])

如果提示參數存在時,它被寫入到標準輸出沒有尾隨換行符。然後該函數從輸入中讀取一行,將其轉換爲一個字符串(剝離尾隨的換行符),然後返回該行。當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