Python Variables

3 min read ·

Variables in Python are used to store data values. Python creates a variable at the moment you assign a value to it, which makes variable handling simple and flexible.

Creating Variables

In Python, variables are created without declaring a data type. You just assign a value using the = operator.
Python automatically determines the type of the variable.

Code Example 1: Creating Variables

Code Example 2: Reassigning Variables

Code Example 3: Multiple Variables

Key Point

Python variables are dynamically typed.


Casting

Casting means specifying a data type for a variable. Python allows you to convert values from one type to another.
Common casting functions:
  • int()
  • float()
  • str()

Code Example 1: Integer Casting

Code Example 2: Float Casting

Code Example 3: String Casting

Important

Casting helps control how data is stored and processed.


Get the Type

Python provides the type() function to check the data type of a variable.
This is useful for debugging and learning.

Code Example 1: Check Integer Type

Code Example 2: Check String Type

Code Example 3: Check Float Type


Single or Double Quotes?

In Python, strings can be created using single quotes (' ') or double quotes (" "). Both are treated the same by Python.
Use double quotes when the string contains single quotes.

Code Example 1: Single Quotes

Code Example 2: Double Quotes

Code Example 3: Mixed Quotes

Best Practice

Be consistent with quote style throughout your code.


Case-Sensitive

Python is a case-sensitive language. This means variable names with different letter cases are treated as different variables.

Code Example 1: Case Sensitivity

Code Example 2: Invalid Assumption

Code Example 3: Recommended Naming Style

Caution

Always use consistent naming to avoid confusion and errors.


Exercise

  • Create variables of different types
  • Convert one type into another using casting
  • Use type() to verify the result