Types of Variables in Python: An In-Depth Look

In our last post, we discussed the concept of variables in Python, what they’re used for and how to write simple code to start utilizing them. We also briefly discussed the types of variables and data structures that you’ll commonly encounter in your Python journey, especially in the field of data science.

In this post, we’ll spend a little more time on variable types with a more in-depth discussion that will help you identify each one and distinguish them from each other. We’ll also talk about possible use cases for these variable types so you can get a feel for their real-world applications.

Additionally, we’ll learn how to use the Type function in Python and how to change variable types as needed. Let’s get started:

Common Types of Variables

In Python, understanding the different types of variables is fundamental for effective programming. Each type of variable has specific characteristics and use cases. This section will discuss the primary types of variables, including integers, strings, booleans, and floating-point numbers. For each type, we’ll define it, discuss its use cases, and provide code examples to illustrate the applications.

Integer

An integer in Python is a whole number, positive or negative, without a fractional part. Python’s “int” type can represent numbers of arbitrary length, constrained only by the memory available.

Integers are used in various scenarios, such as counting, indexing, looping, and any arithmetic operations where whole numbers are required.

Examples:

# Example of integer variables
age = 25
year = 2024
temperature = -5
print(type(age))   # Output: <class 'int'>
print(type(year))   # Output: <class 'int'>
print(type(temperature))   # Output: <class 'int'>

Floating Point

A floating-point number in Python is a number that has a decimal point. The “float” type is used for representing real numbers with fractional parts.

Floating-point numbers are used in mathematical calculations that require precision, such as scientific computations, financial calculations, and any scenario where a fraction is involved.

Examples:

python
Copy code
# Example of floating-point variables
pi = 3.14159
height = 5.9
negative_float = -2.75
print(type(pi))   # Output: <class 'float'>
print(type(height))   # Output: <class 'float'>
print(type(negative_float)) # Output: <class 'float'>

String

A string in Python is a sequence of characters enclosed in single, double, or triple quotes. The “str” type is used for text data.

Strings are used for representing text, such as names, messages, and any data that consists of a sequence of characters.

Examples:

python
Copy code
# Example of string variables
name = "Alice"
greeting = 'Hello, world!'
long_text = """This is a
multi-line string."""
print(type(name))   # Output: <class 'str'>
print(type(greeting))   # Output: <class 'str'>
print(type(long_text))   # Output: <class 'str'>

Boolean

A Boolean in Python is a variable that can hold one of two values: True or False. The “bool” type is used for logical operations.

Booleans are used in conditional statements, loops, and logical operations to control the flow of the program based on certain conditions.

Examples:

python
Copy code
# Example of boolean variables
is_active = True
is_logged_in = False
has_permission = True
print(type(is_active))  # Output: <class 'bool'>
print(type(is_logged_in)) # Output: <class 'bool'>
print(type(has_permission)) # Output: <class 'bool'>

As you go deeper into data analytics and machine learning, you’ll appreciate the differences between variables even more. Each one serves a very specific purpose that allows you to build algorithms and models effectively.

The Type Function in Python: An In-Depth Look

In Python, the type() function is a powerful and essential tool that allows developers to inspect the type of a variable. Understanding the types of variables is crucial since it influences the operations that can be performed on them and how they interact with other variables. This section will delve into the type() function, its syntax, and provide code examples to illustrate its usage.

What is the type() Function?

The type() function in Python is used to determine the type of an object. It returns the type of the given object, which can be helpful for debugging, writing type-specific code, or simply understanding the data you are working with.

Syntax of the type() Function

The syntax of the type() function is straightforward:

type(object)

Here, object is the variable or value whose type you want to determine.

Code Examples

Let’s look at some examples to see how the type() function works in practice.

1. Checking the Type of an Integer

number = 42
print(type(number))

Output:

<class 'int'>

In this example, type(number) returns <class ‘int’>, indicating that number is an integer.

2. Checking the Type of a String

text = "Hello, Python!"
print(type(text))

Output:

<class 'str'>

Here, type(text) returns <class ‘str’>, showing that text is a string.

The same coding syntax can be used to determine the types of variables whether they’re floating points, Boolean values, or even data structures (more on that in succeeding posts).

Math Operations Between Variable Types

In Python, variables of different types can interact through various mathematical operations. Understanding how these operations work and what results to expect is crucial for writing functional code. In this section, we’ll explore possible math operations between variable types, including compatible and incompatible pairings.

Compatible Operations

1. Integer and Integer

Operations between integers yield integer results unless division is involved:

a = 10
b = 3
print(a + b)  # Output: 13 (Addition)
print(a - b)  # Output: 7 (Subtraction)
print(a * b)  # Output: 30 (Multiplication)
print(a / b)  # Output: 3.3333333333333335 (Division, result is a float)
print(a // b)  # Output: 3 (Floor Division)
print(a % b)  # Output: 1 (Modulus)
print(a ** b)  # Output: 1000 (Exponentiation)

2. Integer and Floating Point

Operations between an integer and a floating-point number yield a floating-point result:

a = 10
b = 3.5
print(a + b)  # Output: 13.5 (Addition)
print(a - b)  # Output: 6.5 (Subtraction)
print(a * b)  # Output: 35.0 (Multiplication)
print(a / b)  # Output: 2.857142857142857 (Division)
print(a // b)  # Output: 2.0 (Floor Division, result is a float)
print(a % b)  # Output: 3.0 (Modulus)
print(a ** b)  # Output: 3162.2776601683795 (Exponentiation)

3. Floating Point and Floating Point

Operations between floating-point numbers yield a floating-point result:

a = 10.5
b = 2.5
print(a + b)  # Output: 13.0 (Addition)
print(a - b)  # Output: 8.0 (Subtraction)
print(a * b)  # Output: 26.25 (Multiplication)
print(a / b)  # Output: 4.2 (Division)
print(a // b) # Output: 4.0 (Floor Division)
print(a % b) # Output: 0.5 (Modulus)
print(a ** b) # Output: 189.20711500272127 (Exponentiation)

4. String and String

String concatenation is the only mathematical operation applicable to strings. This is the process of joining two or more strings end-to-end to form a new string. In Python, the + operator is commonly used to concatenate strings.

a = "Hello"
b = "World"
print(a + " " + b)  # Output: "Hello World" (Concatenation)

Incompatible Operations

1. String and Integer

Combining a string and an integer directly using arithmetic operations results in a TypeError:

a = "Age: "
b = 30
#This will raise a TypeError
try:
  print(a + b)
except TypeError as e:
   print(e)  # Output: can only concatenate str (not "int") to str

To perform the operation, the integer must be explicitly converted to a string: print(a + str(b))  # Output: “Age: 30”

2. String and Floating Point

Similar to strings and integers, strings and floating-point numbers cannot be directly combined using arithmetic operations:

a = "Height: "
b = 5.9
# This will raise a TypeError
try:
 print(a + b)

except TypeError as e:
 print(e)  # Output: can only concatenate str (not "float") to str

Explicit conversion is required:

print(a + str(b))  # Output: "Height: 5.9"

3. Boolean and Numeric Types

Booleans can participate in arithmetic operations with integers and floating-point numbers, where True is treated as 1 and False as 0:

a = True
b = 3
print(a + b)  # Output: 4 (True is 1)
print(a * b)  # Output: 3 (True is 1)
a = False
print(a + b)  # Output: 3 (False is 0)
print(a * b)  # Output: 0 (False is 0)

Type Conversion in Python

Type conversion is the process of converting one data type to another. This is an essential concept in Python, as it allows you to manipulate data in ways that are compatible with various operations and functions. Type conversion can be classified into two categories: explicit and implicit.

Explicit Type Conversion

Explicit type conversion, also known as type casting, is when the programmer manually converts a variable from one type to another using Python’s built-in functions.

Use Cases and Scenarios

  • Mathematical Operations. Converting user input (usually strings) into integers or floats to perform arithmetic operations.
  • String Formatting. Converting numbers to strings for concatenation in messages.
  • Data Processing. Converting data types to ensure consistency in data processing tasks.

Syntax:

  • 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.

Examples:

# Converting string to integer
user_input = "42"
number = int(user_input)
print(type(number))  # Output: <class 'int'>
# Converting integer to float
integer_value = 10
float_value = float(integer_value)
print(type(float_value))  # Output: <class 'float'>
# Converting integer to string
age = 25
age_str = str(age)
print(type(age_str))  # Output: <class 'str'>
# Converting string to boolean
truth_value = "True"
bool_value = bool(truth_value)
print(type(bool_value))  # Output: <class 'bool'>

Implicit Type Conversion

Implicit type conversion, also known as coercion, is when Python automatically converts one data type to another during an operation, without the need for explicit instructions from the programmer.

Use Cases and Scenarios:

  • Mixed-Type Operations. When performing operations on mixed data types, Python implicitly converts data types to ensure the operation can be carried out.
  • Avoiding Type Errors. Simplifies code by reducing the need for explicit conversions and helps in avoiding type errors.

Examples:

# Implicit conversion in mathematical operations
integer_value = 5
float_value = 2.5
result = integer_value + float_value # int is implicitly converted to float
print(result)  # Output: 7.5
print(type(result)) # Output: <class 'float'>
# Implicit conversion in boolean context
number = 10
result = number / 2
if result:
   print("The result is non-zero")  # Output: The result is non-zero

In the first example, when adding an integer (5) and a float (2.5), Python implicitly converts the integer to a float, resulting in a float value (7.5). In the second example, Python implicitly converts the result of the division to a boolean in the if statement context. We’ll learn more about if statements as we go along. For now, it’s enough for you to know that if is a conditional statement used for logic-based operations.

And there you have it: a quick guide on variable types in Python along with the basics on what you can do with them. In our next lessons, we’ll discuss data structures and how they can help organize large variable groups.

About Glen Dimaandal

Picture of Glen Dimaandal
Glen Dimaandal is a data scientist from the Philippines. He has a post-graduate degree in Data Science and Business Analytics from the prestigious McCombs School of Business in the University of Texas, Austin. He has nearly 20 years of experience in the field as he worked with major brands from the US, UK, Australia and the Asia-Pacific. Glen is also the CEO of SearchWorks.PH, the Philippines' most respected SEO agency.
Picture of Glen Dimaandal
Glen Dimaandal is a data scientist from the Philippines. He has a post-graduate degree in Data Science and Business Analytics from the prestigious McCombs School of Business in the University of Texas, Austin. He has nearly 20 years of experience in the field as he worked with major brands from the US, UK, Australia and the Asia-Pacific. Glen is also the CEO of SearchWorks.PH, the Philippines' most respected SEO agency.
ARTICLE & NEWS

Check our latest news

In data science, saving progress is essential. Just like saving your progress in a video game…

In our last lesson, we introduced the concept of Python packages and NumPy in particular. Short…

Now that we have a solid handle on basic Python programming, we can move on to…

Ready to get started?

Reveal the untapped potential of your data. Start your journey towards data-driven decision making with Griffith Data Innovations today.