你幾乎在那裏,只是不完全。正如評論中指出的那樣,您在原始代碼中的一個問題是第一個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
>>>
這樣,直到輸入一個有效的整數您隨時查詢偏移值。
請修復您的縮進。另外,如果你的代碼看起來像*那樣。這實際上是你的問題。您需要確保您的代碼正確對齊。 – idjaw
您可能應該使用支持python語法的文本編輯器或IDE,並自動對其進行格式化,因此這對您而言不會有任何問題。 –