4. Functions¶
Gives possibility to reuse code,
Gives as chance to track code,
Splitting is more logical than executing code line by line
Different definitions of functions
def function_a():
""""Docstring documenting function"""
print('This is simple function')
# "Execution" of a function
function_a()
This is simple function
4.1. Function with parameteres¶
def sum_of_three_numbers(a, b, c):
"""Function calculating sum of three numbers"""
print(a + b + c)
result = sum_of_three_numbers(3, 5, 8)
print(result)
16
None
def sum_of_four_numbers(a, b, c=0, d=0):
"""Simple function suming 4 numbers with default 4th param"""
return (a + b + c + d)
print(sum_of_four_numbers(3, 5))
print(sum_of_four_numbers(3, 5, 8))
print(sum_of_four_numbers(3, 5, 8, 16))
8
16
32
4.2. Args¶
def sum_of_many(show, *nums):
res_sum = 0
for num in nums:
res_sum += num
if show:
print('Sum equals to {}'.format(res_sum))
return res_sum
res = sum_of_many(True, 1, 2, 3, 4, 5, 6, 7)
print(res)
Sum equals to 28
28
4.3. Kwargs¶
def res_salary_sum(**kwargs):
"""Sums all people"""
res_sum = 0
for person, salary in kwargs.items():
res_sum += salary
return res_sum
print(res_salary_sum(Adam=3000, Tomek=2500, Kasia=4320))
9820
4.4. Exercises part 1¶
Create function checking if person is adult
Function should use 2 arguments (name of person and age)
4.5. Exercises part 2¶
Create function which would be checking strength of password (own algorithm)
Password can have at least 6 characters
Password is stronger, when:
It has uppercase letters,
Has numbers,
Has special character (you can define list of special characters on your own ex.
['_', '*', '&']
)
4.6. Exercises part 3¶
Modify code calculation BMI - now it should be function
Takes additional parameter - name,
4.7. Exercises part 4¶
Create function
report_salary(team, stats=True, *args)
which for specific team returns average salary of the team, round the result to the 2nd decimal placeAdditionaly if flag
stats
is on print statistics:Average,
Median,
Minimal value,
Maximal value
Hint
To calculate median either you can create own function. But also you can create function form libraries.