CodeGym /Courses /Python SELF EN /Data Type Conversion

Data Type Conversion

Python SELF EN
Level 5 , Lesson 2
Available

2.1 Determining the Type

Sometimes, in a specific part of the code, we don't know what kind of data is stored in a variable. For this, Python provides the function type(), which is used to determine the type of an object.

It's a built-in function that returns the type of the specified object, which can be useful for debugging, data validation, or implementing logic that depends on data types.

How the type() function works

When you call type(x), Python returns a special type object that represents the type of the variable x. For example:


x = 1
print(type(x))  # Will print: <class 'int'>

x = "hello"
print(type(x))  # Will print: <class 'str'>

x = [1, 2, 3]
print(type(x))  # Will print: <class 'list'>

Note that the word class will be printed. This is because even types like int, str, list, and others are classes — they are just built-in, so they don't require declaration, they come with Python.

Practical Use

The type() function is often used in scenarios where it's necessary to differentiate actions based on data type.

  • Different actions can be performed depending on the type of the variable.
  • In functions and methods, to ensure the correctness of argument types.

If you want to ensure that a variable contains a number, write code like the following:


arg = 123
if type(arg) == int:
    print(arg + 10)  # Will print: 133               

A more practical example where we check the type of the object stored in a variable:


arg = "123"
if type(arg) == int:
    print(arg + 10)  # This won't execute as arg is a string
elif type(arg) == str:
    print(arg + " world")  # Will print: 123 world
else:
    print("Unknown type")               

2.2 Explicit Type Declaration

In Python, explicitly specifying the object type is done using type-casting functions such as int(), float(), str(), tuple(), and others. These functions allow setting a specific type and converting data from one type to another, which is handy for processing user input, performing mathematical operations, or working with strings and data collections.

Examples of type-casting functions

int(): Converts data to an integer. We have encountered this function multiple times and know that if you pass a string with a number, int() will convert it into the corresponding integer.


num = int("123")  # num will be the integer 123               

float(): Another familiar function. Converts data to a floating-point number.


num = float("123.45")  # num will be 123.45               

str(): Converts any Python object to its string representation.


s = str(10.5)  # s will be '10.5'               

tuple(): Converts a sequence into a tuple.


t = tuple([1, 2, 3])  # t will become (1, 2, 3)               

list(): Converts an iterable object (like a string or a tuple) into a list. An iterable object is one you can loop over, like strings, lists, or tuples.


l = list("abc")  # l will be ['a', 'b', 'c']               

dict(): Creates a dictionary from key-value pairs.


d = dict([(1, 'a'), (2, 'b')])  # d will be {1: 'a', 2: 'b'}

We'll talk more about dictionaries and tuples later on, but I think you've got the general idea: if you need to explicitly set a certain type, you can always use the functions listed above.

2.3 Type Conversion

In Python, explicit type conversion (or typecasting) allows programmers to control and change the data types of variables. This can be useful for ensuring data compatibility in various operations or fixing data types obtained from user input or file reading. Essentially, type conversion and typecasting mean the same thing — the process of changing the data type of an object to another type.

We're already a bit familiar with explicit typecasting. It's done in Python using built-in functions like int(), float(), str(), tuple(), list(), dict(), set(), and others.

Let's reinforce this with a few more examples:

Function Description Input Example Output Example
int() Conversion to an integer int("10") 10
float() Conversion to a floating-point number float("20.5") 20.5
str() Conversion to a string str(15) "15"
tuple() Conversion to a tuple tuple([1, 2, 3]) (1, 2, 3)
list() Conversion to a list list("abc") ['a', 'b', 'c']
dict() Creating a dictionary from key-value pairs dict([(1, 'one'), (2, 'two')]) {1: 'one', 2: 'two'}
set() Creating a set from a list set([1, 1, 2, 2, 3, 3]) {1, 2, 3}

Examples of Use

Explicit typecasting is used in many scenarios, including:

  • Handling user input: Ensuring that input data matches the expected data type.
  • Data interoperability: When data from different sources or APIs need to be combined or compared.
  • Error handling: Preventing runtime errors by converting data to an appropriate type before performing operations.

Best Practices and Warnings

Explicit type conversion should be used thoughtfully to avoid data loss (such as when converting float to int) or conversion errors (like trying to convert a non-numeric string to a number).

It's also important to remember that some conversions might be non-intuitive and result in unexpected outcomes, requiring careful data checking. For example, converting int to bool and back can have surprising effects :)

2
Task
Python SELF EN, level 5, lesson 2
Locked
Mix-Up
Mix-Up
2
Task
Python SELF EN, level 5, lesson 2
Locked
Not everything is so simple.
Not everything is so simple.
Comments (1)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Gurjinder Level 10
19 March 2025
Why is it suggesting try catch blocks when we have not been taught these?