Variables in python

Variables in Python

Variables in Python are containers used to store data in memory.
Unlike statically typed languages, Python is dynamically typed — you don’t need to declare the data type of a variable explicitly. A variable is created the moment you assign a value to it.

Creating and Using Variables

Here is a simple example of creating variables and printing their values:

age = 38 name = "Sreya" weight = 58.5 print(age) # Output: 38 print(name) # Output: Sreya print(weight) # Output: 58.5

Explanation:

  • age stores an integer value (38).

  • name stores a string value ("Sreya").

  • weight stores a floating-point value (58.5).

Using Variables in Computations

You can also use variables in arithmetic operations:

price = 100 tax = 18 total_price = price + tax print(total_price) # Output: 118

Here, total_price is calculated by adding the values of price and tax.

How Variables Work Internally

When you assign a value to a variable, Python creates a memory location to store the value, and the variable becomes a reference (or label) to that memory location.

Example:

x = 10 y = "coder" z = 20 w = z print(x, y, z, w) # Output: 10 coder 20 20

If you later update the value of w, it no longer references z:

w = 30 print(x, y, z, w) # Output: 10 coder 20 30

Dynamically Typed Nature of Python

In Python, variables do not have fixed types — you can assign different types of values to the same variable:

x = 10 print(x) # Output: 10 x = "Python" print(x) # Output: Python

As shown above, x first stores an integer, then a string.

Boolean Variables

Variables can also store Boolean values — either True or False:

is_valid = True is_published = False print(is_valid) # Output: True print(is_published) # Output: False

👀Note: True and False must be written with capital letters in Python.

Special Value: None

If you want to indicate that a variable has no value, you can assign it None, which is a special value in Python:

x = None print(x) # Output: None

👀Keep in mind that None is not equivalent to False, 0, or an empty string.

Accessing Undefined Variables

If you try to access a variable that has not been defined, Python will raise a NameError:

print(my_var) # NameError: name 'my_var' is not defined

Always ensure that variables are assigned values before you use them.

Summary

  • Variables are used to store data in memory.

  • Python is dynamically typed — you can change a variable’s type at any time.

  • Variables can store different types of data: integers, floats, strings, Booleans, and None.

  • Undefined variables will cause a NameError.

Comments

Popular Posts