Home » Learn Python » Getting Started » Python Types

Python Types

In Python, unlike in many other programming languages, variables do not have a type. This means that, for example, you could make a variable refer to a string, then later on make the same variable refer to a number instead.

A Python variable is really just a name to attach to a piece of data. Technically the full story is a little bit more complex, because what look like simple pieces of data in Python are really objects, with hidden functionality!

# Create a variable and assign
# a string to the variable
something = "Hello"
print(something)

# Now assign a number to the
# variable instead.
something = 7
print(something)
Hello
7

Classes, Objects and Types

While variables don’t have types, the values they refer to always have a definite type. All values in Python are technically objects, and objects always have a type, also known as a class.

Three very important classes are:

  • str: for representing text
  • int: for represeting whole numbers (integers)
  • float: for representing floating point (fractional) numbers.

You can discover the type of an object in Python by using the type function. This can be applied directly to objects, or to variables that refer to objects.

string_type = type("Hello")
integer_type = type(27)
float_type = type(1.234)

print(string_type)
print(integer_type)
print(float_type)
<class 'str'>
<class 'int'>
<class 'float'>

In this program we’re passing various objects (values) to the type function, then we’re passing the return value of the type function to the print function for each of the three cases.

If you’re new to programming this will seem confusing, but the trick is always just to try out the code and see what it does. The key is to practice, rather than try to memorise things.

Passing Return Values To Other Functions

In the above program we use variables to get the return value of the type function, while passing three different objects to the type function.

We can eliminate these variables and simply pass the return value of type directly to print.

So, the following program does exactly the same thing.

print(type("Hello"))
print(type(27))
print(type(1.234))

Checking Variables With the Type Function

You can use the type function to check what kind of object a variable refers to. In fact, you can always use a variable that refers to some data, rather than the data itself. This is always true in Python.

text = "Hello"
print(type(text))
<class 'str'>

It’s important to always know what types of things your variables refer to. You can always use the type function to check.

Leave a Reply

Blog at WordPress.com.

%d bloggers like this: