본문 바로가기
개발/Python

[파이썬, Python] int 정리

by 꾀돌이 개발자 2022. 4. 5.
반응형

 

[ 파이썬 int 정리 ]

 

 

help(int) : int 도움말 보기

help(int)

'''
[출력값]

class int(object)
	int(x=0) -> integer
	int(x, base=10) -> integer
 
 	Convert a number or string to an integer, or return 0 if no arguments
 	are given.  If x is a number, return x.__int__().  For floating point
 	numbers, this truncates towards zero.
 
 	If x is not a number or if base is given, then x must be a string,
 	bytes, or bytearray instance representing an integer literal in the
 	given base.  The literal can be preceded by '+' or '-' and be surrounded
 	by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 	Base 0 means to interpret the base from the string as an integer literal.
'''

 

< explanation >

int() : 숫자형 혹은 문자열을 정수형으로 변환합니다.

 

< syntax of int() >

int(x=0, base=10)

  • x : 정수형으로 변환될 숫자형 혹은 문자열 객체, 기본값 = 0
  • base : x 가 몇 진수인지 0 혹은 2-36 범위에서 정의, 기본값 = 10

 


x : Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__().  For floating point numbers, this truncates towards zero.

  • int(x) 에서 x 로 정의된 숫자형 혹은 문자열 값을 정수값으로 변환합니다.
  • x 의 기본값은 0 입니다.
  • x 의 기본값이 0이기 때문에 int() 와 같이 인자를 부여하지 않은 경우 0 을 반환합니다.
  • int(x) 에서 x 가 숫자라면 정수값을 반환하며, 소숫점 아래 값들은 모두 0 으로 잘라냅니다. (반올림 X)
  • 반올림이 아니기 때문에 1.333 과 1.999 모두 1 로 출력됩니다.
# 숫자형, 문자열을 정수값으로 변환
print(int(1)) # 출력값 : 1
print(int('123')) # 출력값 : 123

# x 기본값 = 0
print(int()) # 출력값 : 0

# 소숫점 아래는 모두 버림
print(int(1.333)) # 출력값 : 1
print(int(1.999)) # 출력값 : 1

 


base : If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base.  The literal can be preceded by '+' or '-' and be surrounded by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.

  • base 는 x 값이 몇 진수인지 정의하는 인자이며, 0 그리고 2 부터 36 까지의 값을 갖습니다.
  • 단 base 가 정의되었다면 x 는 반드시 n진수로 표현가능한 string, bytes, bytearray 값으로 정의되어야 합니다.
  • 즉, base 가 정의되었다면 x 를 숫자형으로 정의할 수 없습니다.
  • base 의 기본값은 10 입니다. (x값이 10진수임을 의미함)
  • base 가 0 일 때에는 문자열을 그대로 정수로 변환합니다.
# base = 0, 2~36
print(int('101', 0)) # 출력값 : 101
print(int('101', 2)) # 출력값 : 5
print(int('102', 3)) # 출력값 : 11
print(int('10f', 16)) # 출력값 : 271
print(int('10f', 36)) # 출력값 : 1311
print(int('101', 1)) # 출력값 : ValueError: int() base must be >= 2 and <= 36, or 0
print(int('101', 37)) # 출력값 : ValueError: int() base must be >= 2 and <= 36, or 0

# n진수 표현 가능한 문자열 (숫자형 안 됨)
print(int('0b101', 2)) # 출력값 : 5
print(int('0o107', 8)) # 출력값 : 71
print(int('0x10f', 16)) # 출력값 : 271
print(int('0o107', 9)) # 출력값 : ValueError: invalid literal for int() with base 9: '0o107'
print(int('0x10f', 26)) # 출력값 : ValueError: invalid literal for int() with base 9: '0o107'
print(int(100, 10)) # 출력값 : TypeError: int() can't convert non-string with explicit base

# base 기본값 = 10
print(int('102')) # 출력값 : 102

 

 

반응형