1

我想檢查看看是否輸入是一個整數,但我一直得到一個語法錯誤。代碼如下,謝謝!Python - 語法錯誤與'異常'

try: 
    offset=int(input("How Much Would You Like To Offset By?\n")) 
    except ValueError: 
     while offset!=int: 
      print("Please Enter An Integer!") 
      offset=int(input("How Much Would You Like To Offset By?\m")) 
      except ValueError 
+5

請修復您的縮進。另外,如果你的代碼看起來像*那樣。這實際上是你的問題。您需要確保您的代碼正確對齊。 – idjaw

+1

您可能應該使用支持python語法的文本編輯器或IDE,並自動對其進行格式化,因此這對您而言不會有任何問題。 –

回答

2

正如評論中所述,您需要正確縮進代碼。例如,您可以使用像Spyder這樣免費且相對輕量級的IDE。另外,你的代碼末尾還有一個except,不應該在那裏。但是,仔細查看代碼,還有其他問題。你while循環目前不這樣做你期望它做的事情,如果你正在使用Python 2.x的,你需要與raw_input

try: 
    offset=int(raw_input("How Much Would You Like To Offset By?\n")) 
except ValueError: 
    while offset!=int: 
     print("Please Enter An Integer!") 
     offset=int(input("How Much Would You Like To Offset By?\m")) 

你想要做這樣的事情,我懷疑,在那裏你保持替換input詢問用戶輸入,直到輸入有效整數:

offset = None 

while not(offset): 
    try: 
     offset=int(input("How Much Would You Like To Offset By?\n")) 
    except ValueError: 
      print("Your input was not a valid number, please try again") 
      offset = None 
+0

請注意,如果OP使用Python 3,那麼'input()'是正確的。我最初的假設是,由於他使用了Python 3樣式的print()函數,而不是Python 2樣式的print語句。 –

+1

謝謝,我已更新我的帖子,以清楚說明。不幸的是,我的工作仍然停留在Python 2.7上。 – Jaco

0

你幾乎在那裏,只是不完全。正如評論中指出的那樣,您在原始代碼中的一個問題是第一個except的縮進。

一旦你解決這個問題,你再有一個第二個問題:

>>> def get_offset(): 
...  try: 
...   offset=int(input("How Much Would You Like To Offset By?\n")) 
... 
...  except ValueError: 
...   while offset!=int: 
...    print("Please Enter An Integer!") 
...    offset=int(input("How Much Would You Like To Offset By?\m")) 
...    except ValueError 
    File "<stdin>", line 9 
    except ValueError 
     ^
SyntaxError: invalid syntax 
>>> 

你從第二except ValueError得到這個問題,因爲沒有 try與它相關聯。如果你解決了這個問題,你會再得到一個錯誤,因爲下面的行引用的offset值它的實際分配前:

while offset!=int: 

如果在input()語句輸入的值轉換初始嘗試失敗,則沒有值實際上分配給offset,這是導致此錯誤的原因。

如下我想接近它:

>>> def get_offset(): 
...  while True: 
...   try: 
...    offset = int(input("How Much Would You Like To Offset By?\n")) 
...    break # Exit the loop after a valid integer has been entered. 
... 
...   except ValueError: 
...    print("Please enter an integer!") 
... 
...  return offset 
... 
>>> x = get_offset() 
How Much Would You Like To Offset By? 
5 
>>> print(x) 
5 
>>> x = get_offset() 
How Much Would You Like To Offset By? 
spam 
Please enter an integer! 
How Much Would You Like To Offset By? 
eggs 
Please enter an integer! 
How Much Would You Like To Offset By? 
27 
>>> print(x) 
27 
>>> 

這樣,直到輸入一個有效的整數您隨時查詢偏移值。

+1

'while true:'帶'break'使我的眼皮抽搐。 –