[英]Indentation Style in Python : Reverse Words Function
def is_reverse(word1, word2):
if len(word1) != len(word2):
return False
i = 0
j = len(word2)
while j > 0:
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
return True
is_reverse('pots', 'stop')
我已經定義了上面的功能,以檢查兩個給定的單詞是否彼此反向匹配。
但是當我運行它時,它會不斷提醒我縮進錯誤。
如何衡量python中的縮進級別?
一般來說
每個縮進級別使用4個空格。
(不要混用制表符和空格)。
當開始一個新塊的主體時(例如,在if
和`while中),相對於引入該塊的行,使主體縮進4個空格。
所以當你寫
if len(word1) != len(word2):
...
...
例如,如果條件發生,應該發生的所有事情都應該相對於if
有4個空格。 如果還有另一個if
,或者while
內部,則進一步增加其主體的縮進4個空格,依此類推。
另外,請注意,您可以使用以下命令檢查兩個單詞是否彼此反向匹配
def is_reverse(word1, word2):
return word1 == reversed(word2)
一般規則是
4
空格縮進。
以下是正確縮進的示例,未更改原始代碼:
def is_reverse(word1, word2):
if len(word1) != len(word2):
return False
i = 0
j = len(word2)
while j > 0:
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
return True
縮進在python中很重要,因為它定義了哪些代碼屬於同一類(例如,用其他語言的方括號來完成)。
由於您的代碼格式嚴重錯誤,請查看重新格式化的代碼:
def is_reverse(word1, word2):
if len(word1) != len(word2):
return False
i = 0
j = len(word2)-1
while j >= 0:
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
return True
is_reverse('pots', 'stop')
-> True
注意,我還更改了j = len(word2)-1
和while j >= 0:
:,因為長度為x的單詞在位置0..x-1處具有字母。
提示:字符串反轉可以通過切片符號和步長為-1來實現:
"pots"[::-1] == "stop"
在python中,縮進級別使用的空格數量在語法上並不重要,它可以是任意數字(在大多數情況下,每個級別使用2、4或8個空格),但必須保持一致。 因此,在if塊之后,您必須返回到以前的縮進級別,如下所示:
def is_reverse(word1, word2):
if len(word1) != len(word2):
return False
i = 0
j = len(word2)
while j > 0:
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
return True
is_reverse('pots', 'stop')
此代碼不會引發IndentationError。 當然,出於風格原因,最好具有恆定的縮進級別,如下所示:
def is_reverse(word1, word2):
if len(word1) != len(word2):
return False
i = 0
j = len(word2)
while j > 0:
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
return True
is_reverse('pots', 'stop')
您的代碼也存在邏輯錯誤,因為j的起始值應比字符串的長度小1(由於從零開始的索引編制),然后一直下降到0,如下所示:
i = 0
j = len(word2) - 1
while j >= 0:
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.