Python Type Conversion

https‮i.www//:‬giftidea.com

In Python, type conversion (or type casting) refers to the process of converting a value from one data type to another. Python provides several built-in functions to perform type conversion. Here are some examples:

  • int(x): Converts x to an integer.
  • float(x): Converts x to a float.
  • str(x): Converts x to a string.
  • bool(x): Converts x to a boolean.
  • list(x): Converts x to a list.
  • tuple(x): Converts x to a tuple.
  • set(x): Converts x to a set.
  • dict(x): Converts x to a dictionary.

Here are some examples of using type conversion in Python:

# Converting from string to integer
x = "10"
y = int(x)
print(y)  # output: 10

# Converting from integer to string
a = 5
b = str(a)
print(b)  # output: "5"

# Converting from string to float
s = "3.14"
f = float(s)
print(f)  # output: 3.14

# Converting from float to integer
c = 3.8
d = int(c)
print(d)  # output: 3

# Converting from list to tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)  # output: (1, 2, 3)

# Converting from set to list
my_set = {1, 2, 3}
my_list = list(my_set)
print(my_list)  # output: [1, 2, 3]

It is important to note that not all conversions are possible, and some conversions may result in a loss of information. For example, converting from float to integer will truncate the decimal part of the number, which may result in an inaccurate value.