Python Notes – Type Conversion, Casting &
Random Numbers
Type Conversion
Use int(), float(), complex() to convert data types.
Example:
x=1 (int), y=2.8 (float), z=1j (complex)
a=float(x), b=int(y), c=complex(x)
Important: Complex numbers cannot be converted to int or float.
Random Numbers
Import random module and use [Link](1,10) to generate a random number from 1 to 9.
Casting
int() - Converts to integer.
float() - Converts to float.
str() - Converts to string.
Examples
int(2.8)=2
float(3)=3.0
str(3.0)='3.0'
Key Points
• int() removes decimals (does not round).
• float() converts integers/strings to float.
• complex() creates complex numbers.
• str() converts values to strings.
• [Link](start, stop) includes start and excludes stop.