3个适合初学者的Python优秀实践,值得拥有!
我们常常分享编程其实很简单的文章,给大家树立信心。
如果只是编写简单的程序,如果你只是想马上完成,一天的时间即可完成。
但如果你想很快地编写复杂,却没有重构和注释几乎不可读的代码。对不起,面对现实吧,编码很难。

通常这种情况下,别人不得不帮你收拾烂摊子。
因此,为了增加可读性和可重用性,负责任的重组和记录代码非常重要。
这里小芯就给大家推荐3种编写Python的好方法,它们能帮你成为更好的程序员。
1. Docstring
Docstring 是Python文档字符串的英文缩写。Docstring是三重双引号 ”“”中,在所定义模块,函数,类或方法的第一个陈述。这是函数中docstring的最小示例。
deffoo(): """This function doesnothing.""" passprint(foo.__doc__) # Thisfunction does nothing.
函数的文档字符串应包含(一行)对目的的简短介绍,后面的段落描述了函数调用约定。样式多种多样,但这是我最喜欢的模板之一:
defsum_of_squares(nums):
"""
Compute the sum of squares of a list of numbers.
Args:
nums (`list` of `int` or `float`): A `list` of numbers.
Returns:
ans (`int` or `float`): Sum of squares of `nums`.
Raises:
AssertionError: If `nums` contain elements that are not floats nor ints.
"""
try:
ans =sum([x**2for x in nums])
except:
raiseAssertionError('Input should be a list of floats or ints.')
return ans 由GitHub发起的rawdocstring.py
2. f-string(格式化字符串)
你可能习惯于使用以下命令格式化字符串,即%或者format().
name ='World'
'Hello %s' % name # Hello World
'Hello {}'.format(name) # Hello World 抛弃它们。 一旦你需要在更长的字符串中打印多个变量,该代码将很快变得混乱且难以理解。无论如何,这些格式化方法并不简单。
Pythonf-string是Python 3.6的引入的改变游戏规则的工具。这是一种可读且高级的字符串格式句法,将表达式嵌入字符串。这是通过语句f'{expr}'完成的; 其中表达式用f字符串内的大括号括起来。表达式在开头带有f,位于单引号之前。
示例:
name ='World' print(f'Hello{name}') # Hello World 可以在大括号内写任何在语法上有效的表达。还可以在表达式中调用函数!
a =[1,2.2,3]
print(f'Sum of squares of {a} is {sum_of_squares(a)}')
# Sum of squares of [1, 2.2, 3] is 14.84