Course Content
Python Functions Tutorial
1. What is Function in Python?
3. Function Return Value Specification
Python Functions Tutorial
Built-in Functions
Built-in functions in Python are pre-defined functions readily available for use in any Python program without requiring additional specifications or definitions. One of the built-in functions is the print()
function - we have already used it. We didn't need to define this function, write its body and specify the return value - we just called it and provided inputs. There are many built-in functions in Python. Now we will consider the most commonly used:
print()
: Outputs a specified message or variable to the console.len()
: Returns the length (number of elements) of an object, such as a string, list, or tuple.type()
: Returns the type of an object.input()
: Reads a line of text input from the user.int()
,float()
,str()
: Converts a value to an integer/float/string.sum()
: Calculates the sum of a sequence of numbers.max()
andmin()
: Returns the maximum/ minimum value from a sequence.round()
: Rounds a number to a specified number of decimal places.
Let's look at the example:
Let's provide some explanations:
- The function begins by checking the type of each input value using the
type()
function. If the type ofa
orb
orc
is not float, it is cast to a float using the float() function. - The calculation is then performed using the updated values of
a
,b
, andc
:max(a, b, c) + min(a, b, c)
calculates the sum of the maximum and minimum values amonga
,b
, andc
.sum([a, b, c]) / 3
calculates the average of the values.
- Finally, the division
(max + min) / average
result is computed and stored in the result variable which is a return value of the function.
Task
Compound interest is a concept in finance and investment that refers to the interest earned or charged on the initial principal amount and any accumulated interest from previous periods. In other words, compound interest allows the interest to be reinvested and earn additional interest over time.
Your task is to write a function that calculates the compound interest given the principal amount, interest rate, and number of years.
You have to:
- Check that all the function arguments have
int
orfloat
type. If it is not true, print an error and set a return value of the function equal to zero. - Round the interest value to two decimal places, ensuring a more concise and readable result.
- Use calculated interest as return value of the function.
Everything was clear?