/

Python Data Types: Exploring Built-in Types in Python

Python Data Types: Exploring Built-in Types in Python

Python, a versatile programming language, provides a range of built-in types to handle different kinds of data. In this blog, we will explore the basics of Python data types and how to work with them effectively.

String

Strings are sequences of characters enclosed in quotes (‘’ or “”). To check if a variable is of the string data type, you can use the type() function or the isinstance() function:

1
2
3
4
name = "Roger"
type(name) == str # True

isinstance(name, str) # True

Numbers

Python supports two types of numbers: integers (int) and floating-point numbers (float). Integers are whole numbers without a fractional component, while floating-point numbers have decimal places. Here’s how you can define and determine the data type of numbers:

1
2
3
4
5
age = 1
type(age) == int # True

fraction = 0.1
type(fraction) == float # True

Creating Variables

In Python, variables are dynamically typed, which means that you don’t need to explicitly specify the data type when creating a variable. Python automatically detects the type from the assigned value. For example:

1
2
name = "Flavio"  # String
age = 20 # Integer

You can also explicitly define a variable of a specific type by using the class constructor:

1
2
3
name = str("Flavio")  # String

anotherName = str(name) # String

Type Conversion: Casting

Python allows you to convert variables from one type to another using the class constructor. This process is known as casting. Python will try to determine the correct value based on the conversion. For example, you can convert a string to an integer:

1
2
3
4
5
6
age = int("20")
print(age) # 20

fraction = 0.1
intFraction = int(fraction)
print(intFraction) # 0

However, note that not all conversions are possible. If you try to convert a value that is not compatible with the target type, you will encounter an error. For instance, converting the string “test” to an integer will result in a ValueError: invalid literal for int() with base 10: 'test' error.

Other Data Types

In addition to strings and numbers, Python offers several other built-in types for different purposes. Here are some notable examples:

  • complex for complex numbers
  • bool for booleans
  • list for lists
  • tuple for tuples
  • range for ranges
  • dict for dictionaries
  • set for sets

These are just the basics of Python data types. In future articles, we will delve into each type individually, exploring their features and practical usage.

tags: [“Python”, “data types”, “string”, “numbers”, “type conversion”, “casting”, “complex”, “bool”, “list”, “tuple”, “range”, “dict”, “set”]