2.python Variables
2.python Variables
Also, Solve:
Table of contents
Creating a variable
Changing the value of a variable
Create Number, String, List variables
Number
Integer variable
Float variable
Complex type
String variable
List type variable
Get the data type of variable
Delete a variable
Variable’s case-sensitive
Constant
Assigning a value to a constant in Python
Rules and naming convention for variables and constants
Multiple assignments
Assigning a single value to multiple variables
Assigning multiple values to multiple variables
Variable scope
Local variable
Global variable
Object/Variable identity and references
Object Reference
Unpack a collection into a variable
Creating a variable
Python programming language is dynamically typed, so there
is no need to declare a variable before using it or declare
the data type of variable like in other programming
languages. The declaration happens automatically when we
assign a value to the variable.
variable_name = variable_value
Example
name = "John" # string assignment
age = 25 # integer assignment
salary = 25800.60 # float assignment
print(name) # John
print(age) # 25
print(salary) # 25800.6
Run
In the above example, “John”, 25, 25800.60 are values that
are assigned to name, age, and salary respectively.
Example
var = 10
print(var) # 10
# print its type
print(type(var)) # <class 'int'>
Run
Number
A number is a data type to store numeric values. The object
for the number will be created when we assign a value to the
variable. In Python3, we can use the following three data
types to store numeric values.
1. Int
2. float
3. complex
Integer variable
Example
Run
Note: We used the built-in Python method type() to check the
variable type.
Float variable
Floats are the values with the decimal point dividing the
integer and the fractional parts of the number. Use float
data type to store decimal values.
Example
Run
In the above example, the variable salary assigned to value
10800.55, which is a float value.
Complex type
The complex is the numbers that come with the real and
imaginary part. A complex number is in the form of a+bj,
where a and b contain integers or floating-point values.
Example
a = 3 + 5j
print(a) # (3+5j)
print(type(a)) # <class 'complex'>
Run
String variable
In Python, a string is a set of characters represented in
quotation marks. Python allows us to define a string in
either pair of single or double quotation marks. For
example, to store a person’s name we can use a string type.
To retrieve a piece of string from a given string, we can
use to slice operator [] or [:]. Slicing provides us the
subset of a string with an index starting from index 0 to
index end-1.
Example
# length of string
print(len(str)) # 8
# concatenate string
print(str + "TEST") # PYnativeTEST
Run
Example
# create list
my_list = ['Jessa', 10, 20, 'Kelly', 50, 10.5]
# print entire list
print(my_list) # ['Jessa', 10, 20, 'Kelly', 50, 10.5]
Run
Syntax of type() :
type(<variable_name>)
Example
a = 100
print(type(a)) # class 'int'
b = 100.568
print(type(b)) # class 'float'
str1 = "PYnative"
print(type(str1)) # class 'str'
Run
If we want to get the name of the datatype only as output,
then we can use the__name__ attribute along with
the type() function. See the following example
where __name__ attribute is used.
Example
my_list =[10,20,20.5,'Python',100]
# It will print only datatype of variable
print(type(my_list).__name__) # list
Run
Delete a variable
Use the del keyword to delete the variable. Once we delete
the variable, it will not be longer accessible and eligible
for the garbage collector.
Example
var1 = 100
print(var1) # 100
Run
Now, let’s delete var1 and try to access it again.
Example
var1 = 100
del var1
print(var1)
Run
Output:
Variable’s case-sensitive
Python is a case-sensitive language. If we define a variable
with names a = 100 and A =200 then, Python differentiates
between a and A. These variables are treated as two
different variables (or objects).
Example
a = 100
A = 200
# value of a
print(a) # 100
# Value of A
print(A) # 200
a = a + A
print(a) # 300
Run
Constant
Constant is a variable or value that does not change, which
means it remains the same and cannot be modified. But in the
case of Python, the constant concept is not applicable. By
convention, we can use only uppercase characters to define
the constant variable if we don’t want to change it.
Example
MAX_VALUE = 500
PI = 3.14
TOTAL_AREA = 205
Constants are declared with uppercase later variables and
separating the words with an underscore.
Example
import constant
print(constant.PI)
print(constant.TOTAL_AREA)
Output
3.14
205
total_addition
TOTAL_ADDITION
totalAddition
Totaladdition
Example
x = "Jessa"
student_name = "Jessa"
Example
ca$h = 1000
Run
Output
ca$h = 11
1studnet = "Jessa"
print(1studnet)
total = 120
Total = 130
TOTAL = 150
print(total)
print(Total)
print(TOTAL)
Run
Output
120
130
150
MIN_VALUE = 100
MAX_VALUE = 1000
current_temperature = 24
Multiple assignments
In Python, there is no restriction to declare a variable
before using it in the program. Python allows us to create a
variable as and when required.
Example
a = b = c = 10
print(a) # 10
print(b) # 10
print(c) # 10
Run
Run
In the above example, two integer values 10 and 70 are
assigned to variables roll_no and marks, respectively, and
string literal, “Jessa,” is assigned to the variable name.
Variable scope
Scope: The scope of a variable refers to the places where we
can access a variable.
Local variable
A local variable is a variable that is accessible inside a
block of code only where it is declared. That means, If we
declare a variable inside a method, the scope of the local
variable is limited to the method only. So it is not
accessible from outside of the method. If we try to access
it, we will get an error.
Example
def test1(): # defining 1st function
price = 900 # local variable
print("Value of price in test1 function :", price)
# call functions
test1()
test2()
Run
In the above example, we created a function with the
name test1. Inside it, we created a local variable price.
Similarly, we created another function with the
name test2 and tried to access price, but we got an
error "price is not defined" because its scope is limited to
function test1(). This error occurs because we cannot access
the local variable from outside the code block.
Global variable
A Global variable is a variable that is defined outside of
the method (block of code). That is accessible anywhere in
the code file.
Example
# call functions
test1()
test2()
Run
In the above example, we created a global variable price and
tried to access it in test1 and test2. In return, we got the
same value because the global variable is accessible in the
entire file.
Example
n = 300
m = n
print(id(n)) # same memory address
print(id(m)) # same memory address
Run
It returns the same address location because both variables
share the same value. But if we assign m to some different
value, it points to a different object with a different
identity.
Run
For m = 500, Python created an integer object with the value
500 and set m as a reference to it. Similarly, n is assigned
to an integer object with the value 400 and sets n as a
reference to it. Both variables have different identities.
Object Reference
In Python, when we assign a value to a variable, we create
an object and reference it.
Example
a = 10
b = 10
print(id(a))
print(id(b))
c = 20
d = 20
e = 20
print(id(c))
print(id(d))
print(id(e))
Run
Output
140722211837248
140722211837248
140722211837568
140722211837568
140722211837568
import sys
print(sys.getrefcount(a))
print(sys.getrefcount(c))
Run
See the following image for more details.
a = 10
b = 20
c = 20
d = 40
tuple1 = a, b, c, d # Packing tuple
print(t) # (10, 20, 20, 40)
Run
Here a, b, c, d are packed in the tuple tuple1.
Example
Run
Note: When we are performing unpacking, the number of
variables and the number of values should be the same. That
is, the number of variables on the left side of the tuple
must exactly match a number of values on the right side of
the tuple. Otherwise, we will get a ValueError.
Example
a, b = 1, 2, 3
print(a,b)
Run
Output
a, b = 1, 2, 3