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 Playground

Learn to be a Pythonista! Try Python

Python Playground is a collection of fun programming projects that will inspire you to new heights. You'll manipulate images, build simulations, and interact with hardware using Arduino & Raspberry Pi. With each project, you'll get familiarized with leveraging external libraries for specialized tasks, breaking problems into smaller, solvable pieces, and translating algorithms into code.

$ Check price
29.9529.95Amazon 4 logo(14+ reviews)

More Python resources

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Ad