- Built-in functions that are provided as part of Python -
print(), type(), float(), int() ...
- Functions that we define ourselves and then use
The built-in function names are treated as "new" reserved words, and should not be used as variable names. We can define a new function using the def
reserved word (We will see this soon).
We call/invoke the function by using the function name, parenthesis and arguments in an expression.
Example 1 - Max()
The following is an example of the in-built max()
function in Python. The max()
returns the largest of its arguments.
1>>> max("hello world") #Returns the largest letter in the string
2'w'
3>>> mylist = [1,2,3,4,5,6] # returns the largest item in the list
4>>> max(mylist)
56
6>>>
7
Example 2 - Round()
Let's take another example of an in-built function round()
. The round()
function rounds a given number to specific digits from the decimal point. The round function takes as first argument the number and the second argument is the precision. In the following example, the number 4.758
is rounded to two decimal points.
1>>> round(4.758,2)
24.76
3
Getting Help on Functions
While there are many ways to get help on Python functions (including Google), the first thing you should do when you want to know about a particular function is to use the inbuild help()
function. The following example shows how we can get help on the round()
function using the help()
function.
1>>> help(round)
2Help on built-in function round in module builtins:
3round(...)
4 round(number[, ndigits]) -> number
5 Round a number to a given precision in decimal digits (default 0 digits).
6 This returns an int when called with one argument, otherwise the
7 same type as the number. ndigits may be negative.
8
Finding a Function
You now know that you can use the Python functions such as max()
and round()
. But how do you know that a function exists in the first place. As you will work more and more with Python code, you will learn more about a variety of functions. Whenever you want to perform a specific task, it's a good idea to do a search on the internet to know if a function already exists (there's a high chance it is actually does). If a function does exist, your first choice should be to use it rather than writing your own code. You can also ask the Finance Train community for your requirements.
Exercises
- Define a list with six numbers and assign it to variable
myvar
. Use the type()
function to find the variable's type and print it. Try this both in interactive and file mode. Note that if you're creating a file, you will have to use the print()
function to print the results.
- Use the
len()
function to get and print the length of the list.
- Get the 2nd element of the list and convert it to a float using the
float()
function.
- Get help on
sorted()
function using the help()
function. Use the sorted()
function to sort the list we created above.