Class 11:Python Casting

Python Casting

Conversion between data types

Casting in python is done using constructor functions:

int() – constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)

float() – constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)

str() – constructs a string from a wide variety of data types, including strings, integer literals and float literals

We can convert between different data types by using different type conversion functions like int(), float(), str() etc.

#Integers:

x = int(10)   # x will be 10
y = int(4.8) # y will be 4
z = int("3") # z will be 3
print(x)
print(y)
print(z)
10
4
3
>>> 
#Floats:

x = float(1)     # x will be 1.0
y = float(2.9)   # y will be 2.9
z = float("3")   # z will be 3.0
w = float("4.7") # w will be 4.7
print(x)
print(y)
print(z)
print(w)
1.0
2.9
3.0
4.7
>>> 
#Strings:

x = str("c1") # x will be 'c1'
y = str(2)    # y will be '2'
z = str(3.0)  # z will be '3.0'
print(x)
print(y)
print(z)
c1
2
3.0
>>> 

Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10

>>> int(10.6)
10
>>> int(-10.6)
-10

Conversion to and from string must contain compatible values.
>>> float(‘2.5’)
2.5
>>> str(25)
’25’
>>> int(‘1p’)
#error

>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
#error