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.

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Learn Python in One Day

Learn to be a Pythonista! Try Python

Have you always wanted to learn computer programming but are afraid it'll be too difficult for you? Or you're familiar with some programming but are interested in learning Python fast? Then this book is for you. You no longer have to waste your time and money learning Python from lengthy books, expensive online courses or complicated Python tutorials.

$ Check price
11.9711.97Amazon 4 logo(185+ reviews)

More Python resources

Ad