Data Type Conversions

Data Type Conversions

Here’s a comprehensive overview of data type conversions in Python, covering both implicit and explicit conversions.

Implicit Type Conversion

Python automatically converts one data type to another without user intervention. This usually happens when you mix different data types in an operation.

Examples:

  1. Integer to Float

    x = 10
    y = 10.5
    z = x + y
    print(z)  # Output: 20.5
    print(type(z))  # Output: <class 'float'>
    
  2. Integer to Complex

    x = 10
    y = 2 + 3j
    z = x + y
    print(z)  # Output: (12+3j)
    print(type(z))  # Output: <class 'complex'>
    

Explicit Type Conversion

This requires the user to manually convert one data type to another using built-in functions.

Common Conversions:

  1. String to Integer

    s = "100"
    num = int(s)
    print(num)  # Output: 100
    print(type(num))  # Output: <class 'int'>
    
  2. Integer to Float

    i = 10
    f = float(i)
    print(f)  # Output: 10.0
    print(type(f))  # Output: <class 'float'>
    
  3. String to Float

    s = "10.5"
    f = float(s)
    print(f)  # Output: 10.5
    print(type(f))  # Output: <class 'float'>
    
  4. Integer to String

    i = 10
    s = str(i)
    print(s)  # Output: "10"
    print(type(s))  # Output: <class 'str'>
    
  5. Character to Integer (ASCII)

    c = 'A'
    ascii_val = ord(c)
    print(ascii_val)  # Output: 65
    print(type(ascii_val))  # Output: <class 'int'>
    
  6. Integer to Hexadecimal String

    i = 255
    hex_val = hex(i)
    print(hex_val)  # Output: "0xff"
    print(type(hex_val))  # Output: <class 'str'>
    
  7. Integer to Octal String

    i = 10
    oct_val = oct(i)
    print(oct_val)  # Output: "0o12"
    print(type(oct_val))  # Output: <class 'str'>
    
  8. Float to Integer

    f = 10.5
    i = int(f)
    print(i)  # Output: 10
    print(type(i))  # Output: <class 'int'>
    
  9. Boolean to Integer

    b = True
    i = int(b)
    print(i)  # Output: 1
    print(type(i))  # Output: <class 'int'>
    
  10. Integer to Boolean

    i = 0
    b = bool(i)
    print(b)  # Output: False
    print(type(b))  # Output: <class 'bool'>
    


Comments

Popular posts from this blog

Error Detection in Data Link Layer

Transmission impairments – Attenuation, Distortion, Noise. Multiplexing – Frequency division, Time division, Wavelength division

DSA 3 DAYS Part 1