Python for the Energy Industry
Python has a number of 'built-in' functions you can use. You are already familiar with some of these, including print
and range
. In this lesson we will look at some built in functions in more detail.
You have seen how range
works with a single argument. It can also be used with two or three arguments:
# only one argument - all numbers up to 5
print([i for i in range(5)])
[0, 1, 2, 3, 4]
# two arguments - numbers between 2 and 5
print([i for i in range(2,5)])
[2, 3, 4]
# three arguments - numbers between 1 and 9 at multiples of 2
print([i for i in range(1,9,2)])
[1, 3, 5, 7]
The function len
will count the number of items in a list, or the number of letters in a string:
my_list = [1,2,4,6,8,13,19]
my_string = 'test_string'
print('length of my_list:', len(my_list))
print('length of my_string:', len(my_string))
length of my_list: 7 length of my_string: 11
There are a number of functions that convert a value from one type to another type. These are:
int(1)
1
str(1)
'1'
float(1)
1.0
bool(1)
True