當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python int()用法及代碼示例


Python和Python3中的int()函數將給定基數的數字轉換為十進製。

用法:

int(string, base)

參數:


string: consists of 1's and 0's
base: (integer value) base of the number.

返回值:

Returns an integer value, which is equivalent 
of binary string in the given base. 

錯誤:

TypeError:Returns TypeError when any data type other 
than string or integer is passed in its equivalent position.

代碼1:

# Python3 program for implementation  
# of int() function  
num = 13
  
String = '187'
  
# Stores the result value of 
# binary "187" and num addition  
result_1 = int(String) + num  
print("int('187') + 13 = ", result_1, "\n") 
  
# Example_2 
str = '100'
  
print("int('100') with base 2 = ", int(str, 2)) 
print("int('100') with base 4 = ", int(str, 4)) 
print("int('100') with base 8 = ", int(str, 8)) 
print("int('100') with base 16 = ", int(str, 16))

輸出:

int('187') + 13 =  200 

int('100') with base 2 =  4
int('100') with base 4 =  16
int('100') with base 8 =  64
int('100') with base 16 =  256

代碼2:

# Python3 program for implementation  
# of int() function  
  
# "111" taken as the binary string  
binaryString = "111"
  
# Stores the equivalent decimal  
# value of binary "111"  
Decimal = int(binaryString, 2)  
  
print("Decimal equivalent of binary 111 is", Decimal)  
  
  
# "101" taken as the binary string 
binaryString = "101"
  
# Stores the equivalent decimal  
# value of binary "101"  
Octal = int(binaryString, 8)  
  
print("Octal equivalent of binary 101 is", Octal)

輸出:

Decimal equivalent of binary 111 is 7
Octal equivalent of binary 101 is 65

代碼3:演示TypeError的程序。

# Python3 program to demonstrate   
# error of int() function  
  
  
# when the binary number is not   
# stored in as string  
binaryString = 111
  
# it returns an error for passing an   
# integer in place of string  
decimal = int(binaryString, 2)  
  
print(decimal)

輸出:

Traceback (most recent call last):
  File "/home/d87cec4c0c33aad3bb6187858b40b734.py", line 8, in 
    decimal = int(binaryString, 2)  
TypeError:int() can't convert non-string with explicit base

應用:
它用於所有標準轉換。例如,將二進製轉換為十進製,將二進製轉換為八進製,將二進製轉換為十六進製。



相關用法


注:本文由純淨天空篩選整理自Striver大神的英文原創作品 Python | int() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。