Monday, 8 July 2019

Variable

So far we discussed

1.  Identifier
2.  Reserved Words

Variable:

A variable name is an identifier that occupies some part of the memory.
A Variable can hold only one value, it is not possible to store more than one value.
Python does not have variables as such, but Python has Object References. We will use the terms variable and object reference interchangeably.

A Variable (Object Reference)does two things:

(1.) It tells the computer what the variable name is
(2.) It specifies what type of data the variable will hold.

Syntax:

objectReference=data

Example:
a=10
Here PVM (Python Virtual Machine) creates one memory location for 10, then this 10 is referred to  'a'. Here value 10 is treated as an object.

Rules for the Variable:

(1.)  1s t character must be alphabet (or) underscore

Ex: 
a=10
123a=5 #error

(2.) Keywords/reserved words are not used as a variable.

Ex: 
for=5 #error
FOR=5 # ok

>>> if=6
SyntaxError: invalid syntax
>>> FOR=2
>>> print(FOR)
2
>>> IF=8
>>> print(IF)
8
>>> 

3. It can be upper case lower case

Ex: 
A=10
b=4

4. Special characters are not allowed.\

Ex: 

$cash=100 # error
a=5
Here a holds the address of object (data/value) 5.

#Ex2.py
x=5
y="Rajendra" # ‘Rajendra’
print(x)
print(y)

#output
5
Rajendra








#Ex3.py:
"""This programs explains the variable
concept"""
a,b,c="vij","hyd","blore"
print(a)
print(b)

Output

"""Ex4.py"""
a = b = c = "rajendra"

print(a)
print(b)
print(c)



Valid
Invalid
a=10
A=4.56
Here a, A are different variables
if=10 bcoz ‘if’ is keyword
IF=10 #OK
a b c=10 #error because space
a=2.3
a=”rajendra”
a=10
b
print(a)
print(b) #Error because value was not initialised


Assignment:

n1 = 123 # single variable assignmentand
n2 = n3 = n4 = n1 # multi variable assignment of same value
print(n3) a, b, c, d = 10, 20, 30, 40 #multi variable
print(a, b, c, d)
#output:
123
10 20 30 40

Youtube channel click here to see this video

Next topic: Data types
Previous topic: Reserved word


Assessment Exam2
You may like the following topics:
Reserved word
Example programs on variables


1 comment:

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...