Variables
Table of contents
1.Variables and constants
2.Rules to write variable name
3.Create variables
4.Print variables
5.Changing value of a variable
6.Summary
01
Variables
and
Constants
let's learn with an example :
Variables are containers for storing data
values.
Things inside this box are called
as variable(value)
The box is called as
location(address)
Variables and Constants in python are the same as in Mathematics
In Mathematics,
If we are asked to find the average of two
numbers.
We assume two variables x and y.
average = (x + y)/2
If x=70 and y=30
average = (70+30)/2 = 50
Syntax:
Variable name = value
Example:
• x and y are variables which
can store any values that they
are assigned.
i a bl e s • 70 and 30 are the constants
Va r
which are assigned to a and b
respectively
Open notepad and type this code and save it as variable.py
Make sure to save as .py extension.
assigning 5 to x
assigning john to y
displays x and y
Open the terminal and type “python name of file with .py extension” . For the previous
example type python variable.py.
Values of x and y
Constants:
A constant is a type of variable that holds values, which cannot be changed.
Example:
create a file and save it as
constant.py
create another file and import
contant.py file and access the
constant value
You can see the constant value
Rules to write
a Variable
name
02
Rules to write a Variable names can be made up
Variable name of letters , numbers, and the
underscore character (_).
01 03
Variable names can’t start
A variable name can’t contain a
with a number
space , so use an underscore to
separate words.
Legal and Illegal Variables
Legal variables Illegal Variables
no of cars = 14
name = “John“ #spaces are not allowed
_my_name = "John“
count= 20 2myvar = "John”
Var1 = “Hello” #starting with a number
is not allowed
Legal
variables
Illegal
Variables
Creation of variables
The variable and its data types are created once any value is
assigned to it.
cost=30.20
length =20
A variable called
A variable called cost is created
length is created and its value is
and its value is 20 30.20
Printing variables
To find out what value a variable stores, enter print in the
shell, followed by the variable name in parentheses
value 89 is assigned to x and it is
displayed
Python reserved words
Python has a set of keywords that are reserved words that cannot be used as variable names.
and def exec if not return
assert del finally import or try
break elif for in pass while
class else from is print with
continue expect global lamda raise yield
Changing value
of variables
Initially we assign value of x as 12
Later we changed value of x to 10
Summary:
What did you learn ?
1. Variables and Constants
2. Rules to write variables
3. Creation of variables
4. Print variables
5. Changing value of variables