Data Science Explorer

[Basic Grammar] Python Casting 본문

Python

[Basic Grammar] Python Casting

grace21110 2023. 10. 20. 18:22
반응형
  • Type Conversion 

You can convert from one type to another with th int(), float(), and complex. 

 

Example 

Convert from one type to another. 

x = 1    # int
y = 2.8  # float
z = 1j   # complex

#convert from int to float:
a = float(x)

#convert from float to int:
b = int(y)

#convert from int to complex:
c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

 

  • Specify a variable type 
  • Integers: 
x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
  • Floats:
x = float(1)     # x will be 1.0
y = float(2.8)   # y will be 2.8
z = float("3")   # z will be 3.0
w = float("4.2") # w will be 4.2
  • Strings:
x = str("s1") # x will be 's1'
y = str(2)    # y will be '2'
z = str(3.0)  # z will be '3.0'

 

'Python' 카테고리의 다른 글

[Basic Grammar] Python While Loops  (0) 2023.10.20
[Basic Grammar] Python If ... Else  (0) 2023.10.20
[Basic Grammar] Python Numbers  (0) 2023.10.20
[Basic Grammar] Python Data Types  (0) 2023.10.20
[Basic Grammar] Python Variables: Output Variables  (0) 2023.10.19