Tips for Creating Functions in Python
- Function names must be verbs.
- The name of each function should accurately reflect what the function does.
- A function should do only what its name clearly implies, and nothing else.
- Each function should perform only one action.
- Use helper functions inside functions.
-
It is better not to make the function code longer than
10-15lines. - It is better to break long functions into a number of auxiliary ones.
-
Use common prefixes in function names:
show,get,set,calc,create,change,check. -
If a function name consists of two or more words, they should be separated from each other by an underscore
_, for example,get_sum. - Move duplicate code into functions.
Write down the shortcomings of the following code and fix them:
def func(num1, num2):
return num1 * num2
Write down the shortcomings of the following code and fix them:
def user(name):
return 'bye, ' + name
Write down the shortcomings of the following code and fix them:
def get_num(num):
return str(num)
Write down the shortcomings of the following code and fix them:
def check(lst):
sum = 0
for el in lst:
if el > 0:
sum += el
if el < 0:
continue
else:
continue
return sum