Lesson 1 of 0
In Progress

Data types

Kedeisha January 17, 2024

Introduction to Data Types in Python

In Python, every value has a data type. Understanding data types is crucial as they define the operations that can be done on the data and how it is stored. In this lecture, we will explore the basic data types in Python: integers, floats, strings, and booleans. We will also learn how to determine the type of a variable.

1. Basic Data Types

Integers (int): Integers are whole numbers without a fractional part. In Python, you can define an integer by directly typing a whole number. For example:

age = 30
print(age)

Here, age is a variable that stores the integer 30.

Floats (float): Floats or floating-point numbers are numbers with a decimal point. They are used when more precision is needed. For example:

height = 175.5
print(height)

In this example, height is a variable that stores the float 175.5.

Strings (str): Strings are sequences of characters, used to store textual data. In Python, strings are created by enclosing characters in quotes. For example:

name = "Alice"
print(name)

Here, name is a string variable that stores the text “Alice”.

Booleans (bool): Booleans represent one of two values: True or False. They are often used to keep track of conditions or to control the flow of the program. For example:

is_student = True
print(is_student)

In this case, is_student is a boolean variable that stores the value True.

2. Determining the Type of a Variable

To find out the data type of a variable in Python, you can use the type() function. This function is particularly useful when you are unsure of the data type or when debugging your code. Here’s how you can use it:

# Defining variables
num = 10
price = 99.99
message = "Hello"
is_active = False

# Checking their types
print(type(num))      # Output: <class 'int'>
print(type(price))    # Output: <class 'float'>
print(type(message))  # Output: <class 'str'>
print(type(is_active))# Output: <class 'bool'>

In this example, we defined four variables, each with a different data type. We then used the type() function to print out the type of each variable.