Guidelines

λ¬Έμžμ—΄, 숫자 κ°„ μžλ£Œν˜• λ³€ν™˜ν•˜κΈ°

ν”„λ‘œκ·Έλž˜λ°μ„ ν•˜λ‹€ 보면 μˆ«μžμ™€ 문자λ₯Ό μ„œλ‘œ λ³€ν™˜ν•΄μ•Ό ν•˜λŠ” κ²½μš°κ°€ 자주 λ°œμƒν•©λ‹ˆλ‹€.

예λ₯Ό λ“€μ–΄ 숫자λ₯Ό κ³„μ‚°ν•œ ν›„ κ·Έ κ²°κ³Όλ₯Ό 화면에 λ³΄μ—¬μ£Όκ±°λ‚˜, μ‚¬μš©μžκ°€ μž…λ ₯ν•œ ν…μŠ€νŠΈλ₯Ό 숫자둜 λ°”κΎΈμ–΄ 계산해야 ν•˜λŠ” κ²½μš°κ°€ λ°œμƒν•  수 μžˆμŠ΅λ‹ˆλ‹€.

μ΄λ ‡κ²Œ ν•˜λ‚˜μ˜ μžλ£Œν˜•μ„ λ‹€λ₯Έ μžλ£Œν˜•μœΌλ‘œ λ³€ν™˜ν•˜λŠ” 것을 μžλ£Œν˜• λ³€ν™˜(Type Conversion)이라고 ν•©λ‹ˆλ‹€.


μ™œ μžλ£Œν˜•μ„ λ³€ν™˜ν•΄μ•Ό ν• κΉŒμš”?

ν”„λ‘œκ·Έλž˜λ°μ—μ„œ λͺ¨λ“  λ°μ΄ν„°λŠ” μžλ£Œν˜•(Data Type)을 κ°–κ³  μžˆμŠ΅λ‹ˆλ‹€.

예λ₯Ό λ“€μ–΄ 숫자 3κ³Ό 문자 "3"은 μ—„μ—°νžˆ λ‹€λ¦…λ‹ˆλ‹€.

μ„œλ‘œ λ‹€λ₯Έ μžλ£Œν˜•λΌλ¦¬λŠ” κ³„μ‚°ν•˜κ±°λ‚˜ 비ꡐ할 수 μ—†κΈ° λ•Œλ¬Έμ—, μ •ν™•ν•œ 연산을 μœ„ν•΄ μžλ£Œν˜•μ„ λ§žμΆ°μ•Ό ν•  λ•Œκ°€ μžˆμŠ΅λ‹ˆλ‹€.


문자λ₯Ό 숫자둜 λ°”κΎΈλŠ” int()와 float()

"5"와 같은 숫자 ν˜•νƒœμ˜ λ¬Έμžμ—΄μ„ 5와 같은 μˆ«μžν˜• λ°μ΄ν„°λ‘œ λ°”κΏ”μ•Ό ν•  λ•Œκ°€ μžˆμŠ΅λ‹ˆλ‹€.

예λ₯Ό λ“€μ–΄ "5" + 3κ³Ό 같이 λ¬Έμžμ—΄κ³Ό 숫자λ₯Ό λ”ν•˜λ €κ³  ν•˜λ©΄ 였λ₯˜κ°€ λ°œμƒν•©λ‹ˆλ‹€.

νŒŒμ΄μ¬μ—μ„œλŠ” μ΄λŸ¬ν•œ 경우λ₯Ό μ²˜λ¦¬ν•˜κΈ° μœ„ν•΄ int()와 float() ν•¨μˆ˜λ₯Ό ν™œμš©ν•΄ λ¬Έμžμ—΄μ„ 숫자둜 λ³€ν™˜ν•©λ‹ˆλ‹€.

λ¬Έμžμ—΄μ„ 숫자둜 λ³€ν™˜
age_str = "25" # λ¬Έμžμ—΄μ„ μ •μˆ˜λ‘œ λ³€ν™˜ age = int(age_str) # 30 좜λ ₯ print(age + 5) price_str = "19.99" # λ¬Έμžμ—΄μ„ μ‹€μˆ˜λ‘œ λ³€ν™˜ price = float(price_str) # 9.99 좜λ ₯ print(price - 10)

μœ„μ™€ 같이 int()λŠ” λ¬Έμžμ—΄μ„ μ •μˆ˜λ‘œ, float()λŠ” λ¬Έμžμ—΄μ„ μ‹€μˆ˜λ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€.


숫자λ₯Ό 문자둜 λ°”κΎΈλŠ” str()

λ°˜λŒ€λ‘œ μˆ«μžμ™€ 문자λ₯Ό μ—°κ²°ν•˜μ—¬ 보여주기 μœ„ν•΄, 숫자λ₯Ό λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•˜κ³  싢을 λ•Œλ„ μžˆμŠ΅λ‹ˆλ‹€.

숫자λ₯Ό λ¬Έμžμ—΄λ‘œ λ³€ν™˜
score = 90 # "Your score is "λŠ” λ¬Έμžμ—΄μ΄μ§€λ§Œ scoreλŠ” μˆ«μžμ΄λ―€λ‘œ 였λ₯˜ λ°œμƒ result_str = "Your score is " + score # TypeError: can only concatenate str (not "int") to str

μ΄λ ‡κ²Œ 숫자λ₯Ό λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•  λ•ŒλŠ” str() ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•©λ‹ˆλ‹€.

숫자λ₯Ό λ¬Έμžμ—΄λ‘œ λ³€ν™˜
score = 90 # 숫자λ₯Ό λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•˜μ—¬ μ—°κ²° result_str = "Your score is " + str(score) # Your score is 90 좜λ ₯ print(result_str)

이처럼 str() ν•¨μˆ˜λŠ” 숫자λ₯Ό λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•΄μ£Όλ©°, μ΄λ ‡κ²Œ λ³€ν™˜λœ λ¬Έμžμ—΄μ€ λ‹€λ₯Έ λ¬Έμžμ—΄κ³Ό μ‰½κ²Œ 결합될 수 μžˆμŠ΅λ‹ˆλ‹€.


λ³€ν™˜ν•  λ•Œ μ£Όμ˜ν•  점은?

μžλ£Œν˜•μ„ λ³€ν™˜ν•  λ•ŒλŠ” 항상 λ³€ν™˜ν•˜λ €λŠ” 값이 λ³€ν™˜λ  수 μžˆλŠ” ν˜•νƒœμΈμ§€ 확인해야 ν•©λ‹ˆλ‹€.

예λ₯Ό λ“€μ–΄, "abc" 같은 λ¬Έμžμ—΄μ„ int() ν•¨μˆ˜λ‘œ λ³€ν™˜ν•˜λ €κ³  ν•˜λ©΄ 였λ₯˜κ°€ λ°œμƒν•©λ‹ˆλ‹€.

잘λͺ»λœ λ³€ν™˜ μ˜ˆμ‹œ
text = "abc" # 였λ₯˜ λ°œμƒ: ValueError number = int(text)
Mission
0 / 1

νŒŒμ΄μ¬μ—μ„œ int() ν•¨μˆ˜λŠ” λ¬Έμžμ—΄μ„ μ •μˆ˜λ‘œ λ³€ν™˜ν•œλ‹€.

O
X

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result