Python Data Types

Learning Objectives

By the end of this tutorial, you should be able to:

  • Understand the different types of basic data types (primitive data types);
  • Recognize the fundamental functioning of each data type; and
  • Understand how to use variables in your code to represent data.

Tutorial Outline

This lesson will cover the following:

  • Emphasize the use of each data type;
  • Utilize built-in functions and methods on various data types;
  • Learn how to assign a variable a value; and
  • Understand the variable naming conventions.

Introduction

Python is a widely used programming language in software development, data research, and artificial intelligence. These use cases necessitate that data be stored effectively and in a way that it may be retrieved quickly. Python does this using its primary data types. These are the fundamental building blocks required for data processing and consist of simple data values.

Primitive data types are a set of fundamental data types from which all other data types are built.

Python makes use of four primitive variable types:

  • Integers
  • Floats
  • Strings
  • Booleans

Variables in Python, like variables in other programming languages, contain values and types. Data types define what sort of data a variable may hold and, in some instances, how much memory it can be allocated. By allocating variable types, we may make assumptions about the sorts of operations that can be performed on a specific variable.

Numbers

Two main data types exist to store numerical data, for example: 5, 6.21, -5000, 0.002, 9877777. Numbers can be stored as either integers or floats.

Integers

In Python, integers (ints) are positive or negative whole numbers with no fractional components. We may use Python’s built-in functions, such as type, to identify whether a number is an integer or a float and convert between the two.

Note, there is no practical limit to the length of an integer number. Of course, it is limited by the amount of memory allocated in your system, but an integer may be as long as you need it to be.

Floats

Another form of numerical data type that is used to represent real numbers is the float. A decimal point is used to split the integer and fractional components of the number.

Data Type Operation

We will see the basic data operations and how to store or manipulate the data type.

#Check data type
In [1]:  type(7)
Out[1]: int

In [2]:  type(2.6)
Out[2]: float
#Integer to Float
In [3]: float(8)
Out[3]: 8.0
#Float to Integer
In [6]: int(6.3)
Out[6]: 6

Mathematical operations with numbers

Let’s have a look at how we do mathematical operations in Python. You’ll observe that every mathematical operation involving an int
and a float always yields a float as a result. This might be due to Python changing the int to a float in certain circumstances.
To execute mathematical operations, the following numerical operators can be used:

  • Addition+
  • Subtraction-
  • Multiplication*
  • Division/
  • Round division//
  • Exponentiation**

The codes below shows how these operators are used:

#Addition
In [8]: 6 + 3
Out[8]: 9

#Subtraction
In [9]: 4 - 1.3
Out[9]: 2.7

#Multiplication
In [10]: 5 * 4.2
Out[10]: 21.0

#Division
In [11]: 6 / 3
Out[11]: 2.0

#Round division
In [12]: 6 // 3
Out[12]: 2

#Exponentiation
In [13]: 6 ** 3
Out[13]: 216

BODMAS

Python maintains traditional mathematical precedence principles by employing the basic sequence of operations when executing arithmetic operations (i.e. brackets first, then division and multiplication, and only after that comes addition and subtraction).

BODMAS is an abbreviation for the following:

  • Brackets
  • Of
  • Division
  • Multiplication
  • Addition
  • Subtraction

Let’s explore some expressions to see how python handles BODMAS operations.

Example 1:

In [14]: 3 + 3 * 3 / 3 - 2
Out[14]: 4.0

Example 2:

In [15]: (3 + 3) * 3/(3 - 2) 
Out[15]: 18.0

In the two examples above, Python will begin by computing the expression 3 * 3 / 3 (which is equal to 3). Only then will it add 3 at the start and deduct 2 at the end (1). Like in school, we must use brackets to describe the sequence of operations (2).

Modulo

Modulo ( %) might be the only high school operator you might remember. The term modulo is derived from a field of mathematics known as modular arithmetic. Modular arithmetic is concerned with integer arithmetic on a fixed-set circular number line. When all arithmetic operations on this number line reach a particular number known as the modulus, they will wrap around.

In [16]: 11 % 3
Out[16]: 2

As a result, 11 % 3 equals 2. This is because the number 3 enters 11 three times (3 x 3 = 9), leaving two extra (11 – 9 = 2). We usually use modulo to determine if an integer is even or odd:

  • Even number: if a number is divided by 2 and the result is 0, the number is even
  • Odd number: if a number is divided by 2 and the result is not 0, the number is odd
#Even number
In [17]:4 % 2
Out[17]: 0

#Odd number
In [18]: 7 % 2
Out[18]: 1

Roundround(number, ndigits)

Python also has an in-built function to round numbers up or down. The example below shows different ways by which python handles the round operation.

In [19]: round(7.34159265359, 2) #(1)
Out[19]: 7.34

Example 1: rounding 7.34159265359 (number) to 2 (digits)decimals, as shown in Out[19] gives 7.34.

In [20]: round(8.769, 2) #(2)
Out[20]: 8.76

Example 2: rounding the float 8.769 (number) to 2 (digits) returns 8.76 rather than 8.77 as expected. This is not an error. It’s just a result of the way computers do math.

For more information on this, check out https://docs.python.org/3.3/tutorial/floatingpoint.html#tut-fp-issues

Strings

string is a collection of characters. In python, anything inside either a single quote(' ') or double quotes (" ") is considered a string and both quotes can be used interchangeably.

Example:

"This is recognized as a string."

'This is also recognized as a string.'

Because strings are so dynamic, you may use more quotes and apostrophes within them, as shown in example (1). Strings can also be used in various ways. One of these methods is to add the strings (2):

In [21]: 'I am writing a script in Python, with another script. How easy is that!' #(1)
Out[21]: 'I am writing a script in Python, with another script. How easy is that!'


In [22]: 'Ice' + ' ' + 'Cream'  #(2)
Out[22]: 'Ice Cream'

Differentiating between numbers and strings

When working with strings in Python, we must always wrap them in quotation marks to make it clear that we want Python to recognize them as strings. This distinguishes them from variable names and numerals.

#Addition with numbers

In [24]: 2 + 2 + 2
Out[24]: 6
#Addition with strings

In [25]: '2' + '2' + '2'
Out[25]: '222'
#Multiplication of variables

In [26]: 2 * 3
Out[26]: 6
#Multiplication of string: Here we just add the string to itself 3 times

In [27]: '2' * 3
Out[27]: '222'

Applying Methods on Strings.

and: the result is True if both variables are true(x and y). and the operator is used to check whether both conditions are true

**or**: the result is True if at least one variable is true (x or y). or operator is used to check if either of the conditions is true

**not**: the result is True only if one variable is false (not x). not operator is used to check for inequality.

These Boolean operators will either equate to True if the condition is met or False if the condition is not.

Comparison Operators

Boolean data types can be used with comparison and logical operations as follows:

In [33]: 4 < 2

Out[33]: False
In [34]: 4 > 2
Out[34]: True
In [35]: 2 + 2 == 4
Out[35]: True
In [36]: 'blue' == 'red'
Out[36]: False

Logical operators

Below we will be testing some conditions using logical operators

In [37]: not 2 + 2 == 4
Out[37]: False
In [38]: 2 + 2 != 4
Out[38]: False
In [39]: 'blue' != 'red'
Out[39]: True
In [40]: 5 > 3 and 2 > 4
Out[40]: False
In [41]: True and True
Out[41]: True
In [42]: True and False
Out[42]: False
In [43]: False and True
Out[43]: False
In [44]: False and False
Out[44]: False
In [45]: 4 > 2 or 3 > 5
Out[45]: True
In [46]: True or True
Out[46]: True
In [47]: True or False
Out[47]: True
In [48]: False or True
Out[48]: True
In [49]: False or False
Out[49]: False

Variables

Variables are typically used to store some value (that might change later on). It’s helpful to think of variables as “virtual storage boxes” where we may keep things. To utilize our “virtual storage box,” we must give it a name (for example, 'x') and set it to a value (for example, 123). (1).

Looking below, we can see that our variable x has been allocated a value. We can now execute operations on it, such as multiplying it by another value (2). Variables may hold any of the Python data types you’ve already learned about, including integers, floats, strings, and even Boolean values. (3). We may even define a variable named 'is y greater', which will store the Boolean value indicating if y is greater than x. (4)

Understanding the purpose of using Variables in Python?

Variables allow us to create more adaptable programs. A programmer can utilize variables to represent data rather than “hard-coding” it straight into a program. The variables are then substituted with real data when we execute the program. This allows the same program to process diverse sets of data.

In [50]: x = 123 #(1)
In [51]: 3 * x #(2)

Out[51]: 369

#finding x squared

In [52]: x ** 2
Out[52]: 15129
In [4]: text = "I love Python "
        text * 3

Out[4]: 'I love Python I love Python I love Python'
In [54]: y = 250
In [55]: is_y_greater = y > x
In [56]: is_y_greater

Out[56]: False
In [57]: x + y

Out[57]: 619
In [58]: a = 3
         b = 2
         c = a**b
In [59]: c

Out[59]: 9

Overwriting Variables

A variable will always have the most recent i.e. last assigned value.

From the first line of code, variable x. If we want to modify its value from 123 to, say, 8, we simply set x equal to 8:

In [61]: x = 8
In [61]: x

Out[61]: 5

In [62]: x * 3
Out[62]: 15

Name conventions used for Variables

A variable can have a simple name (like x and y) or a more descriptive name that corresponds to the variable that you want to assign, such as title, color, or percentage_total.

Basic rules to naming variables in Python:

  • A variable name cannot begin with a number and must begin with a letter or the underscore character.
  • Only alphanumeric characters and underscores (A-z, 0-9, and _) are permitted in variable names.
  • Variable are case-sensitive. The case of variable names matters (age, Age and AGE are three different variables)
  • Variable names are limited to one word. Spaces will not satisfy:
vari able = 2
  File "<ipython-input-63-5a6006b67b5d>", line 1
    vari able = 2
            ^
SyntaxError: invalid syntax

3variables = 3
  File "<ipython-input-64-715d504b74e7>", line 1
    3variables = 3
             ^
SyntaxError: invalid syntax

Assigning Multiple Variables at Once

It is possible to assign multiple variables at once in Python, as this does not violate any of the naming conventions. You can equally assign the same value to multiple variables in one line. (2)

In [65]: two, three,four = 2, 3, 4

In [66]: print(three)
         print(five)
         print(seven)

Out[65]: 3
         5
         7
In [65]: a, b, c = "red", "blue", "green"

In [66]: print(a)
         print(b)
         print(c)

Out[65]: red
         blue
         green
In [68]: a = b =c = "Apple"
         print(a)
         print(b)
         print(c)

Out[65]: Apple
         Apple
         Apple
In [69]:x=32
	y=30/5
	z=3*4

In [70]:x
Out[70]:32

In [71]:y
Out[71]:6.0

In [71]:y
Out[71]:6.0

Conclusion

We’ve now learned about the primitive data types in Python. We also learned about built-in functions and methods and how to apply them to various data types. You should now have a solid knowledge of the usage of variables while creating Python code, as well as how to assign different data types to variables and the variable naming standards.

Appendix

Facebook
Twitter

Unlimited access to educational materials for subscribers

Ask ChatGPT
Set ChatGPT API key
Find your Secret API key in your ChatGPT User settings and paste it here to connect ChatGPT with your Tutor LMS website.
Hi, Welcome back!
Forgot?
Don't have an account?  Register Now