Variables and Data Types in Python
Subject: Data Structures and Algorithms · Language: Python · Level: beginner · 6 min read
Learn Python variables, dynamic typing, primitive-style values, collections, type conversion, constants by convention, and DSA data type choices.
A variable is a name used to store a value in memory. In Python, you do not need to write the data type before the variable name, but the value still has a type internally. For example, `age = 20` stores an integer value, while `name = "Rahul"` stores a string value.
Python decides the type from the assigned value at runtime. This makes code shorter than Java, but it also means students must pay attention to what kind of value a variable contains. If a number is stored as text, mathematical operations will not work correctly until it is converted.
Data types decide what operations are allowed. Integers can be added, subtracted, multiplied, and divided. Strings can be joined, sliced, and searched. Lists can store multiple values and can be changed. Dictionaries store key-value pairs. Choosing the correct type makes the program simpler and safer.
In DSA, variables are used to store counts, sums, indexes, maximum values, minimum values, flags, answers, and temporary values. A variable like `found = False` is useful when searching. A variable like `max_value` is useful when finding the largest element. A variable like `count` is useful when counting conditions.
Students should also understand mutable and immutable types. Integers, floats, strings, booleans, and tuples are immutable, which means their actual value cannot be changed directly. Lists, sets, and dictionaries are mutable, so their contents can be updated. This matters when passing values to functions.
Good variable names make code easier to understand. Instead of writing only `x` and `y` everywhere, use names like `marks`, `total`, `index`, `target`, `is_prime`, and `current`. In interviews, clear names help the interviewer understand your logic quickly.
A variable is a name used to store a value in memory. When you write programs, you often need to remember information such as age, marks, name, count, index, sum, or result. Variables make this possible.
In Python, you do not need to write the data type before the variable name. Python decides the type from the value assigned to the variable. This is why Python is called a dynamically typed language.
For example, if you store `20`, Python treats it as an integer. If you store `"Rahul"`, Python treats it as a string. If you store `True`, Python treats it as a boolean value.
Creating a Variable
Creating a variable means assigning a value to a name.
```python
age = 20
```
Here, `age` is the variable name and `20` is the value stored in it. Python automatically understands that `age` currently stores an integer value.
A variable name should be meaningful. Names like `sum`, `marks`, `count`, `is_prime`, and `found` are easier to understand than random names.
Updating a Variable
A variable value can be changed later in the program.
```python
age = 20
age = 21
```
After the second line, the old value `20` is replaced by the new value `21`.
Dynamic Typing
Python allows a variable to point to a different type later.
```python
value = 10
value = "Python"
```
This is allowed, but in clean DSA code you should avoid changing the meaning of a variable. If `value` starts as a number, it is usually better to keep it as a number so the code remains clear.
Common Data Types
- `int` stores whole numbers such as `10`, `0`, and `-5`
- `float` stores decimal values such as `72.5` and `3.14`
- `str` stores text such as names, words, and sentences
- `bool` stores `True` or `False`
- `list` stores ordered and changeable values
- `tuple` stores ordered but unchangeable values
- `set` stores unique values
- `dict` stores key-value pairs
Numeric Types
Use `int` for counting, indexing, loop variables, array values, and most DSA problems. Use `float` for decimal values such as percentage, average, distance, or measurement.
Python integers can grow very large, so integer overflow is usually less of a problem than in languages like C or Java. Still, you should understand the size of values because very large calculations can affect performance.
String Type
A string is a sequence of characters. Names, email IDs, passwords, words, and sentences are stored as strings.
```python
name = "Rahul"
message = "Welcome to Python"
```
Strings are very important in DSA because many placement problems involve character checking, palindrome logic, frequency counting, and string comparison.
Boolean Type
A boolean value is either `True` or `False`. Boolean variables are useful for conditions and flags.
```python
found = False
is_prime = True
```
In DSA, boolean flags are commonly used to remember whether a target was found, whether a number is prime, or whether an array is sorted.
Collection Types
Python provides collection types that are very useful for DSA.
A `list` is used like a dynamic array. A `dict` is used for mapping and frequency counting. A `set` is used for uniqueness and fast membership checking. A `tuple` is useful when values should stay grouped and unchanged.
Checking Data Type
Use `type()` to check the type of a value.
```python
age = 20
print(type(age))
```
Output
```text
<class 'int'>
```
This is useful while learning because it helps you understand what Python has inferred.
Type Conversion
Type conversion means converting a value from one type to another. This is common when reading input because `input()` always returns text.
```python
marks = int(input())
percentage = float(input())
```
Use `int()` for whole numbers, `float()` for decimal values, and `str()` when you need text.
Constants by Convention
Python does not have a strict `final` keyword like Java for normal constants. Programmers usually write constant names in uppercase to show that they should not be changed.
```python
PI = 3.14159
MAX_MARKS = 100
```
This is a convention, not a hard rule enforced by Python.
Example Program
```python
age = 20
grade = "A"
passed = True
print("Age =", age)
print("Grade =", grade)
print("Passed =", passed)
```
Output
```text
Age = 20
Grade = A
Passed = True
```
This program creates three variables. `age` stores an integer, `grade` stores a string, and `passed` stores a boolean value.
Variables in DSA
Variables are used everywhere in DSA. A loop counter like `i`, a sum variable like `total`, a flag like `found`, and an answer variable like `result` are all variables.
When solving a problem, first identify what information must be stored. Then choose a clear variable name and the correct data type.
This is different from Java, where you write `int age = 20`. In Python, the type is decided from the value assigned at runtime. This makes beginner code shorter, but students must still know what type they are working with because operations depend on type.
For example, `10 + 20` gives `30`, but `"10" + "20"` gives `"1020"`. The operator is the same, but the data types are different, so the behavior changes. This is why input conversion is important in Python.
In DSA, type choice affects correctness. Use `int` for counting and indexing, `float` for decimal values, `str` for text, `bool` for true/false decisions, `list` for ordered multiple values, `set` for uniqueness, and `dict` for key-value mapping.
A strong habit is to give meaningful variable names. Names like `sum`, `count`, `max_value`, `is_found`, and `index` make logic easier to read. In interviews, readable code often helps the interviewer follow your thinking quickly.
Practice Question
Create variables for a student's name, roll number, marks, grade, and pass status. Print all details in a clean format.