Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

Learning About Python Data Types

When a variable is created by an assignment such as variable=value, Python determines and assigns a data type to the variable. A data type defines how the variable is stored and the rules governing how the data can be manipulated. Python uses the variable’s assigned value to determine its type.

So far, this hour has focused on character strings. When the Python statement coffee_cup='tea' was entered, Python saw the characters in quotation marks and determined the variable coffee_cup to be a string literal data type, or str. Table 4.2 lists a few of the basic data types Python assigns to variables.

Table 4.2 Python Basic Data Types

Data Type

Description

float

Floating-point number

int

Integer

long

Long integer

str

Character string or string literal

You can determine which data type Python has assigned to a variable by using the type function. In Listing 4.22, the variables have been assigned two different data types.

Listing 4.22 Assigned Data Types for Variables

>>> coffee_cup='coffee'
>>> type(coffee_cup)
<class 'str'>
>>> cups_consumed=3
>>> type(cups_consumed)
<class 'int'>
>>>

Python assigned the data type str to the variable coffee_cup because it saw a string of characters between quotation marks. However, for the cups_consumed variable, Python saw a whole number, and thus it assigned the integer data type, int.

Making a small change in the cups_consumed variable assignment statement causes Python to change its data type. In Listing 4.23, the number assigned to cups_consumed is reassigned from 3 to 3.5. This causes Python to reassign the data type to cups_consumed from int to float.

Listing 4.23 Changed Data Types for Variables

>>> cups_consumed=3
>>> type(cups_consumed)
<class 'int'>
>>> cups_consumed=3.5
>>> type(cups_consumed)
<class 'float'>
>>>

You can see that Python does a lot of the “dirty work” for you. This is one of the many reasons Python is so popular.

  • + Share This
  • 🔖 Save To Your Account