Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Getting to Know Your Data

In the previous lesson, I told you about values that variables point to or reference. In learning how to assign values to variables, we saw that we could assign ages, names, etc. There is a nature to each value, either a number, a string, etc. That aspect of the values is called the data type.

Understanding the type of data you are working with in Python is essential for writing correct and efficient code. This lesson covers how to inspect and understand different data types.

Checking Data Type with type()

Python provides the type() function to check the type of any value or variable.

print(type(10))          # <class 'int'>
print(type(3.14))        # <class 'float'>
print(type("Hello"))     # <class 'str'>
print(type(True))        # <class 'bool'>

Basic Data Types in Python

Here are some of the common data types in Python:

Data Type Example Description
int 10 Whole numbers
float 3.14 Decimal numbers
str "Hello" Text (strings)
bool True Boolean (True/False)

You can always check what type a variable is using type(variable).

Checking if a Variable is of a Certain Type

Python has built-in functions to check if a variable is of a specific type.

x = 10
print(isinstance(x, int))  # True
print(isinstance(x, float)) # False

This is useful when writing programs that need to ensure values are of a certain type before performing operations on them.

Converting Between Data Types

Python allows converting data types using type casting functions:

Function Converts to
int(x) Integer
float(x) Floating-point
str(x) String
bool(x) Boolean

Example:

num = "100"  # This is a string
num_int = int(num)  # Convert to an integer
print(num_int)  # Output: 100

Exercise: Try It Yourself!

  1. Print the type of "Python" using type().
  2. Convert 3.14 to an integer.
  3. Check if True is an instance of bool.
  4. Convert the string "200" into a number and print its type.