fbpx

Variables and Data Types in Python

Variables:

In Python, a variable is a name assigned to a value. Variables are used to store and manipulate data. Unlike some other programming languages, you don’t need to declare the data type of a variable explicitly; Python determines the type dynamically.

Variable Assignment:

# Variable assignment
name = "John"
age = 25
height = 5.9
is_student = True

Variable Naming Rules:

  • Variable names can contain letters, numbers, and underscores.
  • They cannot start with a number.
  • Python keywords cannot be used as variable names.

Data Types:

Python supports various data types, each serving a specific purpose. Here are some of the fundamental data types:

1. Integer (int):

Whole numbers without a decimal point.

age = 25

2. Float (float):

Numbers with a decimal point.

height = 5.9

3. String (str):

A sequence of characters enclosed in single or double quotes.

name = "John"
message = 'Hello, Python!'

4. Boolean (bool):

Represents truth values – True or False.

is_student = True
has_license = False

5. List:

An ordered, mutable collection of items.

fruits = ["apple", "banana", "orange"]

6. Tuple:

An ordered, immutable collection of items.

coordinates = (3, 4)

7. Dictionary (dict):

An unordered collection of key-value pairs.

person = {
    "name": "Alice",
    "age": 30,
    "is_student": False
}

8. Set:

An unordered collection of unique items.

unique_numbers = {1, 2, 3, 4, 5}

Type Conversion:

You can convert between data types using built-in functions:

# Convert float to int
height_as_int = int(height)

# Convert int to float
age_as_float = float(age)

# Convert int to string
age_as_str = str(age)

Checking Data Types:

Use the type() function to check the data type of a variable.

print(type(name))      # <class 'str'>
print(type(age))       # <class 'int'>
print(type(height))    # <class 'float'>
print(type(is_student)) # <class 'bool'>

Understanding variables and data types is fundamental to Python programming. In the next sections, we’ll explore how to manipulate and work with these variables and data types to perform various operations.