002 Python Variables and Python Data Types Updated
002 Python Variables and Python Data Types Updated
In this Python lesson on Python Variables and Python Data Types, we will learn about at Python
variables and data types being used in Python. Since we know that Python is a dynamically-typed
language, we don’t specify the type of a variable when declaring one. We will also learn about
converting one data type to another in Python and local and global variables in Python.
A variable is a container for a value. It can be assigned a name; you can use it to refer to it later in the
program. Based on the value assigned, the interpreter decides its data type. You can always store a
different type in a variable.
For example, if you store 7 in a variable, later, you can store ‘Dinosaur’.
There are certain rules to what you can name a variable (called an identifier).
>>> 9lives=9
>>> flag=0
2|Page Introduction to programming using Python
>>> flag
>>> _9lives='cat'
>>> _9lives
‘cat’
2. The rest of the identifier may contain letters(A-Z/a-z), underscores (_), and numbers (0-9).
>>> year2='Sophomore'
>>> year2
‘Sophomore’
>>> _$$=7
3. Python is case-sensitive, and so are Python identifiers. Name and name are two different identifiers.
>>> name='A'
>>> name
‘Ayushi’
>>> Name
To assign a value to Python variables, you don’t need to declare its type. You name it according to the
rules stated in section 2a, and type the value after the equal sign (=).
>>> age=7
>>> print(age)
7
3|Page Introduction to programming using Python
>>> age='Dinosaur'
>>> print(age)
Dinosaur
However, age=Dinosaur doesn’t make sense. Also, you cannot use python variables before assigning it a
value.
>>> name
You can’t put the identifier on the right-hand side of the equal sign, though. The following code causes
an error.
>>> 7=age
>>> False=choice
c. Multiple Assignment
>>> age,city=21,'Indore'
>>> print(age,city)
21 Indore
>>> age=fav=7
>>> print(age,fav)
77
d. Swapping variables
Swapping means interchanging values. To swap Python variables, you don’t need to do much.
4|Page Introduction to programming using Python
>>> a,b='red','blue'
>>> a,b=b,a
>>> print(a,b)
blue red
e. Deleting variables
You can also delete python variables using the keyword ‘del’.
>>> a='red'
>>> del a
>>> a
Although we don’t have to declare type for python variables, a value does have a type. This information
is vital to the interpreter. Python supports the following Python data types.
a. Python Numbers
1. int– int stands for integer. This Python Data Type holds signed
integers. We can use the type() function to find which class it
belongs to.
>>> a=-7
>>> type(a)
<class ‘int’>
An integer can be of any length, with the only limitation being the available memory.
>>> a=9999999999999999999999999999999
>>> type(a)
<class ‘int’>
2. float– This Python Data Type holds floating point real values. An
int can only store the number 3, but float can store 3.25 if you
want.
>>> a=3.0
>>> type(a)
<class ‘float’>
>>> a=2+3j
>>> type(a)
<class ‘complex’>
Use the isinstance() function to tell if python variables belong to a particular class. It takes two
parameters- the variable/value, and the class.
>>> print(isinstance(a,complex))
True
b. Strings
A string is a sequence of characters. Python does not have a char data type, unlike C++ or Java. You can
delimit a string using single quotes or double quotes.
>>> city='Ahmedabad'
6|Page Introduction to programming using Python
>>> city
‘Ahmedabad’
>>> city="Ahmedabad"
>>> city
‘Ahmedabad’
>>> var="""If
only"""
>>> var
‘If\n\tonly’
>>> print(var)
If
Only
>>> """If
only"""
‘If\n\tonly’
As you can see, the quotes preserved the formatting (\n is the escape sequence for newline, \t is for tab).
>>> lesson='disappointment'
>>> lesson[0]
‘d’
You can also display a burst of characters in a string using the slicing operator [].
>>> lesson[5:10]
‘point’
>>> x=10;
>>> printer="Dell"
>>> print("I just printed %s pages to the printer %s" % (x, printer))
>>> a='10'
>>> print(a+a)
1010
>>> print('10'+10)
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.
>>> days=['Monday','Tuesday',3,4,5,6,7]
>>> days
[‘Monday’, ‘Tuesday’, 3, 4, 5, 6, 7]
1. Slicing a list – You can slice a list the way you’d slice a
string- with the slicing operator.
>>> days[1:3]
[‘Tuesday’, 3]
Indexing for a list begins with 0, like for a string. A Python doesn’t have arrays.
>>> len(days)
>>> days[2]='Wednesday'
>>> days
>>> a=[[1,2,3],[4,5,6]]
>>> a
d. Python Tuples
>>> subjects=('Physics','Chemistry','Maths')
>>> subjects
1. Accessing and Slicing a Tuple– You access a tuple the same way as you’d access a list. The same
goes for slicing it.
>>> subjects[1]
‘Chemistry’
>>> subjects[0:2]
(‘Physics’, ‘Chemistry’)
e. Dictionaries
A dictionary holds key-value pairs. Declare it in curly braces, with pairs separated by commas. Separate
keys and values by a colon (:).
>>> person={'city':'Ahmedabad','age':7}
>>> person
>>> type(person)
<class ‘dict’>
>>> person['city']
‘Ahmedabad’
21
>>> person.keys()
f. bool
>>> a=2>1
>>> type(a)
10 | P a g e Introduction to programming using Python
<class ‘bool’>
g. Sets
>>> a= {1,2,3}
>>> a
{1, 2, 3}
It returns only one instance of any value present more than once.
>>> a= {1,2,2,3}
>>> a
{1, 2, 3}
>>> a [2]
Also, it is mutable. You can change its elements or add more. Use the add () and remove () methods to
do so.
>>> a= {1,2,3,4}
>>> a
{1, 2, 3, 4}
>>> a.remove(4)
>>> a
{1, 2, 3}
{1, 2, 3, 4}
4. Type Conversion
Since Python is dynamically-typed, you may want to convert a value into another type. Python supports
a list of functions for the same.
11 | P a g e Introduction to programming using Python
a. int ()
3
Notice how it truncated 0.7 instead of rounding the number off to 4. You can also turn a Boolean into an
int.
>>> int("a")
77
b. float ()
7.0
7.7
1.0
11.0
>>> float("2.1e-2")
0.021
0.021
However, this number works even without the float () function.
>>> 2.1e-2
0.021
c. str ()
‘2.1’
‘7’
‘True’
You can also convert a list, a tuple, a set, or a dictionary into a string.
‘[1, 2, 3]’
d. bool ()
True
False
True
True
>>> bool([1,2])
True
>>> bool ()
False
>>> bool ([])
False
>>> bool ({})
False
False
e. set ()
{1, 2, 3}
{1, 2, 3}
f. list ()
[1, 2, 3]
>>> list({"a":1,"b":2})
[‘a’, ‘b’]
g. tuple ()
(1, 2, 3)
You can try your own combinations. Also try composite functions.
(1, 2)
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.
2
15 | P a g e Introduction to programming using Python
>>> uvw
b. Global variables
When you declare a variable outside any context/scope, it is visible in the whole program.
>>> xyz=3
>>> def func2():
xyz=0
xyz+=1
print(xyz)
>>> func2()
>>> xyz
You can use the ‘global’ keyword when you want to treat a variable as global in a local scope.
>>> foo=1
>>> def func2():
global foo
foo=3
print(foo)
>>> func2()
>>> foo