Memo # 4 for Python beginners to read "Detailed Python Grammar"

Back number

-Memo # 1 for Python beginners to read "Detailed explanation of Python grammar" -Memo # 2 for Python beginners to read "Detailed Explanation of Python Grammar" -Memo # 3 for Python beginners to read "Detailed explanation of Python grammar"

is


#Returns true for the same object
>>> a = b = [1, 2, 3]
>>> a is b
True

#In this case it is a different object so the result of is is false
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
>>> a == b
True

#The result of is is judged by the id of the object
>>> id(a)
4353816328
>>> id(b)
4353060616

>>> a = b = [1, 2, 3]
>>> id(a)
4353816392
>>> id(b)
4353816392

Conditional operator (ternary operator)


>>> x = 1
>>> 100 if x == 1 else 200
100

>>> x = 2
>>> 100 if x == 1 else 200
200
>>> x == 1 and 100 or 200   #Rewriting by and and or
200

Automatic type conversion of numerical calculation results


>>> 1 + 1.0  #integer+Floating point number
2.0          #The result is a floating point number
>>> 1 + 1j   #integer+Complex number
(1+1j)       #The result is a complex number

Numerical calculation method


>>> divmod(20, 6)
(3, 2)  #The quotient and remainder of the division are returned as tuples. It looks convenient.

>>> pow(3, 4)     # 3 **Same as 4
81
>>> pow(3, 4, 5)  # 3 ** 4 %Same as 5, but faster
1

int([x, byte])


#Returns 0 with no arguments
>>> int()
0

#If you pass a floating point number, it will be rounded to 0
>>> int(10.5)
10
>>> int(-10.5)
-10

#Cardinal number can be specified when passing a character string
>>> int('100')    #Decimal number when radix is omitted
100
>>> int('100', 2)
4
>>> int('100', 8)
64
>>> int('100', 10)
100
>>> int('100', 16)
256

#Convert as an integer literal, where the radix is 0
>>> int('100', 0)
100
>>> int('0b100', 0)
4
>>> int('0o100', 0)
64
>>> int('0x100', 0)
256

#Converts any character that is considered a number in the Unicode character database
>>> int('V', 32)
31
>>> int('100', 2)
4

Binary → integer object


>>> int.from_bytes(b'\x00\xff', byteorder = 'big')  #Since it is a class method, call it as an int type method
255
# signed =True to convert the byte sequence to a 2's complement signed integer
>>> int.from_bytes(b'\xfe\xff\xff\xff', byteorder = 'little', signed=True)
-2

Integer object method


#Get byte sequence of integer values
>>> (255).to_bytes(2, byteorder = 'big')
b'\x00\xff'
#Converted as 2's complement
>>> (-2).to_bytes(4, 'little', signed = True)
b'\xfe\xff\xff\xff'

#Returns the number of bits required to convert a number to a binary number (sign bit not included)
>>> (100000000).bit_length()
27

Logical value type


#Derived from an integer type, True is actually an integer 1 and False is an integer 0.
>>> int(True)
1
>>> int(False)
0

#Can perform the same operations as ordinary integers
>>> True + False
1
>>> True * False
0
>>> False - 1
-1
>>> True + 1
2
>>> True / 2
0.5

Logical value object


#Logical value object is a bool type object
#There is always only one True object and one False object each
>>> bool(0)
False
>>> bool(1)
True
>>> bool([100])
True
>>> bool([])
False
>>> bool()
False

Bit inversion


# ~x is-1*(x+1)Returns an integer value that is (Python does not perform bit operations internally)
>>> ~5
-6
>>> ~(-6)
5
>>> '{:08b}'.format(5 & 0xff)
'00000101'
>>> '{:08b}'.format(-6 & 0xff)
'11111010'

Infinity / non-number in floating point arithmetic


#If the floating point value is greater than the valid range
>>> 1e200 * 1e200
inf  #Infinity is displayed as inf
>>> -1e200 * 1e200
-inf

#The result is a non-number (Not A Number), such as when operating with an infinite value.:When it becomes NaN)
>>> 0 * 1e1000
nan

#The value is inf,nan floating point number is float()Create with method
>>> float('nan')        #Non-number
nan
>>> float('inf')        #Infinity
inf
>>> float('-inf')       #Negative infinity
-inf
>>> float('infinity')   # 'infinity'Infinite
inf

Floating point object methods


#Returns a tuple of two integer values whose ratio is the same as the value of the object. The second value is always positive.
>>> (0.5).as_integer_ratio()
(1, 2)
>>> (-2.5).as_integer_ratio()
(-5, 2)

# inf,The following exception is thrown for nan
>>> float('inf').as_integer_ratio()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Cannot pass infinity to float.as_integer_ratio.

>>> float('nan').as_integer_ratio()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Cannot pass NaN to float.as_integer_ratio.


#Output the value of the object as a character string in hexadecimal format
# [sign]['0x']integer['.'fraction]['p'exponent]Created in format
>>> 1.0.hex()
'0x1.0000000000000p+0'


#Returns True if the value has a decimal point of zero and is an integer value other than inf or nan
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
>>> float('inf').is_integer()
False
>>> float('nan').is_integer()
False

Decimal floating point number


#Calculations with floating point numbers are generally inaccurate
>>> 0.3 - 0.2
0.09999999999999998

#Python provides a decimal module for decimal floating point arithmetic
#Unlike float type calculations, all calculations are done by software, so performance is degraded.
>>> import decimal
>>> print(decimal.Decimal('0.3') - decimal.Decimal('0.2'))
0.1

# inf, nan
>>> from decimal import Decimal
>>> Decimal('inf')
Decimal('Infinity')

>>> Decimal('nan') + 1   #The result of the operation with nan is nan,
Decimal('NaN')
>>> Decimal('sNaN') + 1  #An exception can be raised by using a special value called signaling NaN.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

Recommended Posts

Memo # 4 for Python beginners to read "Detailed Python Grammar"
Memo # 3 for Python beginners to read "Detailed Python Grammar"
Memo # 1 for Python beginners to read "Detailed Python Grammar"
Memo # 2 for Python beginners to read "Detailed Python Grammar"
Memo # 7 for Python beginners to read "Detailed Python Grammar"
Memo # 6 for Python beginners to read "Detailed Python Grammar"
Memo # 5 for Python beginners to read "Detailed Python Grammar"
Basic Python grammar for beginners
~ Tips for beginners to Python ③ ~
Memo to ask for KPI with python
Beginners read "Introduction to TensorFlow 2.0 for Experts"
[Python] Read images with OpenCV (for beginners)
The fastest way for beginners to master Python
For beginners to build an Anaconda environment. (Memo)
Python for super beginners Python for super beginners # Easy to get angry
python textbook for beginners
Try to calculate RPN in Python (for beginners)
Python basic grammar memo
Introduction to Programming (Python) TA Tendency for beginners
How to make Python faster for beginners [numpy]
[For beginners] How to study programming Private memo
OpenCV for Python beginners
[For beginners] How to use say command in python!
How to convert Python # type for Python super beginners: str
[For beginners] How to study Python3 data analysis exam
[For beginners] Learn basic Python grammar for free in 5 hours!
Python # How to check type and type for super beginners
Python memo (for myself): Array
Learning flow for Python beginners
Python Basic Grammar Memo (Part 1)
Python code memo for yourself
Python3 environment construction (for beginners)
3 Reasons Beginners to Start Python
Python basic grammar (miscellaneous) Memo (3)
Python #function 2 for super beginners
Python basic grammar (miscellaneous) Memo (2)
100 Pandas knocks for Python beginners
[Python] Sample code for Python grammar
Python for super beginners Python #functions 1
Python #list for super beginners
Python basic grammar (miscellaneous) Memo (4)
Introduction to Python For, While
Tips for Python beginners to use Scikit-image examples for themselves 4 Use GUI
[For beginners] How to read Numerai's HP + Submit + Convenient links
[R] [Python] Memo to read multiple csv files in multiple zip files
How to learn TensorFlow for liberal arts and Python beginners
Tips for coding short and easy to read in Python
How to convert Python # type for Python super beginners: int, float
[For beginners] Script within 10 lines (4. Connection from python to sqlite3)
Tips for Python beginners to use the Scikit-image example for themselves
[Python] Introduction to graph creation using coronavirus data [For beginners]
Python Exercise for Beginners # 2 [for Statement / While Statement]
Minimum grammar notes for writing Python
Python for super beginners Python # dictionary type 1 for super beginners
Python #index for super beginners, slices
<For beginners> python library <For machine learning>
Python #len function for super beginners
Beginners use Python for web scraping (1)
[Nanonets] How to post Memo [Python]
Run unittests in Python (for beginners)
Beginners use Python for web scraping (4) ―― 1