Python variables

A variable is the name given to a memory location. A value-holding Python variable is also known as an identifier.
Since Python is an infer language that is smart enough to determine the type of a variable, we do not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both letters and digits.
The name of the variable should be written in lowercase.

Identifier Naming

Identifiers are things like variables. An Identifier is utilized to recognize the literals utilized in the program. The standards to name an identifier are given underneath.

Declaring Variable and Assigning Values

In Python, we don't have to explicitly declare variables. Variables are declared and assigned values in Python using the assignment operator (=). Python doesn't tie us to pronounce a variable prior to involving it in the application. It permits us to make a variable at the necessary time.

Object References

When we declare a variable, it is necessary to comprehend how the Python interpreter works. Compared to a lot of other programming languages, the procedure for dealing with variables is a little different. Python is the exceptionally object-arranged programming language; Because of this, every data item is a part of a particular class.

Let's say we have a variable named x. When we say x = 5, we are not really storing the value 5 in the variable x. Instead, we are creating a new object with the value 5 and assigning the reference to that object to the variable x. This is known as an object reference. The object is the actual value, and the reference is the variable that points to the object.

Code Example


    # Object references
    x = 10
    y = x       # y references the same object as x
    
    print(f"x: {x}, y: {y}")
    
    # Changing value of x
    x = 20
    print(f"x: {x}, y: {y}")
                

Output

x: 10, y: 10 x: 20, y: 10

Python Variable Scope

Python variables can have different scopes, which determine where a variable can be accessed. Variables declared inside a function are local to that function, while variables declared outside of all functions are considered global. Python also supports non-local variables in nested functions:

Best Practices for Using Variables

Here are some best practices to consider when working with variables in Python:

Dynamic Typing and Type Casting

Python is dynamically typed, meaning you can change the data type of a variable during runtime. However, sometimes you may need to convert a variable from one type to another using type casting. For example:

Code Example


# Type casting example
number_str = "123"
number_int = int(number_str)  # Converts string to integer

print(type(number_str))  # Output: 
print(type(number_int))  # Output: 
            

Output

<class 'str'> <class 'int'>