1.I-Python-Introduction & Data Types Part-I 2022-23
1.I-Python-Introduction & Data Types Part-I 2022-23
LECTURE NOTES
ON
PYTHON PROGRAMMING
R18 Regulation
Dr. N.Venkateswaran,
Associate Professor,
PYTHON PROGRAMMING
Introduction
Python is a general purpose, dynamic, high level, and interpreted programming language. It supports Object
Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-
level data structures.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public
License (GPL).
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for
Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal language for scripting
and rapid application development.
Python supports multiple programming pattern, including object-oriented, imperative, and functional or
procedural programming styles.
Python is not intended to work in a particular area, such as web programming. That is why it is known
as multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed so we can write a=10
to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step included in
Python development, and edit-test-debug cycle is very fast.
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile
your program before executing it. This is similar to PERL and PHP.
Python is Interactive − you can actually sit at a Python prompt and interact with the interpreter directly to
write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that
encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level programmers and
supports the development of a wide range of applications from simple text processing to WWW browsers
to games.
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 2
II B.Tech I- Semester Python Programming (2022-23)
Python Features
Python's features include −
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows
the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-platform compatible
on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive testing and
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 4
II B.Tech I- Semester Python Programming (2022-23)
Apart from the above-mentioned features, Python has a big list of good features, few are listed below −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
1. Python 2 uses print as a statement and used as print "something" to print some string on the console. On
the other hand, Python 3 uses print as a function and used as print("something") to print something on
the console.
2. Python 2 uses the function raw_input() to accept the user's input. It returns the string representing the
value, which is typed by the user. To convert it into the integer, we need to use the int() function in
Python. On the other hand, Python 3 uses input() function which automatically interpreted the type of
input entered by the user. However, we can cast this value to any type by using primitive functions
(int(), str(), etc.).
3. In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit string type is Unicode.
4. Python 3 doesn't contain the xrange() function of Python 2. The xrange() is the variant of range()
function which returns a xrange object that works similar to Java iterator. The range() returns a list for
example the function range(0,3) contains 0, 1, 2.
5. There is also a small change made in Exception handling in Python 3. It defines a keyword as which is
necessary to be used.
Running Python
There are three different ways to start Python −
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or
shell window.
python% # Unix/Linux
or
C:> python # Windows/DOS
A Python script can be executed at command line by invoking the interpreter on your application, as in the
following −
$python script.py # Unix/Linuxor
python% script.py # Unix/Linuxor
You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application
on your system that supports Python.
If you are not able to set up the environment properly, then you can take help from your system admin. Make
sure the Python environment is properly set up and working perfectly fine.
The Python language has many similarities to Perl, C, and Java. However, there are some definite differences
between the languages.
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 6
II B.Tech I- Semester Python Programming (2022-23)
Invoking the interpreter without passing a script file as a parameter brings up the following prompt −
$ python
Python 3.7.3 (default, Mar 27 2019, 17:13:21)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Type the following text at the Python prompt and press the Enter −
>>> print "Hello, Python!"
If you are running new version of Python, then you would need to use print statement with parenthesis as in
print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result −
Hello, Python!
Invoking the interpreter with a script parameter begins execution of the script and continues until the script is
finished. When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the following source
code in a test.py file −
print "Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −
$ python test.py
Let us try another way to execute a Python script. Here is the modified test.py file −
#!/usr/bin/python
print "Hello, Python!"
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as
follows −
$ chmod +x test.py # This is to make file executable
$./test.py
Hello, Python!
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 7
II B.Tech I- Semester Python Programming (2022-23)
2. If a Python expression is well formed, the interpreter then translates it to an equivalent form in a low-
level language called byte code. When the interpreter runs a script, it completely translates it to byte
code.
3. This byte code is next sent to another software component, called the Python virtual machine (PVM),
where it is executed. If another error occurs during this step, execution also halts with an error message.
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier
starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits
(0 to 9).
Python does not allow white space, punctuation characters such as @, $, and % within identifiers. Python is a
case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 8
II B.Tech I- Semester Python Programming (2022-23)
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.
We don't need to declare explicitly variable in Python. When we assign any value to the variable that variable is
declared automatically.
Output:
1. >>>
2. 10
3. ravi
4. 20000.67
5. >>>
The number of spaces in the indentation is variable, but all statements within the block must be indented the
same amount. For example −
if True:
print "True"
else:
print "False"
if True:
print "Answer"
print
"True"
else:
print "Answer"
print
"False"
Thus, in Python all the continuous lines indented with same number of spaces would form a block.
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For
example −
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type
of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of
the physical line are part of the comment and the Python interpreter ignores them.
# First comment
print "Hello, Python!" # second comment
Hello, Python!
You can type a comment on the same line after a statement or expression −
name = "varun" # This is again comment
Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comment:
'''
This is a multiline
comment.
'''
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
Numbers
Number stores numeric values. Python creates Number objects when a number is assigned to a variable. For
example;
x = 1 # int
y = 2.8 # float
z = 1j # complex #x, y and z are number objects
A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts
respectively).
String
The string can be defined as the sequence of characters represented in the quotation marks. In python, we can
use single, double, or triple quotes to define a string.
String handling in python is a straightforward task since there are various inbuilt functions and operators
provided.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as repetition operator as the operation "Python " *2 returns "Python Python ".
The following example illustrates the string handling in python.
Output:
he
o
hello varunjoelhello varunjoel
hello varunjoel how are you
List
Lists are similar to arrays in C. However; the list can contain data of different types. The items stored in the list
are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition
operator (*) works with the list in the same way as they were working with the strings.
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different
data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Output:
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<class 'tuple'>
Traceback (most recent call last):
File "C:/Users/VARUN/test1.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
Dictionary is an ordered set of a key-value pair of items. It is like an associative array or a hash table where
each key stores a specific value. Key can hold any primitive data type whereas value is an arbitrary Python
object.
The items in the dictionary are separated with the comma and enclosed in the curly braces {}.
Syntax
dictionary_name = {key_1: value_1, key_2: value_2, ...}
Consider the following example.
d = {1:'varun', 2:'joel', 3:'shailu', 4:'milkey'};
print("1st name is "+d[1]);
print("2nd name is "+ d[4]);
print (d);
print (d.keys());
print (d.values());
Output:
1st name is varun
2nd name is milkey
{1: 'varun', 2: 'joel', 3: 'shailu', 4: 'milkey'}
dict_keys([1, 2, 3, 4])
dict_values(['varun', 'joel', 'shailu', 'milkey'])
Output:
{1, 99.99, '25 years', 'Jyothishmathi'}
<class 'set'>
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 15
II B.Tech I- Semester Python Programming (2022-23)
a = range(10,20,1)
print(type(a))
print(list(a))
In the above example Python code the variable a is stored with a list [10,11,12,13,14,15,16,17,18,19]. The
range() function takes three arguments. The first argument indicates the starting value, the second argument
indicates ending value, and the third argument indicates the difference between each element in the list.
Python Typecasting
In all programming languages, frequently, we need to convert the values from one data type to another data type.
The process of converting a value from one data type to another data type is called Typecasting or simply
casting. In Python, the typecasting is performed using built-in functions. As all the data types in Python are
organized using classes, the type casting is performed using constructor functions.
a = float(10)
print(f"value of a is {a} and data type of a is {type(a)}")
a = float(60.99)
print(f"value of a is {a} and data type of a is {type(a)}")
a = float("150")
print(f"value of a is {a} and data type of a is {type(a)}")
Output:
value of a is 10.0 and data type of a is <class 'float'>
value of a is 60.99 and data type of a is <class 'float'>
value of a is 150.0 and data type of a is <class 'float'>
Output:
value of a is 10 and data type of a is <class 'str'>
value of a is 60.99 and data type of a is <class 'str'>
value of a is 150 and data type of a is <class 'str'>
Note:
In Python, when an integer value is cast to float value, then it is appended with the fractional part containing
zeros (0).
In Python, when a float value s cast to an integer it rounding down to the previous whole number.
Python Strings
A string is a sequence of characters which is enclosed in quotes. In Python, a string value can be enclosed either
in single quotes or double quotes. The Python treats both single quote and double quote as same. For example, the
strings 'Hi Students' and "Hi Studentss" both are same.
Creating Strings
In Python, creating string variables is very simple as we need to assign a string value to a variable.
Example - Creating Strings
wish_1 = 'Good Morning'
wish_2 = "Good Evening"
print(f"wish_1 data type is {type(wish_1)} and wish_2 data type is {type(wish_2)}")
Output:
wish_1 data type is <class 'str'> and wish_2 data type is <class 'str'>
To access the entire string which is stored in a variable, we use the variable name directly. Let's look at the code of
how a string value is accessed.
Output:
Good Morning
To access a single character from a string variable, we use the index value in square brackets os the respective
character. Let's look at the code of how a character can be accessed from a string value.
Example - Accessing a single character from a Strings
wish = 'Good Morning'
print(wish[0])
Output:
G
We can also access a single character from a string using negative index values. When we use negative index
value, it starts from the last character with index -1. Let's look at the following example code to demonstrate how
negative index values are used to access individual character from a string.
Example - Accessing a single character using the negative index value from a Strings
Output:
n
In Python, it also possible to access a substring from a string. To access substring from a string, we use string
variable name followed by square brackets with starting index and ending index of the required substring. Let's
look at the following example code to demonstrate how to access substring from a string.
Example - Accessing a substring from a Strings
wish = 'Good Morning'
print(wish[2:8]) # Accessing specified substring
print(wish[:8]) # Here default starting index is '0'
print(wish[2:]) # Here default Ending index is 'Last - (11)'
Output:
od Mor
Good Mor
od Morning
Python Operators
The operator can be defined as a symbol which is responsible for a particular operation between two operands.
Operators are the pillars of a program on which the logic is built in a particular programming language. Python
provides a variety of operators described as follows.
Arithmetic operators
Comparison operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands. It includes + (addition), -
(subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and exponent (**).
Example
a = 20
b=6
c = -6
print(f"a + b = {a + b}")
print(f"a - b = {a - b}")
print(f"a * b = {a * b}")
print(f"a / b = {a / b}")
print(f"a % b = {a % b}")
print(f"a ** b = {a ** b}")
print(f"a // b = {a // b}")
print("a // c = {0}".format(a // c))
When you execute the above program, it produces the following result –
a+ b = 26
a - b = 14
a * b = 120
a / b = 3.3333333333333335
a%b=2
a ** b = 64000000
a // b = 3
a // c = -4
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition becomes true.
If the first operand is greater than or equal to the second operand, then the condition becomes
>=
true.
<> If the value of two operands is not equal, then the condition becomes true.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
Example
a = 10
b=3
print(a < b)
print(a <= b)
print(a > b)
print(a >= b)
print(a == b)
print(a != b)
When you execute the above program it produces the following result −
False
False
True
True
False
True
Operator Description
= It assigns the the value of the right expression to the left operand.
It increases the value of the left operand by the value of the right operand and assign the modified
+= value back to left operand. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assign the modified
value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.
It multiplies the value of the left operand by the value of the right operand and assign the
*= modified value back to left operand. For example, if a = 10, b = 20 => a* = b will be equal to a =
a* b and therefore, a = 200.
It divides the value of the left operand by the value of the right operand and assign the reminder
%= back to left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and
therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
Example
Assume variable a holds 10 and variable b holds 20, then −
a = 10
b=3
a += b
print(f"a += b => {a}")
a -= b
print(f"a -= b => {a}")
a *= b
print(f"a *= b => {a}")
a /= b
print(f"a /= b => {a}")
a %= b
print(f"a %= b => {a}")
a **= b
print(f"a **= b => {a}")
a //= b
print(f"a //= b => {a}")
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 23
II B.Tech I- Semester Python Programming (2022-23)
When you execute the above program, it produces the following result −
a += b => 13
a -= b => 10
a *= b => 30
a /= b => 10.0
a %= b => 1.0
a **= b => 1.0
a //= b => 0.0
Bitwise operator
The bitwise operators perform bit by bit operation on the values of the two operands.
Operator Description
& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the result.
and) Otherwise, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will be 1.
^ (binary xor) The resulting bit will be 1 if both the bits are different otherwise the resulting bit will be 0.
~ (negation) Returns one’s complement of the number.
<< (left shift) The left operand value is moved left by the number of bits present in the right operand.
>> (right
The left operand is moved right by the number of bits present in the right operand.
shift)
Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a | b; # 61 = 0011 1101
print("Line 2 - Value of c is ", c)
c = a ^ b; # 49 = 0011 0001
print("Line 3 - Value of c is ", c)
k=10
z = ~k; #11 =1101
print("binary value ", bin(~k))
print("Line 4 - Value of c is ", z)
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
binary value -0b1011
Line 4 - Value of c is -11
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision. Python supportsthe
following logical operators.
Operator Description
If both the expression are true, then the condition will be true. If a and b are the two expressions,
And a → true, b → true => a and b → true.
If one of the expressions is true, then the condition will be true. If a and b are the two expressions,
Or a → true, b → false => a or b → true.
Not If an expression a is true then not (a) will be false and vice versa.
Example : AND
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10
Example: OR
x=5
print(x > 3 or x < 4)
# returns True because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)
Example : NOTx =
5
print(not(x > 3 and x < 10))
# returns False because not is used to reverse the result
Membership Operators
Python membership operators are used to check the membership of value inside a data structure. If the value is
present in the data structure, then the resulting value is true otherwise it returns false. Here the data structure may
be String, List, or Tuple.
Operator Description
It is evaluated to be true if the first operand is found in the second operand (list, tuple, or
In
dictionary).
It is evaluated to be true if the first operand is not found in the second operand (list, tuple, or
not in
dictionary).
Example:
x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the list
print('s' in 'jyothishmathi')
#return True
Identity Operators
Identity operators compare the memory locations of two objects.
Operator Description
Is It is evaluated to be true if the reference present at both sides point to the same object.
is not It is evaluated to be true if the reference present at both side do not point to the same object.
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]z = x
print(x is z)
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y, even if they have threw same content(because list is
mutable).
print(x == y)
# to demonstrate the difference between "is" and "==": this comparison returns True because x is equal to y
Example :
print(x is not z)
# returns False because z is the same object as x
print(x is not y)
# returns True because x is not the same object as y, even if they have the same content
print(x != y)
# to demonstrate the difference between "is not" and "!=": this comparison returns False because x is equalto y
Operator Precedence
The precedence of the operators is important to find out since it enables us to know which operator shouldbe
evaluated first. The precedence table of the operators in python is given below.
Operator Description
** The exponent operator is given priority over all the others used in the expression.
~+- The negation, unary plus and minus.
* / % // The multiplication, divide, modules, reminder, and floor division.
+- Binary plus and minus
>> << Left shift and right shift
& Binary and.
^| Binary xor and or
<= < > >= Comparison operators (less then, less then equal to, greater then, greater then equal to).
<> == != Equality operators.
= %= /= //= -= +=
Assignment operators
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators