Mathematics, Sciences, and Technologies

Python for Scientists 1-4: Simple Built-in Functions

,

Concept of Functions

Almost always, we need to perform a certain set of operations in Python repeatedly. It is very cumbersome to copy and paste the entire code block multiple times to achieve the effect. This is one of the main reasons why we have functions. A function in any programming language can take in any number of inputs (including none), execute the code within it, and then return some outputs (also including none). In Python, it is denoted by <function>(<arguments>). Compared to methods introduced in the last tutorial, the main difference is that functions do not need to be bound to any object.

Other advantages of using functions include making the main script simpler. All the heavy lifting is wrapped inside a well-written function that can be called with just one line, and hence after writing that function, we can just put it aside. When we want to tweak it, we just have to modify the definition of the function, without having to change the same thing all over the place. This significantly reduces the risk of errors and facilitates maintenance. Finally, since a function can accept different combinations of inputs every time, it is very versatile and reusable.

Actually, we have encountered the first function in the very beginning. It is the print function that accepts string(s) and outputs them on the screen. (The actual process involves the mechanism of standard streams, and interested readers can search for that.)

Basic Built-in Functions

Python comes with a considerable number of built-in functions for utility. Below, we will introduce some of the most important ones. The full list can be found at https://docs.python.org/3/library/functions.html. The first one is the type function that, as its name suggests, inspects the type of the object being input. To illustrate:

a_int = 123
a_float = 1.23
a_string = "123"
print(type(a_int), type(a_float), type(a_string))

returns <class 'int'> <class 'float'> <class 'str'> as expected.

Three clearly related functions are int, float, str, which converts the input into the corresponding class. For example,

x = 1
y = 3.88
x_float = float(x)
y_int = int(y)
y_string = str(y)
print(x_float, y_int, y_string)
print(type(y), type(y_string))

will give

1.0 3 3.88
<class 'float'> <class 'str'>

Two things to note here. First, applying int to a float will truncate its decimal parts no matter what. Second, even though y_string also appears as 3.88, it is actually a string, as shown by the type function.

input Function

A particularly interesting function is the input function, which will prompt and store the user’s input when invoked. As an example, if we execute

user_name = input("Please enter your name:")
print(f"Hello, {user_name}!")

then we will be prompted as follows:

Please enter your name:

If we indeed enter our own input after the prompt, e.g.

Please enter your name:Benjamin

then this will lead to the output of

Please enter your name:Benjamin
Hello, Benjamin!

This utility is quite useful for making interactive programs. Notice that no matter what characters are typed for responding to the input function, they will be treated as a single string object. (see exercise)

Exercise

Write a program to ask the user for two numbers and add them together. Notice that we have to convert the inputs from strings to floats!

Suggested Solution
first_num = float(input("Enter Number 1 here:"))
sec_num = float(input("Enter Number 2 here:"))
print(f"{first_num} plus {sec_num} is {(first_num+sec_num):.2f}.")

Check by entering 1.23 and 2.46 returns 1.23 plus 2.46 is 3.69. as expected. Try removing the float part and see what will be raised!

Leave a Reply

I’m Benjamin

Welcome to my Mathematical World! Here you can find posts and tutorials related to applied topics like Linear Algebra, Calculus, Differential Equations, and Programming. Feel free to leave comments and suggestions!

Discover more from Benjamin's Maths World

Subscribe now to keep reading and get access to the full archive.

Continue reading