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?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Programming for Beginners

Learn to be a Pythonista! Try Python

This book doesn't make any assumptions about your background or knowledge of Python or computer programming. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(124+ reviews)

More Python resources

Ad