05. Function and Method Calls

Function Calls

Calls are a type of expression that call on some lines of code. A function call works by invoking a function, which is simply a code block with several lines of code.

Take, for example, the print() function. As the help manual page says, this prints the values to a stream, or to sys.stdout (standard out) by default. Our standard out here, is the terminal window (or IDLE GUI on Windows). Thus, when we call the print command, it'll print out to our terminal window.

>>> print("Hello world!")
Hello world!

Try out the len() function as well, which is used to count the number of characters in some argument.

>>> len("Hello world!")
12

Additionally, there are functions that allow for user interaction, which we'll see soon.

>>> userName = input("What is your name? ")
What is your name? JohnDoe

Now if you print out the userName variable, you'll get the user's inputted name.

>>> print(userName)

Method Calls

Furthermore, there exists method calls, which are functions that come with objects, or data types. To use a particular object's method, use the dot notation such as objectInstance.methodCall().

For example, we can use method calls from the String object to run functions on any string we created.

>>> "GAATTAGATCAGTACA".count("G")

This will look for how many times the G letter appears in our string. Note that this method is specific to the primitive data type string. If you try the same method call with an int, for instance, you'll get an error

>>> x = 42
>>> x.count("C")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'count'

We'll see many data types other than the string and int, and along with the variety of methods that come along with them.

Learn to be a Pythonista!

Python Programming

Learn to be a Pythonista! Try Python

This book is designed to be used as the primary textbook in a college-level first course in computing. It takes a fairly traditional approach, emphasizing problem solving, design, and programming as the core skills of computer science. However, these ideas are illustrated using a non-traditional language, namely Python.

$ Check price
45.9945.99Amazon 4.5 logo(211+ reviews)

More Python resources

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Ad