Using Functions

using functions

Using functions

Video Transcript

In this section, we're going to look more closely at using functions. In earlier sections, we learned that in order to use a function, we first write the function's name, then a pair of parentheses, and then any necessary arguments inside. That function will then perform some kind of action, maybe printing something to the console like print(), or producing some value that can be used or saved in a variable like input() or random.randint().
There are two important things to remember when using functions with arguments. Let's take a look at random.randint() to see what they are.
The first thing is that the order matters. The random.randint() function, for example, takes two arguments. The first is the minimum value, and the second is the maximum value. If we put them in correctly, we get something like:
import random
number = random.randint(1, 10)
print(number)
# random number between 1 and 10
But if we reverse the order and try to put the larger number first, then we end up with an error:
import random
number = random.randint(10, 1)
print(number)

# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "/usr/lib/python3.8/random.py", line 248, in randint
#     return self.randrange(a, b+1)
#   File "/usr/lib/python3.8/random.py", line 226, in randrange
#     raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
# ValueError: empty range for randrange() (10, 2, -8)
The second thing is that the data type matters in many cases. random.randint() works fine with integers, but if we try to use floats or strings, we again get an error:
import random
number = random.randint(1.5, 10.6)
print(number)

# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "/usr/lib/python3.8/random.py", line 248, in randint
#     return self.randrange(a, b+1)
#   File "/usr/lib/python3.8/random.py", line 212, in randrange
#     raise ValueError("non-integer arg 1 for randrange()")
# ValueError: non-integer arg 1 for randrange()
Last section Next section