PY0101EN - Types 2:57
New Section
In this video, we will discuss different types of data in Python and how they are represented. We will explore integers, floats, strings, and booleans as the main data types.
Types of Data in Python
- Integers (int): Represent whole numbers, both positive and negative.
- Example: 11
- Floats (float): Represent real numbers, including integers and decimal values.
- Example: 21.213
- Strings (str): Represent sequences of characters.
- Example: "Hello World"
- Booleans (bool): Represent logical values that can be either true or false.
- Example: True
Typecasting in Python
- Typecasting allows us to convert one data type to another.
- Integer to Float:
- Casting an integer to a float does not change the value significantly.
- Example:
float(1)returns1.0
- Float to Integer:
- Casting a float to an integer may result in loss of information.
- Example:
int(1.1)returns1, losing the decimal part.
Converting Data Types
- String to Integer:
- If a string contains an integer value, it can be converted to an int data type.
- Example:
int("10")returns10
- String to Float:
- If a string contains a numeric value, it can be converted to a float data type.
- Example:
float("3.14")returns3.14
- Boolean to Integer/Float:
- Casting boolean values (
TrueorFalse) to integers or floats results in corresponding numerical values.
- Example:
- Casting
Truereturns1
- Casting
Falsereturns0
Summary
- Python has different data types, including integers, floats, strings, and booleans.
- Typecasting allows us to convert one data type to another.
- When typecasting, be cautious of potential loss of information.
- Converting strings to integers or floats is possible if the string contains valid numeric values.
- Boolean values can be casted to integers or floats, resulting in corresponding numerical values.
For more examples and practice, refer to the lab associated with this video.