5  Data Types

Understanding data types is fundamental to programming in Python, as they dictate how the interpreter will manipulate and store values. Data types are the classification of data items. They tell the interpreter how the programmer intends to use the data. In Python, every value has a data type, and it is crucial to know these types to write efficient and error-free code.

The Importance of Data Types

Data types define the operations that can be performed on a particular piece of data, the structure in which the data can be stored, and the way the data can be manipulated. For example, you cannot perform arithmetic operations on a string of text, but you can concatenate it with another string. Understanding data types helps in preventing type-related errors and optimizing code performance.

5.1 Common Data Types in Python

Python supports various built-in data types, each suited for different kinds of operations and uses. The primary data types include:

  1. Integer (int)
  2. Float (float)
  3. String (str)
  4. Boolean (bool)
  5. NoneType (None)

We will discuss each of these types in detail.

5.1.1 Integer (int)

An integer is a whole number, positive or negative, without decimals, of unlimited length. In Python, integers are of type int.

Example:

a = 10
b = -5
c = 123456789

To check the type of a variable, use the type() function:

print(type(a))  
print(type(b))
<class 'int'>
<class 'int'>

5.1.2 Float (float)

A float, or floating-point number, is a number that has a decimal place. Python uses the float type to represent these numbers.

Example:

x = 10.5
y = -3.14
z = 1.0

Checking the type of a float variable:

print(type(x))
print(type(y))
<class 'float'>
<class 'float'>

5.1.3 String (str)

A string is a sequence of characters enclosed in quotes. Strings can be enclosed in single quotes ('), double quotes ("), or triple quotes (''' or """).

Example:

name = "Alice"
greeting = 'Hello, World!'
paragraph = """This is a
multiline string."""

To determine if a variable is a string:

print(type(name)) 
<class 'str'>

5.1.4 Boolean (bool)

Booleans represent one of two values: True or False. They are commonly used in conditional statements and comparisons.

Example:

is_student = True
is_raining = False

Checking the type of a boolean variable:

print(type(is_student)) 
<class 'bool'>

5.1.5 NoneType (None)

None is a special data type in Python that represents the absence of a value. It is an object of its own datatype, the NoneType.

Example:

unknown = None

To check if a variable is of NoneType:

print(type(unknown))
<class 'NoneType'>

5.2 Dynamic Typing in Python

Python is a dynamically typed language, which means you do not need to declare the type of a variable when you create one. The type is determined at runtime based on the value assigned to it.

Example:

variable = 5
print(type(variable)) 

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

This feature provides flexibility but requires careful handling to avoid type-related errors.

5.3 Type Conversion

Sometimes, you may need to convert values from one type to another. This is known as type casting. Python provides several built-in functions for this purpose.

  • int(): Converts a value to an integer.
  • float(): Converts a value to a float.
  • str(): Converts a value to a string.
  • bool(): Converts a value to a boolean.

Example:

a = 10.5
b = int(a)  # b is now 10

c = "123"
d = int(c)  # d is now 123

e = "True"
f = bool(e)  # f is now True

Checking the types after conversion:

print(type(b))
print(type(d))
print(type(f))
<class 'int'>
<class 'int'>
<class 'bool'>

5.4 Operators and Data Types

Operators are used to perform operations on variables and values. Python supports various operators, and their behavior can differ based on the data types they operate on. Here, we will explore how operators work with different data types.

5.4.1 Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations such as addition, subtraction, multiplication, and division.

Example with Integers:

a = 10
b = 3

print(a + b) 
print(a - b)  
print(a * b)  
print(a / b)  
print(a % b)  
print(a ** b) 
print(a // b)  
13
7
30
3.3333333333333335
1
1000
3

Example with Floats:

x = 10.5
y = 3.2

print(x + y)  
print(x - y)  
print(x * y)  
print(x / y)
13.7
7.3
33.6
3.28125

5.4.2 String Operators

Strings can be manipulated using the + (concatenation) and * (repetition) operators.

Example:

str1 = "Hello"
str2 = "World"

print(str1 + " " + str2)  
print(str1 * 3)  
Hello World
HelloHelloHello

5.4.3 Comparison Operators

Comparison operators are used to compare two values. They return a boolean value (True or False).

Example with Integers and Floats:

a = 10
b = 5
c = 10.0

print(a == b)  
print(a != b)  
print(a > b)   
print(a < b)   
print(a >= c)  
print(a <= c) 
False
True
True
False
True
True

Example with Strings:

str1 = "Hello"
str2 = "World"
str3 = "Hello"

print(str1 == str2)  
print(str1 == str3)  
print(str1 != str2) 
print(str1 > str2)   # (Lexicographical comparison)
print(str1 < str2)  
False
True
True
False
True

5.4.4 Logical Operators

Logical operators are used to combine conditional statements.

Example:

a = True
b = False

print(a and b)  
print(a or b)  
print(not a)   
False
True
False

Logical operators can also be used with integers, where 0 is considered False and any non-zero value is considered True.

x = 0
y = 10

print(x and y)  
print(x or y)   
print(not x)  
0
10
True

5.5 Exercises

Exercise 1: Identifying Data Types

For each of the following variables, use the type() function to determine its data type.

a = 42
b = 3.14
c = "Python"
d = True
e = None

Exercise 2: Type Conversion

Convert the following values to the specified types and print the results.

  1. Convert x = 3.75 to an integer.
  2. Convert y = "123" to a float.
  3. Convert z = 0 to a boolean.
  4. Convert w = False to a string.

Exercise 3: Arithmetic Operations

Perform the following arithmetic operations and print the results.

  1. Add 15 and 23.
  2. Subtract 9 from 45.
  3. Multiply 7 by 8.
  4. Divide 20 by 4.
  5. Calculate the modulus of 27 and 4.
  6. Raise 2 to the power of 5.
  7. Perform floor division of 17 by 3.

Exercise 4: String Operations

Use the appropriate operations to do the following and print the results.

  1. Concatenate the strings "Data" and "Science" with a space in between.
  2. Repeat the string "Hello" 5 times.

Exercise 5: Logical Operations

Evaluate the following logical expressions and print the results.

  1. True and False
  2. True or False
  3. not True
  4. (5 > 3) and (2 < 4)
  5. (10 == 10) or (5 != 5)

Exercise 6: Mixed-Type Operations

Do the following operations and print the results.

  1. Add an integer and a float: 7 + 3.14
  2. Concatenate a string and an integer (convert the integer to a string first): "Age: " + str(30)
  3. Multiply a string by an integer: "Data" * 4