
Data Types
This tutorial will cover two main topics:
Python's four most used data types, including String (
str
), Integer (int
), Float (float
), Boolean (bool
)
String
String, denoted as str in Python, is used to represent text and character data. String type data are enclosed within single (''
), double (""
), or triple quotes (""" """
). Regardless of the content—be it letters, numbers, symbols, or characters from other languages—anything enclosed within quotes is considered a string type.
Single (''
) and double (""
) quotes can be used interchangeably to denote string literals in Python. Triple quotes (""" """
), on the other hand, are primarily used when you need to represent multi-line strings, allowing you to include line breaks and preserve formatting within the string.
Example of Strings
Examples below are all string type data.
# With single quote'English''An apple a day, keeps doctor away''!@#'
# With double quotes"132""www.google.com"
# Multi-line strings with triple quotes"""This is a line.This is another line.This is a third line."""
Integer
Integer, denoted as int in Python, is a fundamental data type used to represent whole numbers, including zero, positive and negative values, without any decimal points.
Example of Integers
Examples below are integer type data.
# Positive integers201234
# Negative integers-20-999
Q: What are the data types of these three data: 'hello word', 108, "108".</span>
A. Interger, Number, String
B. String, Integer, Integer
C. String, Integer, String
D. Integer, Integer, Integer
Answer:
Click here to view the answer!
The correct answer is C!
Float
Float, denoted as float in Python, is used to represent numbers with decimal points, including fractional values.
Example of Floats
Examples below are float data type.
# Positive floats10.23.1415
# Negative floats-22.2
Boolean
Boolean, denoted as bool in Python, represents binary values, either True or False, and is often used for logical operations.
Example of Booleans
Examples below are boolean data type.
# A boolean trueTrue
# A boolean falseFalse
Assign Various Data Types to Variables
In our previous article on Python Variables, we described them as containers for holding values accessible by names. Now, we'll demonstrate assigning various data types to variables and display their types.
# Assign strings to variablesstr1 = 'Europe'str2 = "North America"
# Assign integers and floats to variablesnum1 = 120num2 = 3.1415
# Assign boolean values to variablesbool_val = True
To check the data type of the values stored in variables, we can use the built-in function type()
# Print the data type of the variable "string1"print(type(str1))
# Print the data type of the variable "string2"print(type(str2))
# Print the data type of the variable "num1"print(type(num1))
# Print the data type of the variable "num2"print(type(num2))
# Print the data type of the variable "bool_val"print(type(bool_val))
Output:
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
The outputs have shown that the 5 variables contain these data types: string, integer, float and boolean.
Properties of Different Data Types
After having basic concepts of data types, let's see some properties of each data type in practice.
Arithmetic Calculations of Intger and Float Variables
Both integers and floats are applicable for mathematical calculations.
Example
Define two integer variables, a and b. Given that both variables are integers, we can readily perform arithmetic calculations on them.
# creating variablesa = 10b = 2
# summationprint(a + b)
# deductionprint(a - b)
Output:
12
8
The output has shown that the sum of a and b is 12, and their difference is 8.
Other Operational Character:
- multiplication:
*
- division:
/
- modulo:
%
- it is used to find the remainder of the division of the left operand by the right operand.
- e.g.
7%2 outputs 1
- floor division or integer division:
//
- it is used to calculate the quotient of a division.
- e.g
10%3 outputs 3
- exponential:
**
- e.g.
3**2 outputs 9
- e.g.
# Example for modulo % print("Example for modulo:")print(7%2)
# Example for //print("Example for floor division")print(10//3)
# Example for exponential **print("Example for exponetial:")print(3**2)
Output:
Example for modulo:
1
Example for floor division
3
Example for exponetial:
9
💡 Experiment by typing these code examples with different values yourself, execute the calculations, and observe the outcomes.
Concatenation of Strings
When "+
" applied on strings, it is used for string concatenation.
# creating string variablestext1 = 'Hello'text2 = "World"
# Add strings together and print the resultprint(text1 + text2)
Output:
HelloWorld
The result shows the two strings concatenated without a space between them. Let's add a space to separate them.
print(text1 + ' ' + text2)
Output:
Hello World
By adding a space denoted by ' '
between text1 and text2 ('Hello World'), we combined them with a space in between.
String concatenation is widely used in data preprocessing and web development, especially for merging separate strings to create desired content.
Let's explore another example.
If we aim to print out "My uer ID is 23412
", could we construct the code like this:
var_1 = 'My user ID is: 'ID = 23412
print(var_1 + ID)
Output:
---------------------------------------------------------------------------TypeError Traceback (most recent call last)Input In [12], in <cell line: 4>() 1 var_1 = 'My user ID is: ' 2 ID = 23412----> 4 print(var_1 + ID)
TypeError: can only concatenate str (not "int") to st
Immediately, it leads to a TypeError indicating that concatenating strings with integers data is allowed.
This error occurs because the ID variable is an integer, which cannot be directly concatenated with strings.
In order to print out "My uer ID is 23412
", we must convert the ID variable from an integer to a string using data type conversion.
str()
Function
The str()
function converts data from other types into the string type. By using this function to convert the ID variable to string, we can complete the string concatenation to print "My suer ID is 23412
".
var_1 = 'My user ID is: 'ID = 23412
print(var_1 + str(ID))
Output:
My user ID is: 23412
Indeed, another method for converting data to string type, which we've discussed in previous articles, involves directly enclosing values in quotes:
print(var_1 + '23412')
Output:
My user ID is: 23412
It's important to note that quotes were used directly on the value, not on the variable. This is because enclosing a variable in quotes converts the variable's name into a string, not the value it holds.
Example of mistakenly using quotes around the variable name:
var_1 = 'My user ID is: 'ID = 23412
print(var_1 + 'ID')
Output:
My user ID is: ID
Both the str()
and quotes can convert data to string. Select the method that best suits your needs.
Let's do a quick check to see how well you understand the str()
function
Q: Which code below has error?
A. print(1+2+3)
B. print('Hello '+"World!")
C. print('Year ' + 2024)
C. print('1+2 equlas ' + str(3))
Answer:
Click here to view the answer!
The correct answer is C!