3 回答

TA貢獻1820條經(jīng)驗 獲得超10個贊
您的代碼不正確:
def verify(number):
# incorrect indent here
if input ['0'] == '4' # missing : and undeclared input variable, index should be int
return True
if input ['0'] != '4' # missing : and undeclared input variable, index should be int
return "violates rule #1"
固定代碼:
def verify(number):
if number[0] != '4'
return "violates rule #1"
# other checks here
return True
另外我建議False從這個函數(shù)返回而不是錯誤字符串。如果您想返回有錯誤的字符串,請考慮使用 tuple like(is_successful, error)或自定義對象。

TA貢獻1839條經(jīng)驗 獲得超15個贊
看看字符串索引:
字符串可以被索引(下標),第一個字符的索引為 0。沒有單獨的字符類型;一個字符只是一個大小為 1 的字符串:
>>> word = 'Python'
>>> word[0] # character in position 0 'P'
>>> word[5] # character in position 5 'n'
然后閱讀if 語句- 您的代碼缺少:,第二個if可以用else子句替換。
您可能還想檢查函數(shù)的參數(shù),而不是全局變量input(這是一個壞名稱,因為它隱藏了input()內(nèi)置變量)
建議修復(fù):
def verify(number) :
if number[0] == '4':
return True
else:
return "violates rule #1"
testinput = "4000-0000-0000" # change this as you test your function
output = verify(testinput) # invoke the method using a test input
print(output) # prints the output of the function

TA貢獻1785條經(jīng)驗 獲得超4個贊
你的代碼很好,但有幾個問題
def verify(number) :
if input [0] == '4':
return True
if input [0] != '4':
return "violates rule #1"
input = "4000-0000-0000" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output of the function
首先,縮進在python中很重要,屬于函數(shù)定義的所有內(nèi)容都應(yīng)該縮進。
其次,if 語句后面應(yīng)該跟:. 就這些
添加回答
舉報