반응형
파이썬 숫자형 자료형 완벽 가이드
파이썬에서 숫자형 자료형은 프로그래밍의 기본이 되는 핵심 요소입니다. 이 가이드에서는 숫자형 자료형의 모든 것을 상세히 다루어 보겠습니다.
숫자형 자료형의 종류와 특징
파이썬의 숫자형은 크게 네 가지 종류로 분류됩니다:
자료형표현 방법사용 예시
정수형 | 일반적인 정수 | 456, -789, 0 |
실수형 | 소수점을 포함한 수 | 67.89, -234.56, 2.7e5 |
8진수 | 0o 또는 0O로 시작 | 0o42, 0O17 |
16진수 | 0x 또는 0X로 시작 | 0x3F, 0XFF |
정수형 자료형 심화 학습
정수형은 양수, 음수, 그리고 0을 포함하는 모든 자연수를 표현합니다. 파이썬의 정수형은 다른 언어와 달리 크기 제한이 없어 매우 큰 수도 처리할 수 있습니다.
python
# 정수형 변수 생성 및 활용
number1 = 456
number2 = -789
zero_value = 0
print(f"양의 정수: {number1}")
print(f"음의 정수: {number2}")
print(f"영: {zero_value}")
# 매우 큰 정수도 처리 가능
big_number = 12345678901234567890123456789
print(f"큰 정수: {big_number}")
실수형 자료형과 과학적 표기법
실수형은 소수점이 포함된 숫자를 다룹니다. 파이썬에서는 일반적인 소수점 표기법뿐만 아니라 과학적 표기법도 지원합니다.
python
# 일반적인 실수 표현
decimal1 = 3.14159
decimal2 = -0.005
# 과학적 표기법 (지수 표현)
scientific1 = 2.5e3 # 2.5 × 10³ = 2500
scientific2 = 1.2E-4 # 1.2 × 10⁻⁴ = 0.00012
scientific3 = 6.67e-11 # 중력상수와 유사한 값
print(f"파이: {decimal1}")
print(f"작은 실수: {decimal2}")
print(f"과학적 표기법 1: {scientific1}")
print(f"과학적 표기법 2: {scientific2}")
print(f"과학적 표기법 3: {scientific3}")
8진수와 16진수 체계
컴퓨터 시스템에서는 8진수와 16진수가 자주 사용됩니다. 파이썬에서는 이러한 진법을 쉽게 다룰 수 있습니다.
python
# 8진수 (0o 또는 0O로 시작)
octal1 = 0o25 # 8진수 25 = 2×8¹ + 5×8⁰ = 21
octal2 = 0O177 # 8진수 177 = 1×8² + 7×8¹ + 7×8⁰ = 127
# 16진수 (0x 또는 0X로 시작)
hex1 = 0x1A # 16진수 1A = 1×16¹ + 10×16⁰ = 26
hex2 = 0XFF # 16진수 FF = 15×16¹ + 15×16⁰ = 255
hex3 = 0xDEAD # 16진수 DEAD = 13×16³ + 14×16² + 10×16¹ + 13×16⁰
print(f"8진수 0o25의 10진수 값: {octal1}")
print(f"8진수 0O177의 10진수 값: {octal2}")
print(f"16진수 0x1A의 10진수 값: {hex1}")
print(f"16진수 0XFF의 10진수 값: {hex2}")
print(f"16진수 0xDEAD의 10진수 값: {hex3}")
반응형
숫자형 연산자 완전 분석
기본 사칙연산
파이썬의 사칙연산은 직관적이고 강력합니다:
python
x = 15
y = 4
# 기본 사칙연산
addition = x + y # 덧셈: 19
subtraction = x - y # 뺄셈: 11
multiplication = x * y # 곱셈: 60
division = x / y # 나눗셈: 3.75
print(f"{x} + {y} = {addition}")
print(f"{x} - {y} = {subtraction}")
print(f"{x} * {y} = {multiplication}")
print(f"{x} / {y} = {division}")
고급 연산자들
python
# 거듭제곱 연산자 (**)
base = 2
exponent = 8
power_result = base ** exponent # 2⁸ = 256
# 나머지 연산자 (%)
dividend = 17
divisor = 5
remainder = dividend % divisor # 17을 5로 나눈 나머지: 2
# 몫 연산자 (//)
quotient = dividend // divisor # 17을 5로 나눈 몫: 3
print(f"{base}의 {exponent}제곱: {power_result}")
print(f"{dividend} % {divisor} = {remainder}")
print(f"{dividend} // {divisor} = {quotient}")
복합 대입 연산자 활용
복합 대입 연산자는 코드를 간결하게 만들어 줍니다:
python
# 복합 대입 연산자 예제
counter = 10
counter += 5 # counter = counter + 5
print(f"5 더한 후: {counter}")
counter -= 3 # counter = counter - 3
print(f"3 뺀 후: {counter}")
counter *= 2 # counter = counter * 2
print(f"2 곱한 후: {counter}")
counter /= 4 # counter = counter / 4
print(f"4로 나눈 후: {counter}")
counter **= 2 # counter = counter ** 2
print(f"제곱한 후: {counter}")
counter %= 7 # counter = counter % 7
print(f"7로 나눈 나머지: {counter}")
실전 예제: 간단한 계산기 프로그램
숫자형 자료형과 연산자를 활용한 실용적인 예제를 살펴보겠습니다:
python
class SimpleCalculator:
"""간단한 계산기 클래스"""
def __init__(self):
print("=== 파이썬 계산기 ===")
print("사용 가능한 연산: +, -, *, /, **, %, //")
def calculate(self, num1, operator, num2):
"""두 숫자와 연산자를 받아 계산 수행"""
try:
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
if num2 == 0:
return "오류: 0으로 나눌 수 없습니다"
return num1 / num2
elif operator == '**':
return num1 ** num2
elif operator == '%':
if num2 == 0:
return "오류: 0으로 나눌 수 없습니다"
return num1 % num2
elif operator == '//':
if num2 == 0:
return "오류: 0으로 나눌 수 없습니다"
return num1 // num2
else:
return "오류: 지원하지 않는 연산자입니다"
except Exception as e:
return f"계산 오류: {e}"
def run_examples(self):
"""다양한 계산 예제 실행"""
examples = [
(25, '+', 17),
(100, '-', 37),
(12, '*', 8),
(144, '/', 12),
(3, '**', 4),
(23, '%', 7),
(47, '//', 6)
]
for num1, op, num2 in examples:
result = self.calculate(num1, op, num2)
print(f"{num1} {op} {num2} = {result}")
# 계산기 실행
calc = SimpleCalculator()
calc.run_examples()
실전 예제: 숫자 맞추기 게임
python
import random
class NumberGuessingGame:
"""숫자 맞추기 게임 클래스"""
def __init__(self, min_num=1, max_num=100):
self.min_num = min_num
self.max_num = max_num
self.secret_number = random.randint(min_num, max_num)
self.attempts = 0
self.max_attempts = 7
def play(self):
"""게임 실행 메서드"""
print(f"=== 숫자 맞추기 게임 ===")
print(f"{self.min_num}부터 {self.max_num} 사이의 숫자를 맞춰보세요!")
print(f"최대 {self.max_attempts}번의 기회가 있습니다.")
while self.attempts < self.max_attempts:
try:
# 사용자 입력 받기 (실제 게임에서는 input() 사용)
# 여기서는 예제를 위해 임의의 추측값들을 사용
sample_guesses = [50, 25, 75, 37, 62, 44, 56]
if self.attempts < len(sample_guesses):
guess = sample_guesses[self.attempts]
else:
guess = random.randint(self.min_num, self.max_num)
print(f"\n시도 {self.attempts + 1}: {guess}")
self.attempts += 1
# 추측값과 비밀 숫자 비교
if guess == self.secret_number:
print(f"🎉 정답입니다! {self.attempts}번 만에 맞추셨네요!")
self.show_statistics()
break
elif guess < self.secret_number:
print("📈 더 큰 숫자입니다!")
remaining = self.max_attempts - self.attempts
if remaining > 0:
print(f"남은 기회: {remaining}번")
else:
print("📉 더 작은 숫자입니다!")
remaining = self.max_attempts - self.attempts
if remaining > 0:
print(f"남은 기회: {remaining}번")
except ValueError:
print("올바른 숫자를 입력해주세요!")
continue
if self.attempts >= self.max_attempts:
print(f"\n💔 게임 오버! 정답은 {self.secret_number}였습니다.")
self.show_statistics()
def show_statistics(self):
"""게임 통계 표시"""
success_rate = (1 / self.attempts) * 100 if self.attempts > 0 else 0
print(f"\n=== 게임 통계 ===")
print(f"총 시도 횟수: {self.attempts}")
print(f"성공률: {success_rate:.1f}%")
print(f"난이도 범위: {self.min_num} ~ {self.max_num}")
# 게임 실행 예제
game = NumberGuessingGame(1, 100)
# 실제 비밀 번호를 56으로 설정 (예제용)
game.secret_number = 56
game.play()
고급 숫자 처리 기법
python
import math
class AdvancedNumberOperations:
"""고급 숫자 연산 클래스"""
@staticmethod
def number_properties(num):
"""숫자의 다양한 속성 분석"""
properties = {}
# 기본 속성
properties['원본값'] = num
properties['절댓값'] = abs(num)
properties['제곱'] = num ** 2
properties['세제곱'] = num ** 3
# 진법 변환
if isinstance(num, int) and num >= 0:
properties['2진수'] = bin(num)
properties['8진수'] = oct(num)
properties['16진수'] = hex(num)
# 수학적 함수들
if num > 0:
properties['제곱근'] = math.sqrt(num)
properties['자연로그'] = math.log(num)
properties['상용로그'] = math.log10(num)
return properties
@staticmethod
def fibonacci_sequence(n):
"""피보나치 수열 생성"""
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
sequence = [0, 1]
for i in range(2, n):
next_num = sequence[i-1] + sequence[i-2]
sequence.append(next_num)
return sequence
@staticmethod
def prime_checker(num):
"""소수 판별 함수"""
if num < 2:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0:
return False
return True
@staticmethod
def factorial(n):
"""팩토리얼 계산"""
if n < 0:
return None
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result
# 고급 연산 예제 실행
advanced_ops = AdvancedNumberOperations()
# 숫자 속성 분석
test_number = 144
properties = advanced_ops.number_properties(test_number)
print(f"=== 숫자 {test_number}의 속성 ===")
for key, value in properties.items():
print(f"{key}: {value}")
print("\n=== 피보나치 수열 (첫 15개) ===")
fib_sequence = advanced_ops.fibonacci_sequence(15)
print(fib_sequence)
print("\n=== 소수 판별 테스트 ===")
test_numbers = [17, 18, 19, 20, 21, 22, 23]
for num in test_numbers:
is_prime = advanced_ops.prime_checker(num)
print(f"{num}: {'소수' if is_prime else '합성수'}")
print("\n=== 팩토리얼 계산 ===")
for i in range(1, 8):
factorial_result = advanced_ops.factorial(i)
print(f"{i}! = {factorial_result}")
데이터 타입 변환과 검증
python
class NumberTypeConverter:
"""숫자 타입 변환 및 검증 클래스"""
@staticmethod
def safe_convert_to_int(value):
"""안전한 정수 변환"""
try:
if isinstance(value, str):
# 공백 제거
value = value.strip()
# 16진수 처리
if value.startswith(('0x', '0X')):
return int(value, 16)
# 8진수 처리
if value.startswith(('0o', '0O')):
return int(value, 8)
# 2진수 처리
if value.startswith(('0b', '0B')):
return int(value, 2)
return int(float(value))
except (ValueError, TypeError):
return None
@staticmethod
def safe_convert_to_float(value):
"""안전한 실수 변환"""
try:
return float(value)
except (ValueError, TypeError):
return None
@staticmethod
def analyze_number_string(s):
"""숫자 문자열 분석"""
analysis = {
'원본': s,
'정수_변환_가능': False,
'실수_변환_가능': False,
'정수값': None,
'실수값': None,
'타입': None
}
# 정수 변환 시도
int_result = NumberTypeConverter.safe_convert_to_int(s)
if int_result is not None:
analysis['정수_변환_가능'] = True
analysis['정수값'] = int_result
# 실수 변환 시도
float_result = NumberTypeConverter.safe_convert_to_float(s)
if float_result is not None:
analysis['실수_변환_가능'] = True
analysis['실수값'] = float_result
# 타입 결정
if analysis['정수_변환_가능'] and analysis['실수_변환_가능']:
if analysis['정수값'] == analysis['실수값']:
analysis['타입'] = 'integer'
else:
analysis['타입'] = 'float'
elif analysis['실수_변환_가능']:
analysis['타입'] = 'float'
else:
analysis['타입'] = 'string'
return analysis
# 변환 테스트 예제
converter = NumberTypeConverter()
test_strings = [
"123",
"45.67",
"0x1F",
"0o77",
"0b1010",
"2.5e3",
"invalid",
" 89 ",
"-123.45"
]
print("=== 숫자 문자열 변환 테스트 ===")
for test_str in test_strings:
result = converter.analyze_number_string(test_str)
print(f"\n입력: '{test_str}'")
print(f"타입: {result['타입']}")
if result['정수값'] is not None:
print(f"정수값: {result['정수값']}")
if result['실수값'] is not None:
print(f"실수값: {result['실수값']}")
이 가이드를 통해 파이썬의 숫자형 자료형에 대한 포괄적인 이해를 얻으실 수 있을 것입니다. 각 예제를 직접 실행해보며 숫자형 자료형의 다양한 활용법을 익혀보시기 바랍니다.
반응형
'파이썬' 카테고리의 다른 글
4. 파이썬 튜플 기초부터 고급 활용까지 (0) | 2025.05.23 |
---|---|
3. 예제와 함께하는 초보의 파이썬 리스트 완전 정복 가이드 (0) | 2025.05.23 |
2. 예제로 공부하는 파이썬 문자열 완전 정복 가이드 | 한번에 끝내는 문자열. (0) | 2025.05.23 |