Python Variables and Data Types
Python Variables and Data Types
Python Variables
A variable is a named location used to store data in the memory. It is helpful to think of
variables as a container that holds data that can be changed later in the program. For
example,
number = 10
Here, we have created a variable named number. We have assigned the value 10 to the
variable.
You can think of variables as a bag to store books in it and that book can be
replaced at any time.
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1.
Assigning values to Variables in Python
As you can see from the above example, you can use the assignment operator = to
assign a value to a variable.
Output
apple.com
In the above program, we assigned a value apple.com to the variable website. Then, we
printed out the value assigned to website i.e. apple.com
Note: Python is a type-inferred language, so you don't have to explicitly define the
variable type. It automatically knows that apple.com is a string and declares the
website variable as a string.
Example 2: Changing the value of a variable
website = "apple.com"
print(website)
print(website)
Output
apple.com
ABCD.com
In the above program, we have assigned apple.com to the website variable initially.
Then, the value is changed to ABCD.com.
Example 3: Assigning multiple values to multiple variables
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
If we want to assign the same value to multiple variables at once, we can do this
as:
x = y = z = "same"
print (x)
print (y)
print (z)
The second program assigns the same string to all the three variables x, y and z.
Constants
A constant is a type of variable whose value cannot be changed.
It is helpful to think ofconstants as containers that hold information which cannot be
changed later.
You can think of constants as a bag to store some books which cannot be replaced once
placed inside the bag.
Assigning value to constant in Python
In Python, constants are usually declared and assigned in a module. Here, the module is a new
file containing variables, functions, etc. which is imported to the main file. Inside the module,
constants are written in all capital letters and underscores separating the words.
Example 3: Declaring and assigning value to a constant
Create a constant.py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant
print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
In the above program, we create a constant.py module file. Then, we assign the constant value
to PI and GRAVITY. After that, we create a main.py file and import the constant module. Finally,
we print the constant value.
Note: In reality, we don't use constants in Python. Naming them in all capital letters
is a convention to separate them from variables, however, it does not actually
prevent reassignment.
Rules and Naming Convention for Variables and constants
• Constant and variable names should have a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:
snake_case
MACRO_CASE
camelCase
CapWords
• Create a name that makes sense. For example, vowel makes more sense than v.
• If you want to create a variable name having two words, use underscore to separate them.
For example:
my_name
current_salary
• Use capital letters possible to declare a constant. For example:
PI
G
MASS
SPEED_OF_LIGHT
TEMP
• Never use special symbols like !, @, #, $, %, etc.
• Don't start a variable name with a digit.
Scope of Variable
Scope of a variable in python is not different than other programming languages. Here also
variable follows same rule i.e., if a variable is defined inside a function, then its scope is inside
the function only and variables which are declared outside of any function block globally do
possess a global scope.
In above program we declared variable with same name inside a function. If you remember
how we manipulated the value of variable but here it didn’t work because Python
considered it as declaration inside function scope i.e., local scope.
Data Types in Python
Data type classifies the variable. It tells what kind of values are acceptable
for a particular variable , what mathematical, relational or logical operations
we can perform without any errors.
Python provides some basic data types as well some advance and very useful
data types. Everything in Python is an object, variables are instance whereas
data types are classes.
Data Types
Number
Number can be an Integer, Float and Complex in Python. They are defined as int, float
and complex class in Python.
type() :This function can be used to know which class a variable or a value belongs.
b=5
print(b, "is of type", type(b))
b = 22.05
print(b, "is of type", type(b))
b = 1+2j
print(b, "is complex number?", isinstance(1+2j,complex))
Output
(5, 'is of type', <type 'int'>)
(22.05, 'is of type', <type 'float'>)
((1+2j), 'is complex number?', True)
Integers in Python are same as any other programming language. The only limitation is
the memory available. Floating numbers are accurate upto 15 decimal places. Decimal
numbers are separated by decimal points. 2 is an integer and 2.3 is float. Complex
numbers are written as (x + 2j) where one is real and another one is imaginary part. Here
‘x’ is real part and ‘2j’ is our imaginary part.
Example
>>> integer = 123456787465454813165
>>> integer
123456787465454813165
>>> b = 0.1215487465415486
>>> b
0.1215487465415486
>>> c = 1 + 2j
>>> c
(1+2j)
Booleans
The boolean data type is either True or False.
In Python, boolean variables are defined by the True and False keywords.
>>> a = True
>>> type(a)
<class 'bool'>
>>> b = False
>>> type(b)
<class 'bool'>
The output <class 'bool'> indicates the variable is a boolean data type.
Note the keywords True and False must have an Upper Case first letter. Using a lowercase
true returns an error.
List
List is a data type in Python which you can relate to arrays in some other programming
languages. But arrays are homogeneous means same type of variable can be stored
whereas in Python list, you can store any type of item in it. Declaring a Python list is very
straight forward, you just need to write all values comma separated inside square
brackets.
Example 1
Suppose you want to store heights of a group then you can store them in list as below :
Example 2
We will access our height list created earlier
print(Height[0])
Example 4
Values = [ 1, 2, 3, 4,5, 6]
Values[0] = 9
print(Values)
Output
[9, 2, 3, 4, 5, 6]
We can use slicing operator [ ] to get a subset list or a particular item. Slicing a very
useful feature in Python
Example:
#Here we are declaring a tuple named score:
Score = (20,30,55,68,12,32)
#All the different types in Python - String, Integer, Float can all be contained in tuple.
Tuple1 = (‘person’, 20, 12.5)
Each element of tuple can be accessed via index same as lists.
Index Value
0 person
1 20
2 12.5
Accessing Tuples
# accessing 0 index
print(Tuple1[0])
Output
person
Declaring a String
str_var = ‘STRING’
str2 = “i am string”
Note: Python does not have a character data type, a single character is simply a string
with a length of 1.
Strings also support the slicing operator after all its sequence of characters.
Example
R = "Hello World"
print("R[4] =", R[4]);
print("R[1:3]=",R[1:3])
Output
('R[4] =', 'o')
('R[1:3]=', 'el')
String Operators
String operators represent the different types of operations that can be employed on the
string type of variables in the program. Python allows several string operators that can be
applied on the python string are as below:
• Assignment operator: “=”
• Concatenate operator: “+”
• String repetition operator: “*”
• String slicing operator: “[]”
• String comparison operator: “==” & “!=”
• Membership operator: “in” & “not in”
• Escape sequence operator: “\”
• String formatting operator: “%” & “{}”
Example #1 – Assignment Operator “=”
Python string can be assigned to any variable with an assignment operator “= “. Python
string can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes [‘’’
‘’’]. var_name = “string” assigns “string” to variable var_name.
Code:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
Output:
print(string1)
print(string2)
print(string3)
Example #2 – Concatenate Operator “+”
Two strings can be concatenated or join using “+” operator in python as
explained in below example code:
Code:
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)
Output:
hello world
Example #3 – String Repetition Operator “*”
The same string can be repeated in python by n times using string*n as explained in the
below example.
Code:
Output:
Example #4 – String slicing operator “[]”
Characters from a specific index of the string can be accessed with the string[index] operator.
The index is interpreted as a positive index starting from 0 from the left side and negative
index starting from -1 from the right side.
•string[a]: Returns a character from a positive index a of the string from the left
side as displayed in the index graph above.
•string[-a]: Returns a character from a negative index a of the string from the right
side as displayed in the index graph above.
•string[a:b]: Returns characters from positive index a to positive index b of the as
displayed in index graph above.
•string[a:-b]: Returns characters from positive index a to the negative index b of the
string as displayed in the index graph above.
•string[a:]: Returns characters from positive index a to the end of the string.
•string[:b] Returns characters from the start of the string to the positive index b.
•string[-a:]: Returns characters from negative index a to the end of the string.
•string[:-b]: Returns characters from the start of the string to the negative index b.
•string[::-1]: Returns a string with reverse order.
Code:
Output:
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
Example #5 – String Comparison Operator “==” & “!=”
String comparison operator in python is used to compare two strings.
•“==” operator returns Boolean True if two strings are the same and return
Boolean False if two strings are not the same.
•“!=” operator returns Boolean True if two strings are not the same and return
Boolean False if two strings are the same.
These operators are mainly used along with if condition to compare two strings
where the decision is to be taken based on string comparison.
Code:
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)
Output:
Example #6 – Membership Operator “in” & “not in”
Membership operator is used to searching whether the specific character is
part/member of a given input python string
•“a” in string: Returns boolean True if “a” is in the string and returns False if
“a” is not in the string.
•“a” not in string: Returns boolean True if “a” is not in the string and returns
False if “a” is in the string.
A membership operator is also useful to find whether specific substring is part
of a given string.
Code:
string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)
Output:
Example #7 – Escape Sequence Operator “\”
To insert a non-allowed character in the given input string, an escape character is used. An
escape character is “\” or “backslash” operator followed by a non-allowed character. An
example of a non-allowed character in python string is inserting double quotes in the string
surrounded by double-quotes.
Code:
Output:
2. Example of non-allowed double quotes with escape sequence
operator:
Code:
Output:
Example #8 – String Formatting Operator “%”
String formatting operator is used to format a string as per requirement. Toinsert
another type of variable along with string, the “%” operator is used along with
python string. “%” is prefixed to another character which indicates the typeof the
value which we want to insert along with python string. Please refer below table
for some of the commonly used different string formatting specifiers:
Code:
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Output:
Set
Sets are type of collections like list and tuples which means you can input
different Python types. Sets are unordered whereas list and tuples are ordered
collections. Sets don’t have any record for the element position they only
contain unique elements.
• A set is a collection which is both unordered and unindexed and
unchangeable.
• Unordered means that the items in a set do not have a defined order.
• Set items can appear in a different order every time you use them, and
cannot be referred to by index or key.
• Sets are unordered, so you cannot be sure in which order the items will
appear.
Creating a set
You can create a set with curly braces and in between the elements you want to put.
Example
Set1 = { 1, 2, 1, 3, 4, 5 }
print(Set1)
You can see that we have kept a duplicate element inside set while declaring but when
the actual set is created this element will be removed and you will get only unique
elements.
Output
set([1, 2, 3, 4, 5])
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
Output
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# initialize a with {}
a = {}
We cannot access or change an element of a set using indexing or slicing. Set data type
does not support it.
We can add a single element using the add() method, and multiple elements using the
update() method. The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
# initialize my_set
my_set = {1, 3}
print(my_set)
# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set) Output
A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set unchanged if
the element is not present in the set. On the other hand, the remove() function will raise an
error in such a condition (if element is not present in the set).
Since set is an unordered data type, there is no way of determining which item will be
popped. It is completely arbitrary.
We can also remove all the items from a set using the clear() method.
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element
my_set.pop() Output
print(my_set)
# clear my_set {'H', 'l', 'r', 'W', 'o', 'd', 'e'}
# Output: set() H
my_set.clear() {'r', 'W', 'o', 'd', 'e'}
print(my_set) set()
print(my_set)
Python Set Operations
Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods.
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Set Union
Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished using the union()
method.
# Set union method
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Output
{1, 2, 3, 4, 5, 6, 7, 8}
# use union function
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the
intersection() method.
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on B
>>> B - A
{8, 6, 7}
While indexing is used with other data types to access values, a dictionary uses keys.
Keys can be used either inside square brackets [] or with the get() method.
If we use the square brackets [], KeyError is raised in case a key is not found in the
dictionary. On the other hand, the get() method returns None if the key is not found.
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
Output
# Output: 26
Jack
print(my_dict.get('age'))
26
# Trying to access keys which doesn't exist throws errorNone
# Output None Traceback (most recent call last):
print(my_dict.get('address')) File "<string>", line 15, in
<module>
print(my_dict['address'])
# KeyError
print(my_dict['address']) KeyError: 'address'
Changing and Adding Dictionary elements
Dictionaries are mutable. We can add new items or change the value of existing items
using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
The popitem() method can be used to remove and return an arbitrary (key, value) item
pair from the dictionary. All the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary
itself.
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value # Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item, return (key,value) # Output: (5, 25)
print(squares.popitem()) Output
# Output: {1: 1, 2: 4, 3: 9} 16
print(squares) {1: 1, 2: 4, 3: 9, 5: 25}
# remove all items (5, 25)
squares.clear() {1: 1, 2: 4, 3: 9}
# Output: {} {}
print(squares) Traceback (most recent call last):
# delete the dictionary itself File "<string>", line 30, in <module>
del squares print(squares)
# Throws Error NameError: name 'squares' is not defined
print(squares)
Manipulate or add elements in dictionary
my_info = {'name':'Rahul', 'age': 25}
# update value
my_info['age'] = 26
# add item
my_info['address'] = 'India'
Type conversion is the process of converting data types from one type to another.
For example, an integer value is converted into a float, or a string is converted into a
number.
Type conversion can occur in one of the two types –
•Implicit Conversion
•Explicit Conversion
1. Implicit Conversion in Python
In implicit conversion, the Python automatically converts the value from one type to
another.
For example: when we add an integer and a float value, the resultant will be in float value.
In these types of situations, Python always converts the smaller data types into larger data
types so that data is not lost.
X = 12
Y = 20.50
Z=X+Y
print(Z)
type(X)
type(Y)
type(Z)
Output:
32.5
<class ‘int’>
<class ‘float’>
<class ‘float’>
However, when we add a string and an integer together, Python is not able to
use implicit conversion and it will give us a TypeError.
We can achieve this task by explicitly converting the data type.
>>> int(10.23)
10
>>> int(-11.96)
-11
Summary
Python has flexible and powerful data structures with in-built functions for all basic
manipulation