KP

Python Variables: Storing Data and Understanding Types

By Krishnamohan Yagneswaran
Tech Blog

Python Variables

What Are Variables?

Variables act as containers that store data values in a program. They allow you to save information and reuse it later in your code.


Creating Variables in Python

Python does not require a special command to declare a variable. A variable is created automatically as soon as you assign a value to it.

For example:
"score = 10"
"name = "Alex""
"print(score)"
"print(name)"

Once assigned, the variable can be used anywhere in the program.

Python variables do not need a fixed data type. A variable can even change its type after it has already been created.

For example:
"level = 2"
"level = "Beginner""
"print(level)"

In this case, the variable first stores a number and later stores text.


Casting Variables

If you want to force a variable to be a specific data type, Python allows this through casting.

Examples of casting include:
"age = str(25)"
"count = int("8")"
"price = float(12)"

Casting is useful when working with user input or converting data between different formats.


Getting the Variable Type

Python provides a built-in way to check the data type of a variable using the type() function.

For example:
"value = 100"
"text = "Python""
"print(type(value))"
"print(type(text))"

This helps developers understand how Python is interpreting stored values.

More details about data types and casting will be covered later in the tutorial.


Single Quotes vs Double Quotes

String values in Python can be created using either single quotes or double quotes.

Both of the following are valid and behave the same way:
"city = "London""
"city = 'London'"

The choice depends on personal or project preference.


Case Sensitivity in Variables

Python variable names are case-sensitive. This means uppercase and lowercase letters are treated as different identifiers.

For example:
"total = 5"
"Total = "Five""

These are considered two separate variables, and one does not replace the other.


Share this post:Share on TwitterShare on LinkedIn