Type Casting

  • It refers to the process of converting one data type into another.

Types of Type Casting in Python:

Implicit or Auto Type Casting:

    • Python automatically converts one data type to another without explicit instructions from the programmer.
    • This usually happens when operations between different data types are performed.
    • Example
# Autotypecasting :

Sum = 4 + 3.4 + True + 4.0 
print(Sum)
Output:
12.4

In this example,

  • True means 1
  • The result data type is float due to the higher hierarchy 
  • Python implicitly converts 4(int) ,True(Bool) to a float 

Explicit or Forced Type Casting:

  • The programmer manually converts one data type to another using specific functions.

  • Commonly used functions include:

    • int(): Converts a value to an integer.
    • float(): Converts a value to a float.
    • str(): Converts a value to a string.
    • list(): Converts an iterable to a list.
    • tuple(): Converts an iterable to a tuple.
    • set(): Converts an iterable to a set.
  • Example:

print(int(3.8))
print(int('10'))
print(int(True))
print(float(2))
print(float(True))
print(bool(3))
print(bool(0))
print(list((1,2,3,4,5,6)))
print(tuple([1,2,3,4,5,6]))
print(set((1,2,3,4,5,6)))
Output:
3
10
1
2.0
1.0
True
False
[1, 2, 3, 4, 5, 6]
(1, 2, 3, 4, 5, 6)
{1, 2, 3, 4, 5, 6}

Register

Login here

Forgot your password?

ads

ads

I am an enthusiastic advocate for the transformative power of data in the fashion realm. Armed with a strong background in data science, I am committed to revolutionizing the industry by unlocking valuable insights, optimizing processes, and fostering a data-centric culture that propels fashion businesses into a successful and forward-thinking future. - Masud Rana, Certified Data Scientist, IABAC

© Data4Fashion 2023-2024

Developed by: Behostweb.com

Please accept cookies
Accept All Cookies