Moment For Technology

How to use int in Python

Posted on June 23, 2022, 12:02 p.m. by Brittany Robinson
Category: The back-end Tag: python The back-end

0. Reference materials


1. A no-argument call to int

Int () with no arguments yields the integer 0.

num = int(a)print(type(num))
print(num)
"""
class 'int'
0
"""
Copy the code

2. Int Receives a number as a parameter

  • intTake an integer as an argument, there's nothing to say about it, you still get the original integer.
  • intWhen a floating-point number is received as an argument, the integer part of the number is intercepted and the intercepted integer is returned.
print(int(2.9))    # 2
print(int(2.1))    # 2
print(int(-2.9))   # 2 -
print(int(-2.1))   # 2 -
print(int(3.0))    # 3
Copy the code

Note: Int has no rounding, it does truncation, truncation, truncation!


3. Int accepts a string as an argument: type conversion

As we all know, the int function converts a string to an integer, and this is its most common use:

s = input('Please enter an integer:')
print(type(s))
"""
class 'str'
"""

num = int(s)
print(type(num))
"""
class 'int'
"""
Copy the code

Note: Int is technically a class, not a function, although it does not begin with a capital letter.

If s is a floating point string, such as '-3.14', casting directly to int will raise ValueError, as shown below:

s = '3.14'
num = int(s)
"" ValueError: invalid Literal for int() with base 10: '-3.14' ""
Copy the code

If you want to convert a string as a floating-point number to an integer, you need to convert the string to a floating-point number using float, and then use int to intercept the floating-point number as an integer, as follows:

s = '3.14'
num = int(float(s))
print(f'num = {num}')
"""
num = -3
"""
Copy the code

4. Int is used for base conversion

So far, we've covered the common uses of int. Next, we'll cover the less common uses of int, which can convert a 2-to-36-base string, bytes, or bytearray instance to the corresponding 10-base integer. The call is of the form int(x, base=10), where x is an instance of a string, byte string, or byte array.

Parameters that

  • parameterxMust be a valid integer literalinteger literal.

Integer literals can be preceded by signs, but there can be no space between signs and numbers. Integer literals can have any amount of white space at either end, including space, tabs, newlines, and so on. A-z or A-z are numbers from 10 to 35, respectively. Binary digits can be prefixed with 0b or 0b, octal digits can be prefixed with 0O or 0O, hexadecimal digits can be prefixed with 0x or 0x, and prefixes are optional.

  • baseThe default is10, can also be taken0As well as236, not a1Because there is no1Into the system.

Base 0 is parsed as code literal, meaning that only 2, 8, 10, and hexadecimal numeric representations can be converted to base 10. For the 2, 8, and 16 bases, you must specify the prefix of the corresponding base; otherwise, the system will parse in base 10.

Default:base=10

x = '6'
num1 = int(x)
num2 = int(x, 10)
print(num1)
print(num2)
"" "6 6 "" "
Copy the code

Other base conversion10Into the system

x = '10'
num1 = int(x, 2)
num2 = int(x, 8)
num3 = int(x, 16)
print(num1)
print(num2)
print(num3)
""" 2 8 16 ""

x = 'z'
num3 = int(x, 36)
print(num3)
35 "" "" ""
Copy the code

Integer literals with signs and Spaces

# with a plus sign
x = '+a0'
num = int(x, 16)
print(num)
"" "160 ", ""

# is subtractive
x = '-a0'
num = int(x, 16)
print(num)
"" "- 160 "" "

# Blank at both ends
x = ' \t +a0\r\n '
num = int(x, 16)
print(num)
"" "160 ", ""
Copy the code

base=0Is parsed directly according to the code literal

x = '10'
num = int(x, 0)
print(num)
"" "10 "" "

x = '0b10'
num = int(x, 0)
print(num)
"""
2
"""

x = '0o10'
num = int(x, 0)
print(num)
"" "8 "" "

x = '0x10'
num = int(x, 0)
print(num)
16 "" "" ""
Copy the code

5. Version features

3.4Version changes

  • ifbaseParameter is notintClass, then it will be calledbase.__index__Method, which returns an integer supplybaseParameter usage.
  • The previous version calledbase.__int__Rather thanbase.__index__.

3.6Version changes

  • Code literal (code literalUnderline is allowed in_To group numbers.

3.7Version changes

  • xThis is now a mandatory position parameterpositional-only parameter.

Note: x cannot pass through x=... This keyword argument is specified in the form of a keyword argument. Here is my experiment in Python 3.6, which shows that version 3.6 still works. However, Python 3.7 will report an error!

# Python 3.6
x = 'a'
num = int(x=x, base=16)
print(num)
"" "10 "" "
# Turn it over
x = 'a'
num = int(base=16, x=x)
print(num)
"" "10 "" "

# Python 3.7 will report an error
 x = 'a'
 num = int(x=x, base=16)
Traceback (most recent call last):
  File "stdin", line 1.in module
TypeError: 'x' is an invalid keyword argument for int(a)Copy the code

Completed in 2019.5.2

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.