0% found this document useful (0 votes)
4 views27 pages

1.I-Python-Introduction & Data Types Part-I 2022-23

This document provides lecture notes on Python programming for II B.Tech I semester students, covering its history, features, and applications. Python is a versatile, high-level programming language known for its ease of learning and use in various domains, including AI and ML. The notes also highlight differences between Python 2 and Python 3, as well as how to run Python programs in different modes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views27 pages

1.I-Python-Introduction & Data Types Part-I 2022-23

This document provides lecture notes on Python programming for II B.Tech I semester students, covering its history, features, and applications. Python is a versatile, high-level programming language known for its ease of learning and use in various domains, including AI and ML. The notes also highlight differences between Python 2 and Python 3, as well as how to run Python programs in different modes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

II B.

Tech I- Semester Python Programming (2022-23)

LECTURE NOTES

ON

PYTHON PROGRAMMING

(AI & ML)

II B. Tech I semester [2022-23]

R18 Regulation

Dr. N.Venkateswaran,
Associate Professor,

Department of Computer Science & Engineering

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 1


II B.Tech I- Semester Python Programming (2022-23)

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.

Guido Van Rossum


Python was developed by Guido van Rossum during 1985- 1990 at the National Research Institute for
Mathematics and Computer Science in the Netherlands. BBC comedy series name ‘Monty Python’s Flying Circus’
from 1970. He though he needed a unique name, so just gave the name.

 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)

History of the Python


The Python programming language was invented by Guido Van Rossum in the year 1989. The first version of
Python was released into the market on 20th Feb 1991, later it was released with different versions. The following
table provides a list of versions released in the Python.

S. No. Version Release Date

1 Python 1.0 January 1994

2 Python 1.5 December 31, 1997

3 Python 1.6 September 5, 2000

4 Python 2.0 October 16, 2000

5 Python 2.1 April 17, 2001

6 Python 2.2 December 21, 2001

7 Python 2.3 July 29, 2003

8 Python 2.4 November 30, 2004

9 Python 2.5 September 19, 2006

10 Python 2.6 October 1, 2008

11 Python 2.7 July 3, 2010

12 Python 3.0 Feb. 13, 2009

13 Python 3.1 June 26, 2009

14 Python 3.2 Feb. 20, 2011

15 Python 3.3 Sept. 29, 2012

16 Python 3.4 March 17, 2014

17 Python 3.5 Sept. 13, 2015

18 Python 3.6 Dec. 23, 2016

19 Python 3.7 June 27, 2018

20 Python 3.7.3 March 25, 2019

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 3


II B.Tech I- Semester Python Programming (2022-23)

S. No. Version Release Date

20 Python 3.8 October 14, 2019

21 Python 3.9 October 5, 2020

22 Python 3.10 October 4, 2021

23 Python 3.11 October 24, 2022

Where we can use Python:



The Python programming language has a very wide range of applications and few of them are listed below.
 Desktop application
 Web application
 Database application
 Networking Application
 Games
 Automation
 Hacking
 Data Analysis
 Artificial intelligence / Machine learning
 Mobile Apps
 IOT applications...etc

Which Companies (users of Pythons)


Google, YouTube, Dropbox, Yahoo, Zope Corporation, Industrial Light & Magic,Walt Disney Feature
Animation, Pixar, NASA, NSA, Red Hat, Nokia, IBM, Netflix, Yelp,Intel, Cisco, HP, Qualcomm, and
JPMorgan Chase, just to name a few.

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)

debugging of snippets of code.


 Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
 Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and ported to many system
calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of
Unix.
 Scalable − Python provides a better structure and support for large programs than shell scripting.

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.

Python 2 vs. Python 3


In most of the programming languages, whenever a new version releases, it supports the features and syntax of
the existing version of the language, therefore, it is easier for the projects to switch in the newer version.
However, in the case of Python, the two versions Python 2 and Python 3 are very much different from each
other.

A list of differences between Python 2 and Python 3 are given below:

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.

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 5


II B.Tech I- Semester Python Programming (2022-23)

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.

Enter python the command line.

Start coding right away in the interactive interpreter.


$python # Unix/Linuxor

python% # Unix/Linux
or
C:> python # Windows/DOS

Script from the Command-line

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

C: >python script.py # Windows/DOS

Note − Be sure the file permission mode allows execution.

Integrated Development Environment

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.

 Unix − IDLE is the very first Unix IDE for Python.


 Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI.
 Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main
website, downloadable as either MacBinary or BinHex'd files.

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)

First Python Program


Let us execute programs in different modes of programming.

Interactive Mode Programming

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!

Script Mode Programming

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

This produces the following result −


Hello, Python!

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

This produces the following result −

Hello, Python!
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 7
II B.Tech I- Semester Python Programming (2022-23)

Behind the Scenes: How Python Works


Whether you are running Python code as a script or interactively in a shell, the Python interpreter does a great
deal of work to carry out the instructions in your program. This work can be broken into a series of steps, as
shown in Figure.

Steps in interpreting a Python program


1. The interpreter reads a Python expression or statement, also called the source code, and verifies that it is
well formed. In this step, the interpreter behaves like a strict English teacher who rejects any sentence
that does not adhere to the grammar rules, or syntax, of the language. As soon as the interpreter
encounters such an error, it halts translation with an error message.

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.

Here are naming conventions for Python identifiers −

 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.

Declaring Variable and Assigning Values


Python does not bind us to declare variable before using in the application. It allows us to create variable at
required time.

We don't need to declare explicitly variable in Python. When we assign any value to the variable that variable is
declared automatically.

The equal (=) operator is used to assign value to a variable.


Eg:

Output:
1. >>>
2. 10
3. ravi
4. 20000.67
5. >>>

Reserved/ Keywords Words


Python Keywords are special reserved words which convey a special meaning to the compiler/interpreter. Each
keyword has a special meaning and a specific operation. These are 33 reserved words(2.6.5) and 35 reserved
words in 3.7.3 and you cannot use them as constant or variable or any other identifier names. All the Python
keywords contain lowercase letters only except True, False and None.
S.No Method Description
1 and A logical operator
2 as To create an alias
3 assert For debugging

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 9


II B.Tech I- Semester Python Programming (2022-23)

4 break To break out of a loop


5 class To define a class
6 continue To continue to the next iteration of a loop
7 def To define a function
8 del To delete an object
9 elif Used in conditional statements, same as else if
10 else Used in conditional statements
11 except Used with exceptions, what to do when an exception occurs
12 False Boolean value, result of comparison operations
Used with exceptions, a block of code that will be executed no matter if there is an
13 finally
exception or not
14 for To create a for loop
15 from To import specific parts of a module
16 global To declare a global variable
17 if To make a conditional statement
18 import To import a module
19 in To check if a value is present in a list, tuple, etc.
20 is To test if two variables are equal
21 lambda To create an anonymous function
22 None Represents a null value
23 nonlocal To declare a non-local variable
24 not A logical operator
25 or A logical operator
26 pass A null statement, a statement that will do nothing
27 raise To raise an exception
28 return To exit a function and return a value
29 True Boolean value, result of comparison operations
30 try To make a try...except statement
31 while To create a while loop
32 with Used to simplify exception handling
33 yield To end a function, returns a generator
34 async To synchronize the object
35 await To wait

Lines and Indentation


Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks
of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the
same amount. For example −

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 10


II B.Tech I- Semester Python Programming (2022-23)

if True:
print "True"
else:
print "False"

However, the following block generates an error −

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 −

days = ['Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday']

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

This produces the following result −

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 11


II B.Tech I- Semester Python Programming (2022-23)

Hello, Python!
You can type a comment on the same line after a statement or expression −
name = "varun" # This is again comment

You can comment multiple lines as follows −


# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comment:
'''
This is a multiline
comment.
'''

Python Data Types


Variables can hold values of different data types. Python is a dynamically typed language hence we need not
define the type of the variable while declaring it. The interpreter implicitly binds the value with its type.
Python enables us to check the type of the variable used in the program. Python provides us the type() function
which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.
A=10
b="welcome to Python"
c = 10.5
print(type(a));
print(type(b));
print(type(c));
Output:
<type 'int'>
<type 'str'>
<type 'float'>

Standard data types


A variable can hold different types of values. For example, a person's name must be stored as a string whereas
its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them. The data types
defined in Python are given below.

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 12


II B.Tech I- Semester Python Programming (2022-23)

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

Python supports 3 types of numeric data.

1. int (signed integers like 10, 2, 29, etc.)


2. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
3. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)

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.

str1 = 'hello varunjoel' #string str1


str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

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 [].

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 13


II B.Tech I- Semester Python Programming (2022-23)

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.

Consider the following example.


l = [1, "hi", "python", 2]
print (l[3:])
print (l[0:2])
print (l)
print (l + l)
print (l * 3)
Output:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]

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.

Let's see a simple example of the tuple.


t = ("hi", "python", 2)
print (t[1:])
print (t[0:1])
print (t)
print (t + t)
print (t * 3)
print (type(t))
t[2] = "hi"

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

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 14


II B.Tech I- Semester Python Programming (2022-23)

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'])

'None' data type in Python


In many programming languages, we use the value null to represent nothing. 'None' is Python's equivalent of
NULL value in other programming languages. In Python, 'None' is the object which represents nothing. When we
want a value to hold nothing, we do assign it with value 'None'.
Example - Python code to illustrate 'None' data type
roll_number = None
print(type(roll_number))

'Set' data type in Python


In Python, a set is a collection of an unordered and unindexed data elements of different data types. In Python, the
set data type elements are immutable (duplicates are not allowed). However, set itself is mutable. Set is created
with curly brackets. Let's look at the code to illustrate set in Python.
Example 1 - Python code to illustrate 'set' in Python
student = {1,'Jyothishmathi',"25 years",99.99}
print(student)
print(type(student))

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)

'Range' function in Python


In Python, range( ) is a built-in function used to create a list of integers with a specified range of values. The
general syntax of range( ) function is as follows.
Syntax
variable_name = range(start, end, difference)

Python code to illustrate 'range( )' in Python

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.

When we run the above code, it produces the output as follows.


<class 'range'>
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

In Python, the default starting value of range() function is 0.


In Python, the default difference between the values of range() function is 1.
In Python, the ending value is not included in the list. That means, the range() function returns a list starting with
starting value and ending with end-1 but end value is not included.

Escape Sequences in Python Strings


The escape sequences are the special characters in string data. All the escape sequences are prefixed with a
backslash (\) character. A backslash (\) character in a string intimates that one or more characters that follow it
should be interpreted with their special meaning only. The following table presents all escape sequences that are
allowed in Python.
S.No. Escape Sequence Special Meaning
1 \' single quote (') character
2 \" Double quote (") character
3 \\ backslash (\) character
4 \a ASCII Bell character
5 \b ASCII Backspace character
6 \n ASCII Newline character
7 \t ASCII Horizontal Tab character
8 \u Unicode character with 16-bit hex value

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 16


II B.Tech I- Semester Python Programming (2022-23)

S.No. Escape Sequence Special Meaning


9 \U Unicode character with 32-bit hex value
10 \v ASCII Vertical Tab character
11 \o Character with octal value
12 \x Character with hex value
13 \newline Backslash and newline ignored

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.

The following are the constructor functions used to perform typecasting.

S.No. Function Description


It is used to convert an integer literal, float literal, and string literal (String must represent a whole
1 int( )
number) to an integer value.
It is used to convert an integer literal, float literal, and string literal (String must represent a whole
2 float( )
number) to a float value.
It is used to convert a value of any data type including strings, integer literals and float literals to a
3 str( )
string value.

Example - int( ) Typecasting


a = int(10)
print(f"value of a is {a} and data type of a is {type(a)}")
a = int(60.99)
print(f"value of a is {a} and data type of a is {type(a)}")
a = int("150")
print(f"value of a is {a} and data type of a is {type(a)}")
Output:
value of a is 10 and data type of a is <class 'int'>
value of a is 60 and data type of a is <class 'int'>
value of a is 150 and data type of a is <class 'int'>

#Example - float( ) Typecasting

a = float(10)
print(f"value of a is {a} and data type of a is {type(a)}")

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 17


II B.Tech I- Semester Python Programming (2022-23)

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'>

#Example - str( ) Typecasting


a = str(10)
print(f"value of a is {a} and data type of a is {type(a)}")
a = str(60.99)
print(f"value of a is {a} and data type of a is {type(a)}")
a = str("150")
print(f"value of a is {a} and data type of a is {type(a)}")

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)}")

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 18


II B.Tech I- Semester Python Programming (2022-23)

Output:
wish_1 data type is <class 'str'> and wish_2 data type is <class 'str'>

Accessing String Values


In Python, whenever a string data value has assigned to a variable, it is organized as an array of characters. The
Python provides a variety of ways to access the string values.
Let's consider the following string value.

Accessing whole string

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.

Example - Accessing whole String


wish = 'Good Morning'
print(wish)

Output:
Good Morning

Accessing a character from a String Values

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

wish = 'Good Morning'


print(wish[-2])
Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 19
II B.Tech I- Semester Python Programming (2022-23)

Output:
n

Accessing a Substring from a String Values

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

Special Operators with Strings


The Python programming language provides special operators which can be used with string data values. The
following table gives the list of special operators used with strings.

S.No. Operator Description


1 + It is used to perform concatenation - Adds values on either side of the operator.
It is used to Reproduction - Generates new strings, concatenating multiple copies of the same
2 *
string.
4 in It is used to check whether a character is present in the string.
5 not in It is used to check whether a character is not present in the string.
6 [] It is used to access a character at a specified index.
7 [:] It is used to access a substring from a string
#Example - Special Operators used with strings
wish_1 = "Hi"
wish_2 = 'Good Morning'
result = wish_1 + wish_2
print(result)
result = 3 * wish_2
print(result)

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 20


II B.Tech I- Semester Python Programming (2022-23)

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 (**).

Consider the following table for a detailed explanation of arithmetic operators.


Operator Description
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
It is used to subtract the second operand from the first operand. If the first operand is less
- (Subtraction) than the second operand, the value result negative. For example, if a = 20, b = 10 => a ? b
= 10
It returns the quotient after dividing the first operand by the second operand. For example,
/ (divide)
if a = 20, b = 10 => a/b = 2
* It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a * b =
(Multiplication) 200
It returns the reminder after dividing the first operand by the second operand. For
% (reminder)
example, if a = 20, b = 10 => a%b = 0
It is an exponent operator represented as it calculates the first operand power to second
** (Exponent)
operand.
// (Floor Performs division which the digits after the decimal point are removed. But if one of the
division) operands is negative, the result is rounded away from zero (towards negative infinity)

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}")

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 21


II B.Tech I- Semester Python Programming (2022-23)

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

Comparison (or) relation operator


Comparison operators are used to comparing the value of the two operands and returns Boolean true or false
accordingly. The comparison operators are described in the following table.

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

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 22


II B.Tech I- Semester Python Programming (2022-23)

True
False
True

Python assignment operators


The assignment operators are used to assign the value of the right expression to the left operand. The
assignment operators are described in the following table.

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; # 12 = 0000 1100


print("Line 1 - Value of c is ", c)

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)

c = a << 2; # 240 = 1111 0000

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 24


II B.Tech I- Semester Python Programming (2022-23)

print("Line 5 - Value of c is ", c)

c = a >> 2; # 15 = 0000 1111


print("Line 6 - Value of c is ", c)
When you execute the above program it produces the following result −

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

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 25


II B.Tech I- Semester Python Programming (2022-23)

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)

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 26


II B.Tech I- Semester Python Programming (2022-23)

# 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

Prepared by Dr. N.Venkateswaran, Associate Professor, CSE Dept, JITS Page 27

You might also like