風格指南
- 使用4-空格縮進砌烁,不用制表符
- 包裹行讓它們不超過79字符
- 使用空行分隔函數(shù)罩驻、類和函數(shù)內(nèi)較大的代碼塊
- 盡量注釋
- 使用文檔字符串
- 逗號后、操作符周圍使用空格
- 統(tǒng)一命名類和函數(shù)
- 傳統(tǒng)是對類使用駱駝拼寫法,函數(shù)和方法使用小寫和下劃線
風格指南
回文示例
#!/usr/bin/python3
"""
Asks for user input and tells if string is palindrome or not
Allowed characters: alphabets and punctuations .,;:'"-!?
Minimum alphabets: 3 and cannot be all same
Informs if input is invalid and asks user for input again
"""
import re
def is_palindrome(usr_ip):
"""
Checks if string is a palindrome
ValueError: if string is invalid
Returns True if palindrome, False otherwise
"""
# remove punctuations & whitespace and change to all lowercase
ip_str = re.sub(r'[\s.;:,\'"!?-]', r'', usr_ip).lower()
if re.search(r'[^a-zA-Z]', ip_str):
raise ValueError("Characters other than alphabets and punctuations")
elif len(ip_str) < 3:
raise ValueError("Less than 3 alphabets")
else:
return ip_str == ip_str[::-1] and not re.search(r'^(.)\1+$', ip_str)
def main():
while True:
try:
usr_ip = input("Enter a palindrome: ")
if is_palindrome(usr_ip):
print("{} is a palindrome".format(usr_ip))
else:
print("{} is NOT a palindrome".format(usr_ip))
break
except ValueError as e:
print('Error: ' + str(e))
if __name__ == "__main__":
main()
- 首個三引號括起的字符串標記了整個程序的文檔字符串
- 第二個是
is_palindrome()
函數(shù)特定的文檔字符串
$ ./palindrome.py
Enter a palindrome: as2
Error: Characters other than alphabets and punctuations
Enter a palindrome: "Dammit, I'm mad!"
"Dammit, I'm mad!" is a palindrome
$ ./palindrome.py
Enter a palindrome: a'a
Error: Less than 3 alphabets
Enter a palindrome: aaa
aaa is NOT a palindrome
- 讓我們看下文檔字符串怎么作為幫助使用
- 注意文檔字符串是怎么自動格式化的
>>> import palindrome
>>> help(palindrome)
Help on module palindrome:
NAME
palindrome - Asks for user input and tells if string is palindrome or not
DESCRIPTION
Allowed characters: alphabets and punctuations .,;:'"-!?
Minimum alphabets: 3 and cannot be all same
Informs if input is invalid and asks user for input again
FUNCTIONS
is_palindrome(usr_ip)
Checks if string is a palindrome
ValueError: if string is invalid
Returns True if palindrome, False otherwise
main()
FILE
/home/learnbyexample/python_programs/palindrome.py
- 也可以直接獲取函數(shù)幫助
>>> help(palindrome.is_palindrome)
Help on function is_palindrome in module palindrome:
is_palindrome(usr_ip)
Checks if string is a palindrome
ValueError: if string is invalid
Returns True if palindrome, False otherwise
- 測試函數(shù)
>>> palindrome.is_palindrome('aaa')
False
>>> palindrome.is_palindrome('Madam')
True
>>> palindrome.main()
Enter a palindrome: 3452
Error: Characters other than alphabets and punctuations
Enter a palindrome: Malayalam
Malayalam is a palindrome
進一步閱讀