VARIABL
ES
PYTHON VARIABLES
Variables are the containers for
storing data values.
OUT P U T
:5
Example: john
X=5
Y=
“john”
Print(x)
Print(y)
1.PYTHON VARIABLES
NAMING RULES
1. Variable name should start with letter(a-z/A-Z) or
an underscore (_).
Valid : age , _age , Age Invalid : 1age
2.In variable name, no special characters allowed
other than underscore (_).
Valid : age_ , _age Invalid : age_*
3.Variables are case sensitive. age and Age are
different, since variable names are case sensitive.
4.Variable name can have numbers but not at the
beginning. Example: Age1
5.Reserve words (keyword)cannot be used as
identifier names . Keywords are also called as
reserved words.
print
b da
l am or
try
in
rai ass
se IF and ert
glo
exc fin
b
def elif
al
ept ally
return del
cla KEYWORD fals for
ss S e
as
wit im is
h tru por
not t
e pas
co
fro
n
m s
ti n
els whi
l
ue
bre
a
oc
e le
ak
nl
no
yield
To assign a value of python variable , you don’t need to declare
it’s type.
You name it according to rules started in section 2a,and type
the value after the equal sign(=).
1. >>> age=7
1. >>> age= OUTPUT 2. >>> print
‘Dinosaur’ Output :
(age)
2. >>> print (age) Dinosaur 7
You can assign values to multiple Python variables.
1. >>> age
,
city=21,’Indo
OUTPU
re’
T
21
Indore
Or you can assign the same value to multiple
Python variables.
1.>>> age = fav = OUTPUT 1. >>>
OUTPUT
7 77 a,b=‘red’ ,’blue’
blue red
2. >>> print 2. >>> a,b=b,a
(age,fav) 3. >>> print
(a,b)
You can also delete python variables using the keyword
‘del’.
1. >>> a =
‘red’
2. >>> del
a
OUTPUT: Traceback
3. >>> a (most recent call
last):
File
“<pyshe11#39>” , line 1, in <module>
a
Name Error: name ‘a’ is not
defined
SCOPE OF VARIABLES IN PYTHO
l
ba
l
ca
lo
Lo
os
-in
G
cl
ilt
d
En
Bu
SCOPE OF VARIABLE
The location where we can find a
Variable and also access it if
required
Is called the scope of a variable.
There are two basic scopes of
variables in python :
Global variables
Local variables
1.PYTHON LOCAL
VARIABLES
When you declare a variable in a function ,class or so , it is only
visible in that scope . If you call it outside of that scope ,you get an
‘undefined’ error.
Example:
def myfunc():
x = 300
print(x) O/P:
300
myfunc()
2.Global Variables
When you declare a variable outside any scope/Context , it
is visible in the whole program.
O/ P :
300
Example:
x = 3003
00
def
myfunc():
print(x)
myfunc()
Global variable and Local variable with same name
X=5
def foo():
local x: 10 x = 10
global x: 5 print (“local x:”, x)
foo()
Print (“global x:”, x)
1.What are variables and data types in python?
2.What is type() in python?
3.What are Local and Global variables in
Python?
4.Explain various naming rules for Python Variables.
5.How to display part of a string ?
PYTHON DATA TYPES
Data types are the classification or
categorization of data items . It represents the
kind of value that tells what operations can be
performed on a particular data . Since every
thing in an object in python programming , data
types are actually classes and variables are
instance of these classes.
Data Types In Python:
Numeric
Sequence Type
Boolean
PYTHON-DATA
TYPES
DICTIONAR SEQUENC
NUMERIC BOOLEAN SET
Y ETYPE
INTEGER FLOAT STRINGS TUPLE
COMPLEX
NUMBER LIST
1.PYTHON NUMBERS
There are four numeric PYTHON data types.
a.in
a.Int
Intt stands for integer . This python Data Type holds signed integers . We can
use the type()function to find which class it belong to.
1.>>> a=-7
2.>>> type(a)
O/P:
<class ‘int’ >
An integer can be of any length ,with the only limitation being the available
memory.
1. >>>
a=99999999999999999999999999
2. >>> type(a)
b.float
O/P:
<class ‘int’>
b. float This python data types holds floating-point real
values . An integer can only store the number 3,but float can store 3.25 if you
want.
1. >>>a=3.0
c.long
This python data type holds a long integer of unlimited length .But this
construct does not exist in Python 3.x.
d.complex
This Python data type holds a complex number . A complex number looks like
this:a+bj Here , a and b are the real parts of the number, and j is imaginary.
O/P:
<class ‘complex’>
2.STRINGS
A string is a sequence of characters . Python does not a char data type , unlike
C++ or Java . You can delimit a string using single quotes or double-quotes.
1. >>> city=‘Ahmedabad’
2. >>> city
B. Displaying Part of a String
You can display a character from a string using its index in
the string . Remember , indexing starts with 0.
1. >>> O/P: ‘d’
lesson=‘disappointment’
2. >>> lesson [0]
You can also display a burst of character in a string using the slicing
operator[].
1. >>> O/P:
lesson[5:1
0] ‘point’
String Concatenation
You can concatenate(join)
strings.
O/P:
1. >>> a=‘10’
1010
2. >>>
print(a+a)
However , you cannot concatenate values of different types.
O/P:
Traceback (most recent call last) :File
1. >>> “<pyshe11#89>” , line 1,in <module>;
print(’10’+10) Print(‘10’+10)
Type Error : must be str ,not int
3. PYTHON LISTS
A list is a collection of values. Remember ,it may contain different types of values.
To define a list , you must put values separated with commas in square brackets .You
don’t need to declare a type for a list either.
1. >>>
days==[‘Monday’,’Tuesday’,3,4,5,6,7] O/P: [‘Monday’, ’Tuesday’, 3, 4, 5,
2. >>> days 6, 7]
A . Slicing a List
You can slice a list the way you’d slice a string-
with the slicing operator.
O/P:
1.
>>>days [1:3] [ ‘Tuesday’ , 3]
Indexing for a list begins with 0,like for a string .A
Python doesn’t have arrays.
B . Length of a List
Python supports an inbuilt function to calculate
the length of a list.
1. >>> len (days) O/P: 7
C . Reassigning Elements of a List
A list is mutable . This means that you can reassign elements
later on .
1. >>> O/P:
days[2]=‘Wednesday’ [ ‘Monday’, ‘Tuesday’, ‘Wednesday’,4, 5, 6,
2. >>> days 7]
D . Iterating on the
List over the list we can use the for loop . By iterating ,we can access each element
To iterate
one by one which is very helpful when we need to perform some operations on each
element of list.
O/P:
1.nums = [1,2,5,6,8]
1
2.for n in nums:
3.print(n) 2
5
6
8
E . Multidimensional List
A list may have more than one dimension . Have a detailed look on this in
DataFlair ’s tutorial on Python Lists .
O/P:
1. >>> a=[[1,2,3] , [4,5,6]]
[[1 , 2, 3] , [4, 5, 6]]
2. >>>
a
4.PYTHON TUPLES
A tuples is like a list . You declare it using parentheses instead.
1. O/P:
>>>subjects=(‘physics’,‘Chemistry’,’Ma (‘Physics’, ‘Chemistry’, ‘Maths’)
ths’)
2. >>> subjects
Accessing and Slicing a Tuple
You access a tuple the same way as you’d access a list . The same
goes for slicing it.
O/P:
1. >>>
subjects[1] ‘chemistry’
O/P:
1.
>>>subjects[0:2] (‘Physics’ ,’Maths’)
5.Dictionaries
A dictionary holds key-value pairs . Declare it in curly braces , with pairs separated
by commas . Separate keys and values by a colon (:).
1. >>>
person={‘city’:’Ahmedabad’,’age’:7}
2. >>> person
O/P:
{ ‘city’: ‘Ahmedabad’ , ‘age’ : 7 }
The type() function works with
dictionaries too.
1. >>> type O/P:
(person) <class ‘dict’>
Accessing a Value
To access a value , you mention the key in square brackets.
O/P:
1.
‘Ahmedabad’
>>>person[‘city’]
Reassigning Elements
You can reassign a value to a key.
1. >>> O/P:
person[‘age’]=21
2. 21
6.Bool
>>>person[‘age’]
A Boolean value can be True or
False.
1.
O/P: {1, 2, 3}
>>> a={1,2,3}
2.
>>>7.Sets
a
A set can have a list of values . Define it using curly braces.
1. >>> a=2>1 O/P:
2. >>> type(a) <class
‘bool’>
It returns only one instance of any value present more than once.
O/P:
1.
{1, 2,
>>> a={1,2,2,3}
3}
2.
>>> a