Functions
Functions
In addition to operators like +
and -
, Python also includes many functions.
Functions can be used by calling them.
We've actually already seen a function: the print
function.
We used print
by calling it like this:
>>> name = "Trey"
>>> print("Hello", name)
Hello Trey
You can call a function by putting parentheses after it.
See Calling a function in Python for more.
Built-in Functions
Python comes with dozens of built-in functions.
The int
function can convert a string that represents an integer into an actual integer:
>>> number = "5"
>>> number
'5'
>>> int(number)
5
The str
function can convert any object to a string:
>>> str(5)
'5'
The type
function can give us the type of an object:
>>> type("5")
<class 'str'>
>>> type(5)
<class 'int'>
>>> type(5.0)
<class 'float'>
The dir
and vars
functions can be helpful for debugging your code, especially while playing around in the Python REPL.
They're ways to ask "what variables are defined right now and what are their values"?
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'name', 'number']
>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'name': 'Trey', 'number': '5'}
You can ignore the variables with double underscores around them. Those are special variables that mean something special to Python and we don't usually define those ourselves.
Other Functions
You can also find functions in the Python standard library (used by importing a module) as well and you can even define your own functions. We'll see how to do that later.
Methods
Many types of Python objects also include functions that live on the object itself. These are called methods.
For example strings have a lower
method, which returns a lowercase version of the string:
>>> name = "Trey"
>>> name.lower()
'name'
You can refer to a method by putting a period (.) after a reference to the object and then writing the method name. Methods can be called just as functions can be.
Want to play with some methods? Try out some of Python's string methods on a new string!
Breakpoint for debugging
There's one function you'll never use in your working Python code, but which can be very handy when you're troubleshooting a broken Python program: the breakpoint
function.
The breakpoint
function allows us to drop into the "Python debugger", which is similar to the Python REPL, though it's slightly different.
The Python debugger has a number of commands you can lookup on your own, but these commands are likely the most useful:
n
(ornext
): Run the next line of codel` (or ``list
): List the surrounding code linesinteract
Starts an interactive Python interpreter (REPL)c
(orcontinue
): Continue running (until a breakpoint or exit)
Try using breakpoint
to debug this Python program:
from random import randint
answer = randint(0, 1)
n = input("Guess: 0 or 1? ")
if n == answer:
print("Correct!")
else:
print(f"Incorrect. The answer was {answer}.")
When we run this program it always says our guess was incorrect, even when it was correct!
$ python3 guess.py
Guess: 0 or 1? 0
Incorrect. The answer was 0.
Let's put a call to breakpoint
just after that ``answer = `` line:
from random import randint
answer = randint(0, 1)
breakpoint()
n = input("Guess: 0 or 1? ")
if n == answer:
print("Correct!")
else:
print(f"Incorrect. The answer was {answer}.")
Using breakpoint is a valuable skill for debugging Python code. So is reading a traceback in Python.