Python Variables and Data Types
Python Variables and Data Types
Python Variables and Data Types
In this Python tutorial, we will learn about Python variables and data types
being used in Python.
We will also learn about converting one data type to another in Python and
local and global variables in Python.
So, let’s begin with Python variables and data types Tutorial.
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’.
Output
SyntaxError: invalid syntax
>>> flag=0
>>> flag
>>> _9lives='cat'
>>> _9lives
Output
‘cat’
Output
‘Sophomore’
>>> _$$=7
Output
SyntaxError: invalid syntax
>>> Name
Output
Traceback (most recent call last):
File “<pyshell#21>”, line 1, in <module>
Name
NameError: name ‘Name’ is not defined
You name it according to the rules stated in section 2a, and type the value
after the equal sign(=).
>>> age=7
>>> print(age)
Output
7
>>> age='Dinosaur'
>>> print(age)
Output
Dinosaur
However, age=Dinosaur doesn’t make sense. Also, you cannot use Python
variables before assigning it a value.
>>> name
Output
Traceback (most recent call last):
File “<pyshell#8>”, line 1, in <module>
name
NameError: name ‘name’ is not defined
You can’t put the identifier on the right-hand side of the equal sign, though.
The following code causes an error.
>>> 7=age
Output
SyntaxError: can’t assign to literal
>>> False=choice
Output
SyntaxError: can’t assign to keyword
3. Multiple Assignment
You can assign values to multiple Python variables in one statement.
>>> age,city=21,'Indore'
>>> print(age,city)
Output
21 Indore
>>> age=fav=7
>>> print(age,fav)
Output
77
4. Swapping Variables
Swapping means interchanging values. To swap Python variables, you don’t
need to do much.
>>> a,b='red','blue'
>>> a,b=b,a
>>> print(a,b)
Output
blue red
5. Deleting Variables
You can also delete Python variables using the keyword ‘del’.
>>> a='red'
>>> del a
>>> a
Output
Traceback (most recent call last):
File “<pyshell#39>”, line 1, in <module>
a
NameError: name ‘a’ is not defined
Python Data Types
Although we don’t have to declare a type for Python variables, a value does
have a type. This information is vital to the interpreter.
1. Python Numbers
There are four numeric Python data types.
a. 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)
Output
<class ‘int’>
An integer can be of any length, with the only limitation being the available
memory.
>>> a=9999999999999999999999999999999
>>> type(a)
Output
<class ‘int’>
b. 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)
Output
<class ‘float’>
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.
>>> a=2+3j
>>> type(a)
Output
<class ‘complex’>
Output
True
2. 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'
>>> city
Output
‘Ahmedabad’
>>> city="Ahmedabad"
>>> city
Output
‘Ahmedabad’
>>> var="""If
only"""
>>> var
Output
‘If\n\tonly’
>>> print(var)
Output
If
Only
>>> """If
only"""
Output
‘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]
Output
‘d’
You can also display a burst of characters in a string using the slicing operator
[].
>>> lesson[5:10]
Output
‘point’
c. String Formatters
String formatters allow us to print characters and values at once. You can use
the % operator.
>>> x=10;
>>> printer="Dell"
>>> print("I just printed %s pages to the printer %s" % (x, printer))
>>> print("I just printed {0} pages to the printer {1}".format(x, printer))
>>> print("I just printed {x} pages to the printer {printer}".format(x=7, printer="Dell"))
d. String Concatenation
You can concatenate(join) strings.
>>> a='10'
>>> print(a+a)
Output
1010
>>> print('10'+10)
Output
Traceback (most recent call last):File “<pyshell#89>”, line 1, in <module>;
print(’10’+10)
TypeError: 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.
>>> days=['Monday','Tuesday',3,4,5,6,7]
>>> days
Output
[‘Monday’, ‘Tuesday’, 3, 4, 5, 6, 7]
a. Slicing a List
You can slice a list the way you’d slice a string- with the slicing operator.
>>> days[1:3]
Output
[‘Tuesday’, 3]
Indexing for a list begins with 0, like for a string. A Python doesn’t have
arrays.
c. Length of a List
Python supports an inbuilt function to calculate the length of a list.
>>> len(days)
Output
7
>>> days[2]='Wednesday'
>>> days
Output
[‘Monday’, ‘Tuesday’, ‘Wednesday’, 4, 5, 6, 7]
nums = [1,2,5,6,8]
for n in nums:
print(n)
Output
1
2
5
6
8
e. Multidimensional Lists
A list may have more than one dimension. Have a detailed look on this in
DataFlair’s tutorial on Python Lists.
>>> a=[[1,2,3],[4,5,6]]
>>> a
Output
[[1, 2, 3], [4, 5, 6]]
4. Python Tuples
A tuple is like a list. You declare it using parentheses instead.
>>> subjects=('Physics','Chemistry','Maths')
>>> subjects
Output
(‘Physics’, ‘Chemistry’, ‘Maths’)
>>> subjects[1]
Output
‘Chemistry’
>>> subjects[0:2]
Output
(‘Physics’, ‘Chemistry’)
b. A tuple is Immutable
Python tuple is immutable. Once declared, you can’t change its size or
elements.
>>> subjects[2]='Biology'
Output
Traceback (most recent call last):
File “<pyshell#107>”, line 1, in <module>
subjects[2]=’Biology’
TypeError: ‘tuple’ object does not support item assignment
Output
Traceback (most recent call last):
File “<pyshell#108>”, line 1, in <module>
subjects[3]=’Computer Science’
TypeError: ‘tuple’ object does not support item assignment
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(:).
>>> person={'city':'Ahmedabad','age':7}
>>> person
Output
{‘city’: ‘Ahmedabad’, ‘age’: 7}
>>> type(person)
Output
<class ‘dict’>
a. Accessing a Value
To access a value, you mention the key in square brackets.
>>> person['city']
Output
‘Ahmedabad’
b. Reassigning Elements
You can reassign a value to a key.
>>> person['age']=21
>>> person['age']
Output
21
c. List of Keys
Use the keys() function to get a list of keys in the dictionary.
>>> person.keys()
Output
dict_keys([‘city’, ‘age’])
6. bool
A Boolean value can be True or False.
>>> a=2>1
>>> type(a)
Output
<class ‘bool’>
7. Sets
A set can have a list of values. Define it using curly braces.
>>> a={1,2,3}
>>> a
Output
{1, 2, 3}
It returns only one instance of any value present more than once.
>>> a={1,2,2,3}
>>> a
Output
{1, 2, 3}
However, a set is unordered, so it doesn’t support indexing.
>>> a[2]
Output
Traceback (most recent call last):
File “<pyshell#127>”, line 1, in <module>
a[2]
TypeError: ‘set’ object does not support indexing
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
Output
{1, 2, 3, 4}
>>> a.remove(4)
>>> a
Output
{1, 2, 3}
>>> a.add(4)
>>> a
Output
{1, 2, 3, 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.
1. int()
It converts the value into an int.
>>> int(3.7)
Output
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(True)
Output
1
>>> int(False)
>>> int("a")
Output
Traceback (most recent call last):
File “<pyshell#135>”, line 1, in <module>;
int(“a”)
ValueError: invalid literal for int() with base 10: ‘a’
>>> int("77")
Output
77
2. float()
It converts the value into a float.
>>> float(7)
Output
7.0
>>> float(7.7)
Output
7.7
>>> float(True)
Output
1.0
>>> float("11")
Output
11.0
>>> float("2.1e-2")
Output
0.021
>>> float(2.1e-2)
Output
0.021
>>> 2.1e-2
Output
0.021
3. str()
It converts the value into a string.
>>> str(2.1)
Output
‘2.1’
>>> str(7)
Output
‘7’
>>> str(True)
Output
‘True’
You can also convert a list, a tuple, a set, or a dictionary into a string.
>>> str([1,2,3])
Output
‘[1, 2, 3]’
4. bool()
It converts the value into a boolean.
>>> bool(3)
Output
True
>>> bool(0)
Output
False
>>> bool(True)
Output
True
>>> bool(0.1)
Output
True
>>> bool([1,2])
Output
True
>>> bool()
Output
False
>>> bool([])
Output
False
>>> bool({})
Output
False
>>> bool(None)
Output
False
5. set()
It converts the value into a set.
>>> set([1,2,2,3])
Output
{1, 2, 3}
>>> set({1,2,2,3})
Output
{1, 2, 3}
6. list()
It converts the value into a list.
Output
[‘1’, ‘2’, ‘3’]
>>> list({1,2,2,3})
Output
[1, 2, 3]
>>> list({"a":1,"b":2})
Output
[‘a’, ‘b’]
>>> list({a:1,b:2})
Output
Traceback (most recent call last):
File “<pyshell#173>”, line 1, in <module>;
list({a:1,b:2})
TypeError: unhashable type: ‘set’
7. tuple()
It converts the value into a tuple.
>>> tuple({1,2,2,3})
Output
(1, 2, 3)
You can try your own combinations. Also try composite functions.
>>> tuple(list(set([1,2])))
Output
(1, 2)
Output
2
>>> uvw
Output
Traceback (most recent call last):
File “<pyshell#76>”, line 1, in <module>
uvw
NameError: name ‘uvw’ is not defined[/php]
2. 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()
Output
1
>>> xyz
Output
3
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()
Output
3
>>> foo
Output
3
Summary
In this tutorial on Python Variables and data types, we learned about different
Python variables and data types with examples.
We looked at the naming rules, and defining and deleting them. Then we saw
different types of data- numbers, strings, lists, dictionaries, tuples, sets, and
many more.
We also learned how to convert one variable type into another and local and
global variables in Python.