Conquer 69 Python built-in functions 6th p ~ r

Python has a large number of built-in functions (Built-in Functions) that allow you to do various things without importing the library. I would like to go back to the basics and organize how to use built-in functions.

The execution example is created with Python 3.7.5 installed on Ubuntu 18.04 of Windows Subsystem for Linux 2 (WSL2).

(Notes) Please note that as a result of the update period, the minor version and execution environment of Python are different from the articles up to Part 4. Also, as of the time of writing, Python 3.8.0 has been released, but since this series is written in Python 3.7 series, please be aware of that as well.

Conquer 69 built-in Python functions 1st a to b Conquer 69 built-in Python functions 2nd c ~ d Conquer 69 built-in Python functions 3rd e-g Conquer 69 built-in Python functions h ~ i Conquer 69 Python built-in functions 5th l ~ o

How to use the function

I will describe how to use each function. I will leave the detailed usage to other articles, but here I will mainly post simple usage examples.

pow()

It calculates the power of the given argument. If you give two arguments like pow (x, y), it is equivalent to x ** y.

>>> #Integers
... pow(2, 3)
8
>>> #The second argument is a negative value
... pow(10, -3)
0.001
>>> #The second argument is a decimal
pow(3, 2.5)
15.588457268119896

Given the third argument, it calculates the remainder. According to the documentation, pow (x, y, z) is more efficient than pow (x, y)% z.

>>> #2 to the 3rd power of 5 remainder
... pow(2, 3, 5)
3
>>> #If the second argument is negative, the third argument cannot be given
... pow(2, -3, 5)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
>>> #Modulo operation requires all arguments to be integers
... pow(2, 1/2, 3)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: pow() 3rd argument not allowed unless all arguments are integers

By the way, from python3.8, it is possible to calculate the remainder even if the exponent is a negative value.

$ docker container run -it python:3.8
Python 3.8.1 (default, Dec 20 2019, 21:56:21)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> pow(2, -3, 5)
2

print()

Converts the given object to a string and writes it to standard output. You can pass multiple values. The delimiter is specified by the argument sep, and the line end is specified by the argument end.

>>> #Famous guy. The default for end is the newline character(\n)
... print('Hello, world!')
Hello, world!
>>> #If you pass more than one. The default for sep is space( )
... print('Good Bye', 'Python2')
Good Bye Python2
>>> #You can set the delimiter and line feed character.
... print('foo', 'bar', 'piyo', 'hoge', sep='!!!, ', end='!?\n')
foo!!!, bar!!!, piyo!!!, hoge!?
>>> #Numerical value
... print(1, 1, 2, 3, 5, 8, 13)
1 1 2 3 5 8 13
>>> #list
... print(['H', 'e', 'l', 'l', 'o'])
['H', 'e', 'l', 'l', 'o']
>>> #Homebrew class
... class MyClass1: pass
...
>>> print(MyClass1())
<__main__.MyClass1 object at 0x7f1c8720a450>
>>> # __str__You can control the value to be stringified by implementing
... class MyClass2:
...     def __str__(self):
...         return 'This is ' + self.__class__.__name__
...
>>> print(MyClass2())
This is MyClass2

By default, the print () function writes a value to standard output (sys.stdout), but you can change the write destination with the file argument.

>>> #Write to standard error
... print('Error has occured!!', file=sys.stderr)
Error has occured!!
>>> #Write to file
... with open('hello.txt', 'w') as f:
...     print('Hello, my file', file=f)
...
>>> #Certainly it is written to a file.
... with open('hello.txt', 'r') as f:
...     f.read()
...
'Hello, my file\n'
>>> #In-memory file stream
... import io
>>> memfile = io.StringIO()
>>> print('Into the memory', file=memfile)
>>> memfile.getvalue()
'Into the memory\n'

The value output by the print function may be buffered. For example, if the value written does not have a newline, it may not be output immediately because it waits for additional data or a file to close. If you want the output result immediately, such as a logging tool, it may be better to give flush = True as an argument so that it can be written immediately at runtime.

$ cat counter.py
import time

def counter(n):
    for i in range(1, n+1):
        print(i, end=' ')  # <==End line with space instead of line break
        time.sleep(1)

counter(10)

$ #Since it will be buffered, it will be output at once after 10 seconds.
$ python3 counter.py
1 2 3 4 5 6 7 8 9 10 
$ cat counter2.py
import time

def counter2(n):
    for i in range(1, n+1):
        print(i, end=' ', flush=True)  # <== flush=Output is forcibly performed by setting it to True
        time.sleep(1)

counter2(10)

$ #Numbers are displayed every second
$ python3 counter2.py
1 2 3 4 5 6 7 8 9 10 

property()

You may want to implement getters, setters, and deleters for attributes to achieve encapsulation in object-oriented programming. property () provides a convenient way to make these easy to implement. property (official document)

The following implements public access to the private attribute _name using property.

$ cat book.py
class Book:

    def __init__(self, name):
        self._name = name

    def _get_name(self):
        """getter"""
        return self._name

    def _set_name(self, name):
        """setter"""
        self._name = name

    def _delete_name(self):
        """deleter"""
        del self._name

    name = property(_get_name, _set_name, _delete_name, 'This is name property')
>>> from book import Book
>>> book = Book('Clean Code')
>>> # getter
... book.name
'Clean Code'
>>> # deleter
... del book.name
>>> book.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/kotaro/book.py", line 8, in _get_name
    return self._name
AttributeError: 'Book' object has no attribute '_name'
>>> # setter
... book.name = 'The Pragmatic Programmer'
>>> book.name
'The Pragmatic Programmer'

The same process can be described using decorator notation as follows:

class Book:

    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        """This is name property"""
        return self._name

    @name.setter
    def name(self, name):
        """setter"""
        self._name = name

    @name.deleter
    def name(self):
        """deleter"""
        del self._name

Since the attribute given to the argument of property is a method, you can also write data conversion processing etc.

    @property
    def uppercase(self):
        """ uppercase book name"""
        return self._name.upper()
>>> book = Book('Clean Code')
>>> book.name
'Clean Code'
>>> book.uppercase
'CLEAN CODE'

range()

From the given argument, create an object of range type and return it. The range type takes three integer arguments, start, stop, and step, and expresses a sequence of integers that change the interval of [start, stop) in steps. If only one argument is given, start = 0`` step = 1 is set, and a sequence that increments from 0 to the argument value -1 is generated.

>>> r1 = range(10)
>>> r1
range(0, 10)
>>> list(r1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> #Can be accessed by index
... r1[3]
3
>>> r1[-2]
8
>>> #Can be sliced. A new range object with the specified range is created.
... r1[2:6]
range(2, 6)
>>> r1[:]
range(0, 10)
>>> r1[100:10000]
range(10, 10)
>>> r1[0:0]
range(0, 0)
>>> #Immutable sequence, so no changes
... r1[1] = 10000
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: 'range' object does not support item assignment
>>> #Given a negative value, but not an infinite loop
... list(range(-100))
[]
>>> #It must be a value that can be handled as an integer type.
... range(1.1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
>>> #For 2 arguments, start, stop
... list(range(3, 7))
[3, 4, 5, 6]
>>> #For 3 arguments, start, stop, step
... list(range(1, 10, 2))
[1, 3, 5, 7, 9]
>>> #Descending range
... list(range(10, -1, -1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> #Comparison is possible. Compare the contents of the sequence
... range(10) == range(10)
True
>>> range(10) == range(9)
False
>>> #Both are true because the sequence length is 0
... range(0) == range(-100)
True
>>> #The elements of the sequence are[1, 3, 5, 7, 9]So equivalent
... range(1, 10, 2) == range(1, 11, 2)
True

The range object is also often used in python to achieve a specified number of loops.

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

repr()

Generates a string of the passed object and returns it. If possible, pass it to eval () to make it a string that can be treated as the same object as the original object.

>>> #String
... repr('Hello')
"'Hello'"
>>> eval(repr('Hello'))
'Hello'
>>> #Numerical value
... repr(12345)
'12345'
>>> eval(repr(12345))
12345
>>> #list
... repr(['This', 'is', 'a', 'list', 'object'])
"['This', 'is', 'a', 'list', 'object']"
>>> eval(repr(['This', 'is', 'a', 'list', 'object']))
['This', 'is', 'a', 'list', 'object']
>>> # range
... repr(range(1, 1000))
'range(1, 1000)'

If a string that can be evaluated by eval () cannot be returned, the information of the object enclosed in <> is displayed.

>>> class MyClass1: pass
...
>>> repr(MyClass1())
'<__main__.MyClass1 object at 0x7f7659690690>'

You can control the return value of repr by implementing the __repr__ () method.

>>> class MyClass2:
...     def __repr__(self):
...         return self.__class__.__name__ + '()'
...
>>> repr(MyClass2())
'MyClass2()'
>>> eval(repr(MyClass2()))
MyClass2()

reversed()

Passing a sequence returns an iterator that returns the sequence in reverse order.

>>> reversed([1, 2, 3])
<list_reverseiterator object at 0x7f76596908d0>
>>> list(reversed([1, 2, 3]))
[3, 2, 1]
>>> reversed(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: reversed expected 1 arguments, got 3
>>> list(reversed(range(1, 10)))
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> import string
>>> for char in reversed(string.ascii_lowercase):
...     print(char, end=' ')
...
z y x w v u t s r q p o n m l k j i h g f e d c b a

Even in your own class, you can use reversed () by implementing __reversed__ ().

>>> class MySequence:
...     def __init__(self):
...         self._data = []
...     def append(self, value):
...         self._data.append(value)
...     def __iter__(self):
...         return iter(self._data)
...     def __reversed__(self):
...         return reversed(self._data)
...
>>> sequence = MySequence()
>>> sequence.append(1)
>>> sequence.append(3)
>>> sequence.append(5)
>>> list(sequence)
[1, 3, 5]
>>> reversed(sequence)
<list_reverseiterator object at 0x7f7659699610>
>>> list(reversed(sequence))
[5, 3, 1]

round()

If you give a number, it will be rounded to the specified decimal place.

>>> #If there is one argument, make it an integer
... round(1.1)
1
>>> round(1.5)
2
>>> #3rd place after the decimal point
... round(3.14159265, 3)
3.142
>>> #5th place after the decimal point
... round(2.71828182846, 5)
2.71828

Note that the built-in rounding rules are ** not rounded **.

Rounded to the closest multiple of 0 minus ndigits; if the two multiples are equally close, then the one to choose an even number (so, for example, round (0.5) and round (-0.5) are both) Rounded to 0, round (1.5) to 2). Official documentation #float

>>> #Note that it is not rounded
... round(0.5)
0
>>> round(-0.5)
0
>>> round(-1.5)
-2

Also note that the float type rounding process causes an error.

>>> # 2.2 instead of 68.Become 67
... round(2.675, 2)
2.67

If you want to perform decimal decimal operations more accurately, you should consider using the standard library Decimal type. There may be.

Continue to the 7th

Next time from set ()

Recommended Posts

Conquer 69 Python built-in functions 6th p ~ r
Python built-in functions ~ Zip ~
Wrap Python built-in functions
Built-in python
Python functions
Built-in functions
Correspondence between Python built-in functions and Rust
Python built-in object
Python built-in object
#Python basics (functions)
[Beginner] Python functions
Python Easy-to-use functions
Useful Python built-in functions that you use occasionally
Python basics: functions
Python's built-in functions
Python Beginner's Guide (Functions)
Python basic course (12 functions)
[Python] Memo about functions
# 4 [python] Basics of functions