An introduction to Python that even monkeys can understand (Part 3)

Then, it is the third article for beginners following the last time. This time we'll cover Python functions, methods, and packages.

table of contents

  1. Function
  2. Method
  3. Package

1. Function

First, let's talk about functions. In fact, functions have already appeared so far. It's a type function, a list function, etc. So who exactly is a function? Simply put, a function is a piece of reusable code that aims to solve a particular task </ b>. If you want to do something, you usually have to write the code yourself, but if a function exists, writing that function will do the work for you instead of writing the code. Let me explain with an example. Below is a list of familiar prices every time.

price = [2, 2.5, 13, 1.15]

Now suppose you want to get the maximum price. You can also find the maximum value by comparing the numerical values one by one without using a function. However, if you know the max function that finds the maximum value, you can find it in one shot as follows.

price = [2, 2.5, 13, 1.15]
max(price)

Running the above code will return the highest number in the list.

13

Like type (), the max function is a Python built-in function (a function that can be used by default without being defined or implemented in code) and can be used by anyone. Of course, you can also assign the result of the function to a new variable as follows:

most_expensive = max(price)
#13 is most_Substituted for expensive

Next, let's introduce a built-in function called round function </ b>. This function called round is a function that rounds. As shown below, describe the number you want to round and the number of digits you want to round. round (number, number of digits) </ b> Below is the code if you want to round 3.14 to the first decimal place.

round(3.14, 1)

If you run the above code, it will be rounded to the first decimal place as shown below.

3.1

And if the number of digits is not specified, it will be rounded to an integer.

round(3.14)

The result is as follows.

3
#If you do not specify the number of digits, it will be an integer.

In fact, let's see python help to see what kind of function round is. To see the contents of the function, use the help function as shown below.

help(round) 

When I run the above code, the details of the function are displayed as output as below.

round(...)
    round(number[, ndigits]) -> number
    
    Round a number to a given precision in decimal digits (default 0 digits).
    This returns an int when called with one argument, otherwise the
    same type as the number. ndigits may be negative.

According to the explanation, the round function requires two types of inputs, number and ndigit (the input of the function is called argument </ b>). However, if there is only one argument and there is no ndigit (the argument that specifies the number of digits), it will be rounded to an integer. If you look closely at the explanation given in this help, you can see that ", ndigits" are enclosed in square brackets []. This means that the function works even if [] does not exist, and this time it means that if there is no [] part, the argument is rounded to an integer. That is, the arguments in [] are optional </ b>.

Next, let's take a look at the sorted function </ b>.

help(sorted)

Looking at the explanation with the help function, the following answer was returned.

Help on built-in function sorted in module builtins:

sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.

You can see that sorted () takes three arguments: iterable, key, and reverse. Actually, this sorted function is deep, but to explain it briefly, iterable objects with multiple elements (such as lists. The concept of "objects" will be explained in the next method chapter, so for the time being list If you specify (please think), it is a function that sorts those elements. If you enter True in reverse, it will be sorted in descending order, and if you enter False, it will be sorted in ascending order. The key is an argument that specifies the sorting option, but this is an article for beginners, so I will omit it.

price = [2, 2.5, 13, 1.15]
sorted(price, reverse = True)

Since reverse is True, it is sorted in descending order,

[13, 2.5, 2, 1.15]

The result is.

Well, this time I introduced the function. I have learned very few functions so far, but I will probably come across various functions in the future as I perform various analyzes. There may be unexpectedly useful functions when you search on the net thinking "I wonder if there is such a function". If you use the help function, you can see how even the first-time function works, so please try out various functions.

2. Method

Now you know about built-in functions such as max () to get the maximum value of a list and len () to get the length of a list or string. However, you still can't do basic operations like getting the index of an element in the list or reordering the contents of the list. Of course, a built-in function that can do this would be a solution, but I've never seen such a function, and if it does, it's rarely used. So what should we do with those operations? By the way, we have already created many variables of various types such as string type, float type, list type and so on.

name = "ItemA"
#String type
value = 13
#float type
price = ["ItemA", 2, "ItemB", 2.5, "ItemC", 13, "ItemD", 1.15]
#list type

These values and data are called Python objects </ b>. This string is also an object, and this float is also an object. Of course, list is also an object. These objects have specific "types", such as strings, floats, lists, etc., the "ItemA" contained in the list is a string type object, and the entire list is also a list type Object. And each object, not just the type, has a method </ b>. Conceptually, you can think of a method as a function that "belongs" to a Python object </ b>. For example, an object of type string has a method called capitalize () that makes the first character of the string uppercase and the rest lowercase, and a method called replace () that performs replacement. As you can see, there are different methods depending on the type of object, and there are also different methods for float and list.

Examples of types and methods

Mold Method example
str capitalize()、replace()
float bit_length()、conjugate()
list index()、count()

By the way, even if you talk about the theory, you may not be able to understand it well, so let me show you an example of how to actually use it.

In the list below, suppose you want to get the index for "ItemC".

price = ["ItemA", 2, "ItemB", 2.5, "ItemC", 13, "ItemD", 1.15]

Since Price is a list type Python object, it has a method called index. To call the method, use dot notation as follows.

price.index("ItemC")
#Apply index method to price

Enter the string "ItemC", the element for which you want to get the index. Of course, what is returned is 4, which is the index of "ItemC".

4
#"ItemC"Index

Now you can count how many 13s are in the list using a method called count that you can use with an object of type list.

price.count(13)
#Apply count method to price

Of course, 13 appears only once in the list, so 1 is returned.

1

So far we have seen methods for list type objects. However, Python objects with methods have various methods not only in lists, but also in float, integer, boolean, and string. For example, let's look at an object of type string.

product1 = "pencil"

The string "ItemA" is assigned to product1. Let's use a method called capitalize () for this product1.

product1.capitalize()

In this case, using capitalize () will return a string with only the first letter capitalized.

"Pencil"

A similar method is upper (), which capitalizes the string.

Now, let's try the replace method that performs the replacement, which I briefly introduced earlier. I have assigned pencil to product1, but when I really want to put it in penstand, I can fix it as follows.

product1.replace("cil","stand")

Since "cil" in pencil is replaced with "stand", the string assigned in product1 is as follows.

"penstand"

As we've seen, each object has its own method, depending on its type, and each type has different methods. For example, you can use replace's replace method for string, but list type objects don't have this method. However, objects of different types may have the same method. For example, the index method.

price.index("ItemC")
product1.index("e")

The index method exists in both list type and string type. When the index method is used in list type, the index of the element in the list is used, and when it is used in string type, the index of the character in the string is used. To get In other words, depending on the type of object, the same method may behave differently.

4
#At price"ItemC"Index is 4
1
#In the pencil"e"Index is 1

Well then, just one point before moving on to the next chapter. Some methods allow you to modify the called object. Try calling the append method on the price list.

price = ["ItemA", 2, "ItemB", 2.5, "ItemC", 13, "ItemD", 1.15]
price.append("ItemE")

append is a method that adds a new element to the list. If you look at the price list after performing the above operations, it will be as follows.

price = ["ItemA", 2, "ItemB", 2.5, "ItemC", 13, "ItemD", 1.15, "ItemE"]

On the other hand, if you want to remove an element from the list, you can remove it with a method called remove () in the same way as append (). You can also arrange the list in reverse order by using the method called reverse () as shown below.

price.reverse()

After performing the above operation, if you try to display the price list with print (price), you can see that the list is in reverse order as shown below.

[1.15, "ItemD", 13, "ItemC", 2.5, "ItemB", 2, "ItemA"]

You need to keep this in mind, as some methods change the contents of the object in this way.

3. Package

Now you know about Python functions and methods. These are quite powerful features and I think they will be used many times in the future. However, if you write all the necessary functions and methods, the actual amount of code to be written will be enormous and it will take time and effort. Besides, managing the code is difficult. So we use a package </ b> that is a collection of python code scripts. There are so many Python packages on the net, especially NumPy </ b> that handles arrays efficiently, Matplotlib </ b> that is used for data visualization, and used for machine learning. Scikit-learn </ b> etc. are often used. However, not all of these packages are available by default, and you must install them on your system and write the "I want to use this package" command as code to use them. (For installation, you can use the Python package maintenance system pip </ b> etc.). Specifically, go to the following URL and download the file get-pip.py. https://pip.pypa.io/en/stable/installing/ Then go to your terminal and run python3 get-pip.py. You can now use pip to actually install your favorite Python packages. In the next article, I'll cover one of the packages, NumPy, in detail, but here let's install the NumPy package specifically. First of all

pip3 install NumPy

Enter. Now you have to use the commands python3 and pip3 to tell the system that you are working with Python version 3. Now that the package is installed, you can actually start using it in your Python script. But before that, you need to import the package or the specific module of the package. This can be done with the import statement. To import the entire NumPy package, run import NumPy as follows:

import numpy

A commonly used function in NumPy is array. So how do you use array? Actually, if you write as follows, an error will occur.

array([2, 2.5, 13, 1.15])
#If you write as above, "Name Error": name 'array'I get an error saying "is not defined"

This time, since the array function is referenced from the NumPy package, it is necessary to write as follows.

numpy.array([2, 2.5, 13, 1.15])

However, it's also hard to type "numpy." Every time, so you can use as to make the name simpler when importing the package.

import numpy as np

This will save you a lot of typing "np." Instead of "numpy.".

Now you know how to import numpy. However, if you want to use various functions of numpy, you can import it like this, but if you want to use only the array function among the various functions of numpy, there is a way to further reduce the amount of description.

from numpy import array

And by importing only array from numpy

array([2, 2.5, 13, 1.15])

You can use numpy's array function just by typing. You no longer have to type "np." Importing to use only a part of the package in this way is useful for reducing the amount of coding. However, this also has its drawbacks, which make it difficult to follow the context of your code. For example, let's say you are working with a very long script like this:

from numpy import array
……
price = ["ItemA", 2, "ItemB", 2.5, "ItemC", 13, "ItemD", 1.15]
……
price_ext = price + ["ItemE", 2.5]
……
print(str(len(price_ext) + "elements in price_ext")
……
np_price = array(price_ext)
#You may have forgotten that numpy has been imported at this point

I'm importing numpy at the very beginning, but since this code is so long, there is a possibility that a third party reading the code may forget that the array is a numpy array in the middle. is. (On the other hand, if you write np.array (), you can instantly understand that "this is a numpy array".) For this reason, it is clear that importing numpy as np and writing it in np.array () uses numpy.

Now you know how to import. For reference, I will also show you how to import only the functions inside the subpackages inside the package. For example, suppose you have a package called scipy that is used for numerical analysis, but you have a subpackage in it called linalg (used to calculate a matrix) and you want to use only that function called inv () (which uses an inverse matrix). The function to be calculated). At this time, write as follows.

from scipy.linalg import inv

from "package". "Subpackage" import function name </ b> Write using dots (.).

So, as a summary so far, write a code to find the circumference and area of a circle with a radius of 1. Pi can be called with pi in a package called math. The answer is as follows

#Define radius
r = 1

#Import math
import math

#Circumference(Diameter x pi)Calculate
C = 2*math.pi*r

#area(Radius x radius x pi)Calculate
A = math.pi*r*r

#Display calculation result
print("Circumference: " + str(C))
print("area: " + str(A))

Now you know how to import packages. Next time, I'll write about one of those packages, NumPy.

Recommended Posts