Unit_I_partII
Unit_I_partII
Python data types are actually classes, and the defined variables are their instances or objects. Since
Python is dynamically typed, the data type of a variable is determined at runtime based on the assigned
value.
In general, the data types are used to define the type of a variable. It represents the type of data we are
going to store in a variable and determines what operations can be done on it.
Each programming language has its own classification of data items. With these datatypes, we can store
different types of data values.
As long as the same sequence of characters is enclosed, single or double or triple quotes don't matter.
Hence, following string representations are equivalent.
>>> 'PTRSU'
' PTRSU '
>>> “PTRSU "
' PTRSU '
>>> ''' PTRSU '''
' PTRSU '
A string is a non-numeric data type. Obviously, we cannot perform arithmetic operations on it.
However, operations such as slicing and concatenation can be done. Python's str class defines a number
of useful methods for string processing. Subsets of strings can be taken using the slice operator ([ ] and
[:] ) with indexes starting at 0 in the beginning of the string.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator in
Python.
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists are the most versatile compound data types. A Python list contains items separated by
commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays in
C. One difference between them is that all the items belonging to a Python list can be of different data
type where as C array can store elements related to a particular data type.(Mutable)
A list in Python is an object of list class. We can check it with type() function.
As mentioned, an item in the list may be of any data type. It means that a list object can also be an item
in another list. In that case, it becomes a nested list.
A list can have items which are simple numbers, strings, tuple, dictionary, set or object of user defined
class also.
The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator.
Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a number
of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses (...).
A tuple is also a sequence, hence each item in the tuple has an index referring to its position in the
collection. The index starts from 0.
In Python, a tuple is an object of tuple class. We can check it with the type() function.
As in case of a list, an item in the tuple may also be a list, a tuple itself or an object of any other Python
class.
To form a tuple, use of parentheses is optional. Data items separated by comma without any enclosing
symbols are treated as a tuple by default.
>>> 2023, "Python", 3.11, 5+6j, 1.23E-4
(2023, 'Python', 3.11, (5+6j), 0.000123)
abcd
(786, 2.23)
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed i.e. lists are mutable, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated (immutable). Tuples can be thought of as read-only lists.
The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.
Similar case is possible with lists −
Open Compiler
A Python range is an immutable sequence of numbers which is typically used to iterate through a
specific number of items.
It is represented by the Range class. The constructor of this class accepts a sequence of numbers starting
from 0 and increments to 1 until it reaches a specified number. Following is the syntax of the function −
for i in range(5):
print(i)
Now let's modify above program to print the number starting from 2 instead of 0 −
Open Compiler
2
3
4
Again, let's modify the program to print the number starting from 1 but with an increment of 2 instead
of 1:
Open Compiler
for i in range(1, 5, 2):
print(i)
1
3
Python dictionary is like associative arrays or hashes found in Perl and consist of key:value pairs. The
pairs are separated by comma and put inside curly brackets {}. To establish mapping between key and
value, the semicolon':' symbol is put between the two.
In Python, dictionary is an object of the built-in dict class. We can check it with the type() function.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]).
This is one
This is two
Python's dictionary is not a sequence. It is a collection of items but each item (key:value pair) is not
identified by positional index as in string, list or tuple. Hence, slicing operation cannot be done on a
dictionary. Dictionary is a mutable object, so it is possible to perform add, modify or delete actions with
corresponding functionality defined in dict class. These operations will be explained in a subsequent
chapter.
Comma separated items in a set are put inside curly brackets or braces {}. Items in the set collection can
be of different data types.
Note that items in the set collection may not follow the same order in which they are entered. The
position of items is optimized by Python to perform operations over set as defined in mathematics.
Python's Set is an object of built-in set class, as can be checked with the type() function.
A set can store only immutable objects such as number (int, float, complex or bool), string or tuple. If
you try to put a list or a dictionary in the set collection, Python raises a TypeError.
Hashing is a mechanism in computer science which enables quicker searching of objects in computer's
memory. Only immutable objects are hashable.
Even if a set doesn't allow mutable items, the set itself is mutable. Hence, add/delete/update operations
are permitted on a set object, using the methods in built-in set class. Python also has a set of operators
to perform set manipulation. The methods and operators are explained in latter chapters
Example of Set
set1 = {123, 452, 5, 6}
set2 = {'Java', 'Python', 'JavaScript'}
print(set1)
print(set2)
{123, 452, 5, 6}
{'Python', 'JavaScript', 'Java'}
Set operations:-union(|),intersection(&),difference(-),symmetric_difference(^)
A Boolean number has only two possible values, as represented by the keywords, True and False. They
correspond to integer 1 and 0 respectively.
a = True
# display the value of a
print(a)
true
<class 'bool'>
Following is another program which evaluates the expressions and prints the return values −
Open Compiler
# Returns false as a is 0
a = 0.0
print(bool(a))
# Returns false as a is 10
a = 10
print(bool(a))
False
False
False
False
False
True
Example
In the following example, we are getting the type of the values and variables −
Open Compiler
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
<class 'int'>
<class 'float'>
<class 'int'>
<class 'float'>
<class 'str'>
<class 'tuple'>
<class 'list'>
The following example, demonstrating how a variable's data type is set based on the given value −
Open Compiler
# Declaring a variable
# And, assigning an integer value
x = 10
x = 10
x = Hello World!
A Python statement is an instruction that the Python interpreter can execute. There are different types
of statements in Python language as Assignment statements, Conditional statements, Looping
statements, etc. The token character NEWLINE is used to end a statement in Python. It signifies that
each line of a Python script contains a statement. These all help the user to get the required output.
hellodearstudent
Output:
Initializing a text using the Explicit multi-line statement A Computer Science portalfor xyz. It
contains well written, well thought and well explained computer science and programming articles
# Initializing a string
# using parentheis "()".
g = (f" Hello"
f"dear"
f"Student")
print(g)
print()
print('Initializing a list using the\
Implicit multi-line statement', list)
Hellodearstudent
# Initializing a string
# using triple qoute.
g = """hello
dear
student"""
print(g)
print()
Output
'hello\ndear\nstudent'
Note:-
Multiline statement in inline :- a=10;print(a) //10.
String statement:- print("Hello ‘shiv’") // Hello ‘shiv’
In Python, indentation plays a crucial role in defining the structure of the code, particularly in blocks of
code like loops, conditionals, functions, and classes. Unlike some programming languages that use braces
({}) to define code blocks, Python relies entirely on indentation to define which lines of code belong to
which blocks.
Expected Indent
Unexpected Indent
1. Expected Indentation
Expected indentation occurs when Python expects an indented block after certain statements, like if, for,
while, def, class, etc. This is how Python knows where the block of code for that statement ends.
if True:
After if True:, Python expects the code block that should be executed if the condition is true to be
indented.
The line print("This is inside the if block") is indented correctly (by 4 spaces or a tab) and is part of
the if block.
2. Unexpected Indentation
Unexpected indentation happens when Python finds an indented line of code where it doesn't expect one,
causing a IndentationError. This typically occurs when you add unnecessary indentation or indent in the
wrong place.
if True:
In this example:
The print statement should be indented after the if True: line to indicate it belongs to the if block.
Since there is no indentation for print("This will cause an IndentationError"), Python raises an
IndentationError.