You can learn about Introduction to Python Programming Programs with Outputs helped you to understand the language better.
Python Programming – Variable
A variable is basically a name that represents (or refers to) some value. For example, you might want the name x to represent 5. To do so, simply execute the following:
>>> x = 5
This is called an assignment. You assign the value 5 to the variable x. In other words, you bind the variable x to the value (or object) 5. After you have assigned the value to the variable, you can use the variable in expressions:
>>> x * 2
10
A value is one of the basic things a program works with, like a letter or a number. These values belong to different types, such as 7 is an integer, 3.5 is float (number with decimal point), and ‘Hello, Python’ is a string, as it contains a string of letters. Variable is a name that refers to a value.
- Python Programming – Identifiers
- Python Programming – Flowcharts for Sequential, Decision-Based and Iterative Processing
- Introduction to Python Programming – The Basic Model Of Computation
The notion of a Variable
In Python, a name refers to an object. The name is actually a label for a memory location in the computer that stores something. A value is a chunk of code or any sort of thing that Python understands. For example, when you enter a statement such as x = 5 in Python, you are binding a name (x) to an object
(5).
- In Python, the object is simply a collection of data (variables) and methods (functions) that act on those data. Hence, a variable is also an object in Python.
Variables are reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory. Based on the data type of the variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by declaring variables with different data types, you can store integers, decimals, or characters in these variables.
However, Python variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable.
For example:
counter = 100 # An integer assignment
miles = 1000.0 # A floating point assignment
name = “Abhishek” # A string assignment
Here 100, 1000.0, and “Abhishek” are the values assigned to counter, miles, and name variables, respectively.
- Initialization is the process that sets the initial value of a variable. It is done only once for each variable when that variable is created.
Identity of a variable refers to the variable address in the memory which does not change once it has been created. To check the address of variable id( ) method is used. For example to check the addresses of the above-declared variables use the id( ) method as follows:
>>> id(counter)
1481522992
>>> id(miles)
57358912
>>> id(name)
23268752
Methods to Manipulate Variable
You can think of a variable as a named storage location in computer memory. Notice that in Figure 3.23 an arrow is used to show which value a variable refers to an old value does not get replaced by a new one. It simply switches to refer to the new value. When a value is no longer referred to by any variable, Python automatically clears these values out of memory so that space is used for new values.
- The equal to sign (=) is used to assign values to variables.
Assigning the same value to multiple variables:
Python allows you to assign a single value to several variables simultaneously. For example:
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location.
Let’s Try
Assigning the same text to multiple variables:
a = b = c = “same”
print ( a )
print ( b )
print ( c )
Assigning multiple values to multiple variables:
You can also assign multiple objects to multiple
variables. For example:
a, b, c = 1, 2, “Abhishek”
Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value “Abhishek” is assigned to the variable c.
Let’s Try
Assigning multiple values to multiple variables:
x, y, z = 2, 4.7, “Welcome”
print ( x )
print ( y )
print ( z )
Assigning None to a variable:
In Python, None is a special data type with a single value. For example,
begin = None
The line assigns a special value called None to variable begin. None is Python’s way of representing nothing. It makes a good placeholder for a value. It also evaluates to false when treated as a condition. Remember the following points while creating the variable name:
(a) They begin with either an alphabet letter (lower or upper case) or an underscore (_), but they cannot start with a digit. Generally, they are written in lower case letters.
(b) The variable name can consist of alphabet letters), number(s), and underscore(s) only. For example, myVar, MyVar, _myVar, MyVarl23, name_23, and _my_name are valid variable names. But m*var, my-var, lmyVar are invalid variable names.
(c) They cannot contain punctuation marks.
(d) Variable name should be meaningful and short, and it cannot contain spaces.
(e) Identifiers in Python are case sensitive. So, NAME, name, nAME, and nAmE are treated as different variable names.
(f) A Python keyword cannot be used as a variable name.
- Starting the name with a single or double underscore has a special meaning in Python.
L-value and R-value
Every assignment statement has two parts: a left-hand side and a right-hand side. Any kind of code that could go on the right-hand side of an assignment operator is called an R-value. Similarly, anything that could appear on its left is called an L-value.
Rvalues are the literals and expressions that are assigned to values. They can come only on the RHS of an assignment statement.
Lvalues are the objects to which you can assign a value or expression. They can come on LHS or RHS of an assignment statement.
Example:
a=2 # valid assignment
b=7 # valid assignment
2=a # invalid and produces an error
7=b # invalid and produces an error
Note in an assignment statement, the variable that is receiving the value must appear on the left side of the = operator, otherwise, it will generate an error as shown in the above examples.
- Note: L-value is an expression that refers to the storage area, and R-value is an expression that denotes value.
Mutable and Immutable Variables
A mutable variable is one whose value may change in place whereas in an immutable variable change of value will not happen in place. Modifying an immutable variable will rebuild the same variable. For example,
>>> x=5 # will create a value 5 referenced by x
>>> y=x # will make y refer to 5 of x
>>> x= x+y # in this statement LHS (x) , will rebuild to 10
>>> print( x )
10
>>> print( y )
5
SO,
x → 10
y → 5
An immutable is an object with a fixed value. Immutable objects include numbers, strings, and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored.
In Python language, variables do not need a declaration to reserve memory space. The “variable declaration” or “variable initialization” happens automatically when you assign a value to a variable.
Variable Assignment and Accepting input
An assignment statement creates a variable and sets its value, or changes the value of an existing vari¬able. The value that is assigned to a given variable does not have to be specified in the program, as demonstrated in previous examples. The value can come from the user by using input function,
print(“Enter your name:”)
x = input()
print(“Hello, ” + x)
Hello, Shashi
Let’s Try
Assigning string by accepting it from the user through the input function.
print ( ” Enter your first name: ” )
a = input ( )
print ( ” Hello , ” + a )
Let’s try
Assigning values by accepting them from the user through the input function.
X = int ( input ( ” Input first number: ” ) )
Y = int ( input ( ” Input second number: ” ) )
Z =int ( input ( ” Input third number: ” ) )
print(“Numbers are: ” , x, y, z)
Working with Dynamic Typing
There are two approaches to data typing in programming languages. You know that a variable is defined by assigning it some value. In static typing, a variable is declared as a certain type before it is used and can be assigned values of that type. However, Python uses dynamic typing. In dynamic typing, the data type of a variable depends only on the type of value that the variable is currently holding. Thus, the same variable may be assigned values of different types during the execution of a program. Once a value has been assigned to a variable, the interpreter will then decide what sort of value it is (i.e., number, string, etc.).
Dynamic typing makes it easier to handle different types of unpredictable user input. The interpreter can accept user input in many different forms, to which it assigns a type dynamically, i.e., words, numbers, or any other data type. This need not be decided by the programmer at the beginning of the program in order to assign it to a variable.
For example, in the following Python statements, an integer value is assigned to a variable ‘X’. Now, the Python interpreter won’t object if the same variable is used to store a reference to a string.
X=20
print (x)
x = “Seven”
print (x)
The above-mentioned code will display:
20
Seven
This means variable x is earlier pointing to an integer value 20 and then to a string value “Seven”. That is why Python is called a dynamically typed language.