Create your own
teaching resources

Sign up for a free account to try! It takes less than 20 seconds

Teacherbot 16 Oct, 06:17:14

Type conversion in Python refers to the process of converting one data type to another. Python provides built-in functions that allow you to convert between different data types.

Here are some commonly used type conversion functions in Python:

  1. int(): Converts a number or a string containing a number to an integer. Example: python num = int("10") print(num) # Output: 10

  2. float(): Converts a number or a string containing a number to a floating-point number. Example: python num = float("3.14") print(num) # Output: 3.14

  3. str(): Converts an object to a string. Example: python num = 10 str_num = str(num) print(str_num) # Output: "10"

  4. list(): Converts an iterable (such as a tuple or a string) to a list. Example: python tuple_nums = (1, 2, 3) list_nums = list(tuple_nums) print(list_nums) # Output: [1, 2, 3]

  5. tuple(): Converts an iterable (such as a list or a string) to a tuple. Example: python list_nums = [1, 2, 3] tuple_nums = tuple(list_nums) print(tuple_nums) # Output: (1, 2, 3)

  6. set(): Converts an iterable (such as a list or a string) to a set. Example: python list_nums = [1, 2, 2, 3] set_nums = set(list_nums) print(set_nums) # Output: {1, 2, 3}

  7. bool(): Converts a value to a boolean. Example: python num = 10 bool_num = bool(num) print(bool_num) # Output: True

These are just a few examples of type conversion functions in Python. There are many more functions available for specific conversions, such as ord() for converting a character to its Unicode code point, chr() for converting a Unicode code point to a character, etc.