0% found this document useful (0 votes)
73 views136 pages

Unit 1 - Python - Btech Second Year

Uploaded by

avikation1234
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)
73 views136 pages

Unit 1 - Python - Btech Second Year

Uploaded by

avikation1234
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/ 136

Quality Content for Outcome based Learning

1.1 Getting started with Python


Day 1

Ver. No.: 1.1 Copyright © 2021, ABES Engineering College


General Guideline
© (2021) ABES Engineering College.

This document contains valuable confidential and proprietary information of ABESEC. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and
commercialized. Such information is furnished herein for training purposes only. Except with the express prior
written permission of ABESEC, this document and the information contained herein may not be published,
disclosed, or used for any other purpose.

2
Copyright © 2021, ABES Engineering College
Topics Covered

Day 1 Day 2 Day 3 Day 4


1.1 Getting started 1.1 Getting started with 1.2 Python Installation 1.3 Basics of Python
with Python Python Guide • 1.3.1 Python keywords
• 1.1.1 Introduction • 1.1.6 Advantages of • 1.2.1 Introduction to • 1.3.2 Python Statement
to programming Python python IDE – IDLE
and Comments
and coding • 1.1.7 Disadvantages of • 1.2.2 Setting Up Your
Environment • 1.3.3 Python Literals
• 1.1.2 Why choose Python
Python • 1.2.3 Installation of • 1.3.4 Data Types
• 1.1.8 Applications of
• 1.1.3 Scope of Python Python and Anaconda • 1.3.5 Variables
Python • 1.1.9 Different Flavors of Navigator • 1.3.6 type (), dir (),ID
• 1.1.4 Python Python • 1.2.4 Quick Tour of command
History • 1.1.10 Different Python Jupyter Notebook
• 1.1.5 Python Frameworks • 1.2.5 Python vs. IPython
Features • 1.1.11 Python in contrast • 1.2.6 Online compilation
with other programming support
languages • 1.2.7 Running python
script using command
prompt
3
Copyright © 2021, ABES Engineering College
Topics Covered

Day 5 Day 6

1.3 Basics of Python 1.3 Basics of Python


• 1.3.7 Type • 1.3.9 Operators
conversion: implicit • 1.3.10 Precedence
and explicit and associativity
• 1.3.8 Basic I/O • 1.3.11 Python 2 vs
Operations: input (), Python 3
print ()

4
Copyright © 2021, ABES Engineering College
Session Plan - Day 1

1.1Getting started with Python


1.1.1 Introduction to programming and coding
1.1.2 Why choose Python
1.1.3 Scope of Python
1.1.4 Python History
1.1.5 Python Features

5
Copyright © 2021, ABES Engineering College
Introduction

Python is a Popular
Programming language

?
https://www.wordclouds.com/

6
Copyright © 2021, ABES Engineering College
Some Areas where it is Popular

Application Development
Web Development
Artificial Intelligence
Data Science

7
Copyright © 2021, ABES Engineering College
Why choose Python : Lets Discuss More

Simple and Easier to learn


Good Readability
Free and Open Source
Python is a platform-independent language
High Level and Interpreted language
Extensive libraries: Python has a vast number of libraries.

8
Copyright © 2021, ABES Engineering College
Scope of Python
Python Language provides promising and rewarding career in the IT industry
Various Job roles advanced in Python with high paying jobs:
Research Analyst
DevOps Engineer
Python Developer
Data Analyst
Software Developer
Game Developer
Web Scrapper

9
Copyright © 2021, ABES Engineering College
Python History

Python was written in the late 1980s by Guido van Rossum at Centrum
Wiskunde & Informatica (CWI)

10
Copyright © 2021, ABES Engineering College
Python Features

11
Copyright © 2021, ABES Engineering College
Review Questions

 In which year was the Python language developed?


 1995
 1972
 1981
 1989

 Who developed the Python language?


 Zim Den
 Guido van Rossum
 Niene Stom
 Wick van Rossum

12
Copyright © 2021, ABES Engineering College
Review Questions

 How many keywords are there in python 3.7?


 32
 33
 35
 30
 Which one of the following is the correct extension of the Python
file?
 .py
 .python
 .p
 None of these

13
Copyright © 2021, ABES Engineering College
Session Plan - Day 2

1.1Getting started with Python


1.1.6 Advantages of Python
1.1.7 Disadvantages of Python
1.1.8 Applications of Python
1.1.9 Different Flavors of Python
1.1.10 Different Python Frameworks
1.1.11 Python in contrast with other programming languages

14
Copyright © 2021, ABES Engineering College
Advantages of Python

15
Copyright © 2021, ABES Engineering College
Contd..

Write a Program using any language to print “ HELLO WORLD “.

Java Program : C++ Program :

public class Hello #include <iostream><br>


{ int main()
public static void main(String argv[]) {
{ cout << "Hello World" << endl;
return 0;
System.out.println(“Hello, World!”); }

}
}

16
Copyright © 2021, ABES Engineering College
Contd..

In Python

print ( "Hello World")

17
Copyright © 2021, ABES Engineering College
Disadvantages of Python
Python code is executed line by line since Python is interpreted as slower
in runtime than other programming languages like C++, Java, and PHP.
Python takes a lot of memory due to the flexibility of the data types, so it
is not a desirable choice for memory-intensive tasks.
Although Python serves as an excellent server-side programming
language, it is less commonly used to build intelligent phone-based
Applications.
Python is rarely used in Enterprise development because Python has
some limitations with Database Access compared to primarily other used
technologies like JDBC (Java Database Connectivity and ODBC (Open
Database Connectivity) as Python Language Database layers are
underdeveloped.

18
Copyright © 2021, ABES Engineering College
Your Future….!!!

Copyright © 2021, ABES Engineering College


Applications of Python
Web and Internet Development
Game Development
Desktop GUI Applications
Artificial Intelligence and Machine Learning
Data Science and Data Visualization
Web Scraping Applications
Desktop Applications
Business Applications
Image Processing and Computer Graphics
Language Development
Popular Applications Built on Python

20
Copyright © 2021, ABES Engineering College
Different Flavors of Python
Cpython
Jpython
Active Python
Anaconda Python
PyPy
Win Python
Python Portable

21
Copyright © 2021, ABES Engineering College
Different Python Frameworks
Full-Stack Frameworks
Non-Full Stack Frameworks
Asynchronous Frameworks

22
Copyright © 2021, ABES Engineering College
Review Questions

 How to output the string “May the odds favor you” in Python?
 print(“May the odds favor you”)
 echo(“May the odds favor you”)
 System.out(“May the odds favor you”)
 printf(“May the odds favor you”)

 In which year was the Python 3.0 version developed?


 2005
 2000
 2010
 2008

23
Copyright © 2021, ABES Engineering College
Review Questions

 Python is often described as a:


 Batteries excluded language
 Gear included language
 Batteries included language
 Gear excluded language

 What do we use to define a block of code in Python language?


 Indentation
 Key
 Brackets
 None of these

24
Copyright © 2021, ABES Engineering College
Quality Content for Outcome based Learning

1.2 Python Installation Guide


Day 3

Ver. No.: 1.1 Copyright © 2021, ABES Engineering College


Session Plan - Day 3

1.2 Python Installation Guide


 1.2.1 Introduction to python IDE – IDLE
 1.2.2 Setting Up Your Environment
 1.2.3 Installation of Python and Anaconda Navigator
 1.2.4 Quick Tour of Jupyter Notebook
 1.2.5 Python vs. IPython
 1.2.6 Online compilation support
 1.2.7 Running python script using command prompt

26
Copyright © 2021, ABES Engineering College
1.2 Python Installation Guide

Before you start, you will need Python on your computer.


Installing Python on your computer is the first step to becoming a Python
programmer.
Python has two main versions:
• Python 2
• Python 3
However, Python installation differs among different operating systems. The
use of Python 3 is highly preferred over Python 2.

27
Copyright © 2021, ABES Engineering College
Contd..
For the installation process, go to the official website of Python, i.e.,
www.python.org. Refer to the current stable version 3.9.4 as of date 13 April
2021.You will get the installer for Python 3.7 or Python 3.9. (at the time of
writing). You may even have it with a 32-bit or 64-bit processor versions.

28
Copyright © 2021, ABES Engineering College
1.2.1 Introduction to python IDE – IDLE

If you have recently installed Python on your computer, you might have seen a
new IDLE program.
"What is this software doing on my computer?" you might be curious. I did not
download that!"
Though you might not have downloaded IDLE on your own, it is included with
any Python installation. It is there to help you get acquainted with the language
right away.

Any Python installation includes an Integrated Development and Learning


Environment, abbreviated IDLE or even IDE.

29
Copyright © 2021, ABES Engineering College
Contd..

In a graphical user interface (GUI) desktop environment, the installation process


puts an icon on the desktop or an object in the desktop menu system that
launches Python.
In Windows, for example, there will be a category in the Start menu called
Python 3.7. Under it, a menu item labeled Python 3.7.4 (32-bit).

30
Copyright © 2021, ABES Engineering College
Contd..
Alternate way: You can also open a terminal window and run the interpreter
from the command line.
It is known as Command Prompt in Windows. It can be renamed terminal in
macOS or Linux.
You can type Windows key+ R and type cmd to open Command Prompt.
Then, type python to execute python programs.

31
Copyright © 2021, ABES Engineering College
Contd..
Start working with Python shell.
To print () to display the string "ABES Engineering College" on your computer.
Enter the command one at a time, and Python returns the results of each
command.

32
Copyright © 2021, ABES Engineering College
Contd..
From this menu bar, you can restart the shell. It will behave as if you had
launched a new instance of Python IDLE. The shell will forget anything from its
former state.
If you want to exit the interpreter, then type exit () and press Enter.

33
Copyright © 2021, ABES Engineering College
Python IDLE Editor
Python IDLE includes a full-featured file editor, allowing you to write and run
Python programs. The built-in file editor also supplies many tools to speed up
your coding workflows, such as code completion and automated indentation.
Select File “New File” from the menu bar to begin a new Python file

34
Copyright © 2021, ABES Engineering College
Contd..
When you are ready to work on a file, click the Edit button. You can save the file
as Demo-Python.py (.py is an extension to save python scripts files) in the
specified default location "C:\Users\Aatif\AppData\Local\Programs\Python."

35
Copyright © 2021, ABES Engineering College
Contd..
When you want to run a file, you must first ensure that it has been saved,
remember to check for asterisks * around the filename at the top of the file
editor window to see whether the file was correctly saved.

But do not panic if you forget! When you want to run an unsaved file in Python
IDLE, it will prompt you to save it.
Click the F5 key on your keyboard to run a file in IDLE. You can also use the
menu bar to choose Run Module

36
Copyright © 2021, ABES Engineering College
1.2.2 Setting Up Your Environment

The route(path that lists the directories in which the OS (Operating System)
looks for executables) is saved in an environment variable called a string.This
variable holds knowledge that the command shell and other programs can use.

In Unix, the path variable is known as PATH, and in Windows, it is known as


Path (Unix is case sensitive; Windows is not).
Following are the steps are taken for setting up the environment:
• Step 1 – Install Python 3.7 (Latest Version) from python.org.
• Step 2-- Add the Python 3.7 Directory to your System Path Environment Variable

37
Copyright © 2021, ABES Engineering College
Contd..

So, navigate to
Control Panel –> System
–> Advanced System
Settings–> Environment
Variables and choose
the PATH variable

38
Copyright © 2021, ABES Engineering College
Contd..
Add the Python path to the end of the string, this is where the package
management software, unit testing tools, and other command line-accessible
Python programs can live.
C:\Users\Aatif\AppData\Local\Programs\Python\Python37-32\Scripts\

39
Copyright © 2021, ABES Engineering College
1.2.3 Installation of Anaconda Navigator
Anaconda Navigator is a desktop graphical user interface that comes with
Anaconda, which allows you to open programs and control conda packages,
environments, and networks without needing to use a command-line interface.

For the installation process, go to the


official website of anaconda navigator
https://docs.anaconda.com/anaconda
/navigator/.
Latest version:
Anaconda3-2020.11-Windows-x86_64.exe

40
Copyright © 2021, ABES Engineering College
Contd..
Click on install and Choose destination folder for installation.

41
Copyright © 2021, ABES Engineering College
1.2.4 Quick Tour of Jupyter Notebook
In an earlier topic, we have seen the installation of the Anaconda package.
Jupyter comes by default with this package

The Jupyter Notebook


is a fantastic platform
for creating basic and
advanced level
programs.

42
Copyright © 2021, ABES Engineering College
Contd..
Alternate way: If you type 'Jupyter notebook' into your command prompt, it will
open the Jupyter dashboard for you

43
Copyright © 2021, ABES Engineering College
Contd..
You might have found that the URL for the dashboard is
https://localhost:8888/tree while Jupyter Notebook is open in your window. The
term "localhost" does not refer to a website, but to the fact that the content is
served from your own devices.

44
Copyright © 2021, ABES Engineering College
Contd..
If you want to create your first file, then you must click on new and then python3.
When you return to the dashboard, you can see the new file Untitled18.ipynb
with green boundary in cell.
A cell is a container for the text that will be viewed in the notebook or code that
the notebook's kernel will execute.

45
Copyright © 2021, ABES Engineering College
Contd..
Every ipynb file stands for a single notebook, which means that each time you
create a new notebook, a new.ipynb file is generated .You should be aware of
kernel that are unfamiliar to you.
A kernel is a kind of "computational engine" that runs the code in a notebook
paper.

46
Copyright © 2021, ABES Engineering College
Contd..
Shift + Enter is the shortcut command to run your cell.
The green boundary over the cell shows the editable mode, and the Blue
boundary over the cell shows the command mode.

47
Copyright © 2021, ABES Engineering College
1.2.5 Python vs. IPython
IPython's interactive shell is known as Ipython.
IPython is a Python graphical command-line terminal founded by Fernando
Perez in 2001. IPython supplies an improved read-eval-print loop (REPL)
environment that is particularly well suited to scientific computing.

48
Copyright © 2021, ABES Engineering College
Contd..
IPython is interactive, and it gives some relaxation to the eyes of coders by
introducing some colors. Some useful commands are not present with the
existing Python idle.
The following are the valuable commands:
• %pwd
• %ls
• %History

49
Copyright © 2021, ABES Engineering College
Contd..
We can also check methods associated with data structures by pressing the tab
over the keyboard.

50
Copyright © 2021, ABES Engineering College
1.2.6 Online compilation support
Assume your machine lacks the necessary resources to install, but you need to
learn Python or run code to try something.

What if you could run Python online in your browser?

That is very great. Isn't that, right?

You will need a browser, which you already have. Using online IDEs saves yor
time in the configuration process.

51
Copyright © 2021, ABES Engineering College
Contd..

w3schools(https://www.w3schools.com/python/python_compiler.asp)

52
Copyright © 2021, ABES Engineering College
Contd..

Onlinegdb (https://www.onlinegdb.com/online_python_compiler)

53
Copyright © 2021, ABES Engineering College
Contd..

One compiler (https://onecompiler.com/python/3wukez6hf)

54
Copyright © 2021, ABES Engineering College
Review Questions

 Which version of Python is currently up to date?


 Python1
 Python2
 Python4
 Python3

 The version of Python (if any) that comes pre-installed on your


operating system is called _.
 Onboard Python
 Monty Python
 Easy Python
 System Python

55
Copyright © 2021, ABES Engineering College
Review Questions

 In a Python context, the acronym IDLE stands for:


 Integrated Development and Learning Environment
 Interpretive Dance Lessons
 Interstellar Dust Laser Explorer
 None of the above

 When you see >>> inside IDLE, it means that:


 An error has occurred
 Your computer is having an existential crisis
 Python is waiting for you to give it some instructions
 Python is upset

56
Copyright © 2021, ABES Engineering College
Session Plan - Day 4

1.3 Basics of Python


1.3.1 Python keywords
1.3.2 Python Statement and Comments
1.3.3 Python Literals
1.3.4 Data Types
1.3.5 Variables
1.3.6 type (), dir (),ID command

57
Copyright © 2021, ABES Engineering College
Python keywords

Python keywords are special reserved words that have specific meanings
and purposes.

These reserve words cannot be used as a –

 function name
 variable name
 identifiers

Note - As of python 3.9.2, there are 35 reserved words in Python.

58
Copyright © 2021, ABES Engineering College
Contd..

The list of such keywords is mentioned below –


True False class def except
if elif else try is
raise finally for in lambda

not from import global continue

nonlocal pass while break del


and with as yield

or assert None return

59
Copyright © 2021, ABES Engineering College
Python Statement and Comments
Python Statement –
 In Python Programming, any executable instruction, that tell the computer to perform a specification
action is refer to as statements.

 Program statement can be an

 input-output statements,

 arithmetic statements,

 control statements,

 simple assignment statements

 and any other statements

 it can also includes comments.

60
Copyright © 2021, ABES Engineering College
Python Literals

Literals are the type of data that is used to store in a variable or constant.

Types of python literals:


 String literals
 Numeric Literals
 Integer Literals
 Float Literals
 Complex Number Literals
 Boolean Literals
 Special literals
 Literal Collections

61
Copyright © 2021, ABES Engineering College
String literals
When set of character are enclosed in quotes ( single quotes or double quotes)
then it formed a string literals.
'abes' 'rate_of_interest' '123', '12.5'
Example -
"ABESEC" "Simple_interest" "A1" "456 "

In Python we can also create multi-line literals by using ‘\’.

Example -
'ABES Engineering College \ "ABES Engineering College \
NH-24 Delhi Hapur Bypass \ NH-24 Delhi Hapur Bypass \
Near Crossing Republic' Near Crossing Republic"

62
Copyright © 2021, ABES Engineering College
Numeric Literals
Numeric literals are of multiple types based on the number type. The types
of numeric literals are integer, float (decimal numbers), and complex
numbers.

Integer Literals - They can be either positive or negative.

Example – 12, 23000000, -45, 0 , -23987

Float Literals - These are basically real numbers that consist of both integer
as well as fractional parts.

Example - -12.45, 12.90, 100.0

63
Copyright © 2021, ABES Engineering College
Numeric Literals

Complex Number Literals - The numerals will be in the form of a + bj,


where ‘a‘ is the real part and ‘b‘ is the complex part.

Python allows us to specify complex numbers like any other variable.

Example -
10j , 1 + 0j , 10 + 2J, 12 – 5j

64
Copyright © 2021, ABES Engineering College
Boolean Literals , Special literals
Boolean Literals - True or False are the values to be used as the Boolean
values.

Example - True, False

In Python, True represents the Non-zero value and False represents the
value as Zero.

Special literals - Python has a special literal named None.

Note - None is used to signify the NULL value.

65
Copyright © 2021, ABES Engineering College
Literal Collections
List Literals – List is a set of values of different types. The values are
separated by comma (,) and enclosed within square brackets( [ ]).

[ 1, 23, 23.4, 100]


Example –
[ 'Blue', 'red', 123, 23.5 ]

Tuple literals – A tuple is a set of values of different types. The values are
separated by comma(,) and enclosed within parentheses “ ( ) “. It is
immutable.
Example -
( 1, 23, 23.4, 100 )

( 'Blue', 'red', 123, 23.5 )


66
Copyright © 2021, ABES Engineering College
Literal Collections
Dictionary literals – It is in form of key-value pair. It is enclosed by curly-
braces “{ }” and each key-value pair is separated by commas (,) .

Example – { 'name':'BOB', 'age':24, 'marks':59.4 }

Set literals – Set is a collection of values of different types. The values are
separated by comma (,) and enclosed within curly-braces “{ }”. It is
unordered and contains only unique value.

{ 1, 23, 45, 56, 67 }


Example -
{ 'Ram', 'Rajesh', 12, 34.5 }
67
Copyright © 2021, ABES Engineering College
Variables
Variable are the names given by the users to the memory locations to store
the data values.
In Python, variable need not to be declared or defined in advances, as we
do in many other programming language.

To create a variable, we just assign it a value and start using it.

Example – a = 23
Here ‘a’, ‘name’ and ‘Marks’ are variable which
name = 'Ram'
refer an integer value 23, a string ‘Ram’ and float
Value 23.5.
Marks = 23.5

68
Copyright © 2021, ABES Engineering College
Variables
Rules for variable name –
 Variables can be named with an alpha-numeric combination, started with
an alphabet or underscore.
 Variable name can’t start with digit.
 Multi- word space separated name can’t be used as a variable name.
 The reserved words(keywords) cannot be used naming the variable.

Valid Variable Names In-Valid Variable Names


Name, num1,
rate_of_interest, for, 123b, rate of
_abc, marks interest, marks-math

69
Copyright © 2021, ABES Engineering College
Can you answer these questions?

1. Select all Valid variable names -

1) age

2) _age

3) -age

4) age_*

5) Item-Number-1

70
Copyright © 2021, ABES Engineering College
type() command
type () command helps in finding the type of the specific declared variable
or a value.

Example –

71
Copyright © 2021, ABES Engineering College
id() command
id () command gives the unique id for a given objects / variable / values.

Note - The unique id is the memory address and will be different each time
when you run for variable or values.

Example –

Unique Identity

72
Copyright © 2021, ABES Engineering College
dir() command
dir () command is a vital function that returns all the properties and
methods associated with given objects.

Example –

Note – Detailed description will be


explain in OOPs

73
Copyright © 2021, ABES Engineering College
Session Plan - Day 5

1.3 Basics of Python


1.3.7 Type conversion: implicit and explicit
1.3.8 Basic I/O Operations: input (), print ()

74
Copyright © 2021, ABES Engineering College
Type conversion
The process of converting the value of one data type (e.g. integer, string,
float, etc.) to another data type is called type conversion.

Example -
12.5  12 ( float to integer )
'123'  123 ( string to integer )
12  12.0 ( integer to float )

Python has two types of type conversion –

 Implicit Type Conversion


 Explicit Type Conversion

75
Copyright © 2021, ABES Engineering College
Type conversion : Implicit Type Conversion

Implicit Type Conversion – In this Python interpreter itself converts one


type of data to another data type as per the performed operation.

This type conversion happens automatically without any user intervention.

Example –

Note - Python promotes the conversion of the lower data type (integer) to
the higher data type (float) to avoid data loss.

76
Copyright © 2021, ABES Engineering College
Type conversion : Explicit Type Conversion

Explicit Type Conversion – In this, user converts the data type of variable
of value to needed data type.

Example –

int()  for Integer


float() for Float
str()  for string
Note – There should be valid Numbers while converting any
string to Numbers.
Complex  for complex

77
Copyright © 2021, ABES Engineering College
Can you answer these questions?

1. What will be the output of the following -

a) 12 (20+0j) 123.45

b) 12 20 123.45

c) Error

78
Copyright © 2021, ABES Engineering College
Basic I/O Operations

In python, various built-in functions are present.

The two important standard input-output functions in python are:

 input() : to take the input from the user

 print() : to show the output on the console

79
Copyright © 2021, ABES Engineering College
Basic I/O Operations : input()
Syntax –
input(prompt='')
Prompt - A String, representing a default message
before the input.

Example –

Note – It return value as a string. So you need to typecast it.

80
Copyright © 2021, ABES Engineering College
Basic I/O Operations : input()
Syntax –
input(prompt='')
Prompt - A String, representing a default message
before the input.

Example –

81
Copyright © 2021, ABES Engineering College
Basic I/O Operations : input()
When we take input using input() function, it return value in string data type.

Example –

As we can see in the above example type of “a” is string

Note – We have to typecast input


value into desired type.

82
Copyright © 2021, ABES Engineering College
Basic I/O Operations : print()
print () is a built-in standard function used to print the output to the console.

Syntax – print(value, ..., sep='', end='\n’)

 value – Can be of any literals, variable, expression, statements

 sep - (optional), Specify how to separate the values, if there is more than
one. Default is ' '.

 end - (optional), Specify what to print at the end. Default is '\n‘

Note – We can assign any set of character into sep.

83
Copyright © 2021, ABES Engineering College
Basic I/O Operations : print()
Example –

In the above example value of a and b is separated by space i.e. default

Here separator is sep='--', so both value is


separated by '--‘ as shown in output.

84
Copyright © 2021, ABES Engineering College
Basic I/O Operations : print()
Example – Write a Python program that takes two integer as input from
user and print sum of both.

85
Copyright © 2021, ABES Engineering College
Session Plan - Day 6

1.3 Basics of Python


1.3.9 Operators
1.3.10 Precedence and associativity
1.3.11 Python 2 vs Python 3

86
Copyright © 2021, ABES Engineering College
Operators
Operators are symbol, used to perform mathematical and logical
operation.

In python operators are categorized


into six categories -

87
Copyright © 2021, ABES Engineering College
Arithmetic operators
There are seven arithmetic operators, and these are of:
Operator Meaning Example
Add two operands or x+y
+ unary plus +2
Subtract right operand from the left or x-y
- unary minus -2
* Multiply two operands x*y
Divide left operand by the right one (always results into
/ float)
x/y
Modulus - remainder of the division of left operand by the
% right
x % y (remainder of x/y)
Floor division - division that results into whole number
// adjusted to the left in the number line
x // y

** Exponent - left operand raised to the power of right x**y (x to the power y)

88
Copyright © 2021, ABES Engineering College
Arithmetic operators
Example of all mentioned arithmetic operators

89
Copyright © 2021, ABES Engineering College
Comparison (Relational) Operators

Operator Meaning Example


The comparison operators
are used for comparisons. Greater than -> True if left operand is
> x>y
greater than the right
Less than -> True if left operand is less than
< x<y
Comparison operators the right
compare two values and == Equal to -> True if both operands are equal x == y
evaluate down to a single Not equal to -> True if operands are not
!= x != y
Boolean value ( True / False equal
). >=
Greater than or equal to -> True if left
x >= y
operand is greater than or equal to the right
Less than or equal to -> True if left operand
<= x <= y
is less than or equal to the right

90
Copyright © 2021, ABES Engineering College
Comparison (Relational) Operators

Example of all mentioned


comparison operators

It always gives answer either


True or False depending upon
relation.

91
Copyright © 2021, ABES Engineering College
Comparison (Relational) Operators

Example –

Note - The == and != operators can actually work with values of any data
type. 92
Copyright © 2021, ABES Engineering College
Bitwise Operators

Bitwise operators act on the bits and performs bit by bit operation on
the operands.
Operator Meaning
Example – Evaluate 2 & 7 & Bitwise AND
| Bitwise OR
How it works - ~ Bitwise NOT
Step 1 – Convert 2 in binary  0010 ^ Bitwise XOR
Step 2 – Convert 7 in binary  0111 >> Bitwise right shift
Step 3 – Perform Bitwise & operation
Step 4 – Convert the result back to << Bitwise left shift
decimal

93
Copyright © 2021, ABES Engineering College
Bitwise Operators – Cont..

Truth Table

Bitwise NOT
A B A&B A|B A^B A ~A
0 1
0 0 0 0 0
1 0
0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

94
Copyright © 2021, ABES Engineering College
Bitwise Operators – Bitwise AND (&)

Example –

Explanation –

Step 1 – Convert 9 in binary  1001 Step 4 – Convert the result (0001)


Step 2 – Convert 3 in binary  0011 back to decimal  1
Step 3 –
1001
0011
0001

95
Copyright © 2021, ABES Engineering College
Bitwise Operators – Bitwise OR( | )

Example –

Explanation –

Step 1 – Convert 9 in binary  1001 Step 4 – Convert the result (1011)


Step 2 – Convert 3 in binary  0011 back to decimal  11
Step 3 –
1001
0011
1011

96
Copyright © 2021, ABES Engineering College
Bitwise Operators – Bitwise XOR ( ^ )

Example –

Explanation –

Step 1 – Convert 9 in binary  1001 Step 4 – Convert the result (1010)


Step 2 – Convert 3 in binary  0011 back to decimal  10
Step 3 –
1001
0011
1010

97
Copyright © 2021, ABES Engineering College
Bitwise Operators – Bitwise Left shift ( << )

Example –

Explanation –

Step 1 – Convert 9 in binary  1001 Step 3 – Convert the result (10010)


Step 2 – Shift 1001 towards left by one back to decimal  18
position and place Zero at end.
1001
10010

98
Copyright © 2021, ABES Engineering College
Bitwise Operators – Bitwise Right Shift ( >> )

Example –

Explanation –

Step 1 – Convert 9 in binary  1001 Step 3 – Convert the result (100)


Step 2 – Shift 1001 towards right by one back to decimal  4
position.
1001
100
10 01
1 will discarded
99
Copyright © 2021, ABES Engineering College
Assignment operators
Assignment operators are used to Operator Example Equivalent to
assign the values to the variables. = x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
a = 5 is a simple assignment
*= x *= 5 x=x*5
operator that assigns the value 5 on
/= x /= 5 x=x/5
the right to the variable a on the
%= x %= 5 x=x%5
left.
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
There are various compound
&= x &= 5 x=x&5
operators in Python like a += 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5

100
Copyright © 2021, ABES Engineering College
Logical Operators
Logical operators perform Logical AND, Logical OR and Logical NOT operations.

Operator Meaning Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

Truth Table – x y x and y x or y


x not x
T T T T
T F
T F F T F T
F T F T
F F F F

101
Copyright © 2021, ABES Engineering College
Logical Operators

Example –

102
Copyright © 2021, ABES Engineering College
Identity Operators
Identity Operators – is and is not are the identity operators in Python.

They are used to check if two values (or variables) are located on the same part
of the memory or not.
Operator Meaning
is Gives True if the operands are identical (refer to the same ID or Memory)
is not Gives True if the operands are not identical (do not refer to the ID or Memory)

Example

103
Copyright © 2021, ABES Engineering College
Membership Operators
in and not in are the membership operators in Python.

They are used to test whether a value or variable is found in a sequence (string,
list, tuple, set and dictionary) or not.
Operator Meaning
in Gives True if value/variable is found in the sequence otherwise False
not in Gives True if value/variable is not found in the sequence otherwise True

Example

104
Copyright © 2021, ABES Engineering College
Precedence and associativity
Operator precedence and associativity decide the priorities of the operator.

 Operator Precedence: This is used in an expression with more than one


operator with different precedence to figure out which operation to perform
first.

 Operator Associativity: If an expression has two or more operators with


the same precedence, then Operator Associativity is used to find. It can
either be Left to Right or from Right to Left.

105
Copyright © 2021, ABES Engineering College
Cont..
Precedence and Associativity Table –

106
Copyright © 2021, ABES Engineering College
Python 2 vs Python 3

 Python has started its journey in 1989-1990 when people started


implementation on it.
 In year 2000, python 2.0 came with new features and have a healthy support
to python.
 Memory management was the major part evolved in python 2.0.
 But in 2008, python has changed in a revolutionary manner to python 3.0.
 There was no support of backward compatibility in python 3.0.

107
Copyright © 2021, ABES Engineering College
Python 2 vs Python 3

Let us have a look to the differences between Python 2 and Python 3.

 In Python 2, print is a statement syntax, but in python 3, print is a built-in


function.
 In python 2, the input was taken from the user by using raw_input() function.
In python 3, input () function is used to take input instead of raw_input().
 When we divide two numbers in python 2, the output is the nearest whole
number. Like 7/2 is 3. In python 3, the fractional numeric value will be shown
as 7/2 is 3.5.

108
Copyright © 2021, ABES Engineering College
Python 2 vs Python 3

Let us have a look to the differences between Python 2 and Python 3.

 In for loop, the iterations are used using a xrange function in python 2, which
is replaced by range function in python3.
 Some of the libraries which are available in python 2 are not moved in python
3.
 Similarly, now the developers are making new libraries for python 3 which are
incompatible to python 2.

109
Copyright © 2021, ABES Engineering College
Python Programming cycle

 The programming cycle in Python, like in most programming languages, involves several key
steps that developers follow to create, test, and maintain Python programs. Here are the
main phases of the Python programming cycle:
 1. **Problem Definition*
 At the beginning of the programming cycle, you need to clearly define the problem you
want to solve with your Python program. This involves understanding the requirements,
gathering information, and defining the goals and objectives of the program.
 2. **Algorithm Design
 Once you have a clear understanding of the problem, you can design an algorithm to solve
it. An algorithm is a step-by-step plan that outlines the logic and operations your program will
perform. You may use flowcharts, pseudocode, or other tools to represent your algorithm
 3. **Coding
 Coding is the process of translating your algorithm into Python code. You write the actual
program by creating functions, classes, and variables, and implementing the logic to perform
the desired operations. This is where you write the Python statements and expressions that
make up your program.
110
Copyright © 2021, ABES Engineering College
 4. **Testing:After coding, you need to thoroughly test your Python program to
ensure that it works as intended and handles different scenarios and inputs
correctly. Testing involves both unit testing (testing individual functions or
components) and integration testing (testing how different parts of the
program work together)
 5. **Debugging: During testing, you may encounter errors or bugs in your
code. Debugging is the process of identifying and fixing these issues. Python
provides various debugging tools and techniques, such as print statements,
debugging libraries like `pdb`, and integrated development environments
(IDEs) with debugging features.
.

111
Copyright © 2021, ABES Engineering College
6. **Optimization:After you have a working program, you can optimize it to improve performance
and efficiency. This may involve refactoring code, using data structures and algorithms more
effectively, and reducing resource consumption.
7. **Documentation: Proper documentation is crucial for maintaining and sharing your Python
code. Document your code by adding comments, docstrings, and README files to explain its
purpose, usage, and any important considerations for other developers.
8. **Version Control:Using a version control system like Git is essential for tracking changes to
your code, collaborating with others, and maintaining a history of your project. You can use
platforms like GitHub or GitLab to host your Python project repositories.
9. **Deployment: If your Python program is meant for production use, you'll need to deploy it to
a server, cloud platform, or other computing environment. This step involves configuring the
necessary infrastructure and ensuring that the program runs smoothly in a production
environment.
10. **Maintenance:Software maintenance is an ongoing process that involves fixing bugs,
adding new features, and adapting the program to changing requirements. Regularly update
and improve your Python code as needed
112
Copyright © 2021, ABES Engineering College
Memory Management in Python:

 Memory management in Python is primarily handled by the Python memory


manager, which is responsible for allocating and deallocating memory for
objects in your Python programs. Python uses a combination of techniques
for memory management, including:
Reference Counting: Python keeps track of how many references there are to
an object. When an object's reference count drops to zero, it means the object
is no longer accessible, and Python can reclaim the memory used by that
object.
Garbage Collection: In addition to reference counting, Python uses a cyclic
garbage collector to identify and collect objects that are no longer reachable,
even if they have circular references (references to each other).

113
Copyright © 2021, ABES Engineering College
 Memory Pools: Python uses a system of memory pools for small objects to
reduce memory fragmentation and improve memory allocation efficiency.
 Dynamic Typing: Python's dynamic typing means that objects can change
their type during runtime, which can have implications for memory
management since objects might need to be reallocated if their type
changes.
 Memory Optimizations: Python includes various memory optimization
techniques, such as interning small integers and string literals, to reduce
memory overhead.

114
Copyright © 2021, ABES Engineering College
PEP 8:

 PEP 8 is the Python Enhancement Proposal 8, titled "Style Guide for Python
Code." It is a document that provides guidelines and recommendations for
writing Python code that is readable and consistent. PEP 8 covers topics
such as naming conventions, code layout, indentation, whitespace, and
more. Following PEP 8 helps make your Python code more understandable
and maintainable, especially when working on projects with multiple
contributors.

115
Copyright © 2021, ABES Engineering College
Some key points from PEP 8 include:

 Use 4 spaces per indentation level.


 Limit all lines to a maximum of 79 characters (or 72 for
docstrings/comments).
 Use blank lines to separate functions, classes, and blocks of code inside
functions.
 Use lowercase with underscores for function and variable names (e.g.,
my_function, my_variable).
 Use CapitalizedWords (CamelCase) for class names (e.g., MyClass).
 Import modules in separate lines and put them at the top of the file.
 Avoid extraneous whitespace.
 Use consistent naming conventions for constants (e.g., MAX_LENGTH)

116
Copyright © 2021, ABES Engineering College
Python is called as dynamic and strongly typed
language?
 Python is called a dynamic and strongly typed language due to the way it
handles data types and variable binding during runtime. Let's break down
these two characteristics:
 1. **Dynamic Typing**: In Python, variable types are not explicitly declared when you define
a variable. Instead, the data type of a variable is determined dynamically at runtime based on
the value it holds. This means that you can assign different types of values to the same
variable during the execution of your program. For example:
 ```python
 x = 5 # x is an integer
 x = "Hello" # x is now a string
 Python's dynamic typing offers flexibility and simplifies the coding process because you don't
need to declare the data type of a variable explicitly. The interpreter determines the
appropriate data type based on the value assigned to the variable.

117
Copyright © 2021, ABES Engineering College
 2. **Strong Typing: Python is also considered a strongly typed language
because it enforces strict rules regarding type compatibility and type
conversion. In strongly typed languages, operations between incompatible
data types are either prohibited or require explicit type conversion.
For example, in Python, you cannot directly concatenate a string and an integer
without converting the integer to a string:
 ```python
 x = "Hello"
 y=5
 result = x + y # This will raise a TypeError

118
Copyright © 2021, ABES Engineering College
 To perform this operation, you need to explicitly convert the integer to a string:
 ```python
 x = "Hello"
 y=5
 result = x + str(y) # Now it works
 Python's strong typing helps prevent unintended type-related errors and promotes code
safety.
 In summary, Python's dynamic typing allows for flexibility in variable assignments by
determining types at runtime, while its strong typing ensures that type-related operations are
well-defined and explicit, reducing the likelihood of subtle bugs and errors. These
characteristics contribute to Python's reputation as a language that is both flexible and safe.

119
Copyright © 2021, ABES Engineering College
Mutable and immutable data type

 In Python, data types are categorized into two main groups: mutable and
immutable. These categories describe how the data stored in variables of
these types can be modified. Here's a breakdown of the differences between
mutable and immutable data types:
 **Immutable Data Types**:
 1. **Immutable** means that once an object of an immutable data type is
created, it cannot be changed or modified. Any operation that appears to
modify the data actually creates a new object with the modified value.
 2. Immutable objects are hashable, meaning they can be used as keys in
dictionaries and elements in sets because their value will not change.
 Examples of immutable data types in Python include `int`, `float`, `str`,
`tuple`, and `frozenset`.

120
Copyright © 2021, ABES Engineering College
 Examples of Immutable Data Types:
 ```python
 # Immutable data types
 x = 42 # int
 y = 3.14 # float
 s = "Hello" # str
 t = (1, 2, 3) # tuple

121
Copyright © 2021, ABES Engineering College
 Mutable Data Types**:
 1. **Mutable** means that objects of these data types can be changed after
they are created. You can modify their contents, add or remove elements,
etc., without creating a new object.
 2. Mutable objects are not hashable, so they cannot be used as dictionary
keys or elements in sets.
Examples of mutable data types in Python include `list`, `dict`, and `set`.
 Examples of Mutable Data Types:
 # Mutable data types
 lst = [1, 2, 3] # list
 dct = {"a": 1, "b": 2} # dict
 st = {1, 2, 3} # set
122
Copyright © 2021, ABES Engineering College
Why Immutability Is Important**:

 1. **Predictable Behavior**: Immutable objects provide predictability in your code because


you can trust that once you create them, their value won't change. This predictability
simplifies debugging and reasoning about your code.
 2. **Hashability**: Immutable objects can be used as keys in dictionaries and elements in
sets because their hash value remains constant. This is essential for data structures that rely
on efficient hash-based lookups.
 3. **Safety in Concurrency**: In multithreaded or multiprocessing environments, immutable
objects are safer to work with because you don't have to worry about other threads or
processes modifying the same object concurrently.
 4. **Functional Programming**: Immutability aligns well with functional programming
principles, making it easier to write functional-style code in Python.
 5. **Caching**: Because immutable objects have constant values, they can be cached and
reused, which can improve performance in certain situations.

123
Copyright © 2021, ABES Engineering College
Multiple comments
Multiline Comments: Python does not have a specific multiline comment syntax like
some other programming languages. However, you can achieve multiline comments
using triple-quoted strings (either single or double-quoted). These strings are often
used as docstrings for documenting functions, classes, or modules.
While they are not technically comments, they can serve a similar
purpose for adding multiline explanations or comments within your code. Here's an example:
python
•""" This is a multiline comment or docstring. You can write multiple lines of
text here. It is often used for documentation. """

It's important to note that these multiline strings are not ignored by the Python
interpreter, but they are typically used for documentation and are not treated as comments for execution purposes.

124
Copyright © 2021, ABES Engineering College
•Variable Declaration and Data Types: In Python, you do not need to declare
variables with explicit data types as you do in some statically typed languages
like C or Java. Python uses dynamic typing, which means that variable types
are determined automatically based on the values assigned to them. You can
simply
•assign a value to a variable, and Python will infer its data type. For example:
python
my_variable = 42 # An integer
my_string = "Hello" # A string
my_list = [1, 2, 3] # A list
Python will assign appropriate data types to these variables based on the
values you provide.

125
Copyright © 2021, ABES Engineering College
While you don't need to declare data types explicitly, Python is still strongly
typed,
meaning that variable types matter in operations.
For example, you cannot add a string and an integer directly without explicit
type conversion:
python
result = my_string + str(my_variable) # Convert integer to string before
concatenation
Python will raise a TypeError if you try to perform incompatible operations on variables with
different types

126
Copyright © 2021, ABES Engineering College
solve the mathmaticalll expression 7/3*1.2+3/2
Ans:

To solve the mathematical expression:


1.First, perform the division: 7/3 = 2.333333...
2.Next, multiply the result by 1.2: 2.333333... * 1.2 = 2.8
3.Then, perform the second division: 3/2 = 1.5
4.Finally, add the two results together: 2.8 + 1.5 = 4.3
So, the result of the expression 7/3*1.2+3/2 is 4.3.

127
Copyright © 2021, ABES Engineering College
Prime no is not?

num = 11
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, int(num/2)+1):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

128
Copyright © 2021, ABES Engineering College
A leap year is exactly divisible by 4 except for century years (years ending with 00).
The century year is a leap year only if it is perfectly divisible by 400.
For example,
2017 is not a leap year 1900 is a not leap year 2012 is a leap year 2000 is a leap year
Source Code
\

129
Copyright © 2021, ABES Engineering College
Find sum of digits , reversal of digits of given no

130
Copyright © 2021, ABES Engineering College
131
Copyright © 2021, ABES Engineering College
semicolons

 In Python, semicolons are primarily used as statement terminators, allowing


you to write multiple statements on a single line. While they are not
commonly used in Python, there are a few situations where semicolons can
be beneficial:
 1.Multiple Statements on a Single Line: You can use semicolons to write
multiple statements on a single line, which can be useful for compact code in
some cases. For example
 a = 1; b = 2; c = a + b
2.In the Python REPL (Interactive Shell): Semicolons can be handy when
using the Python interactive shell (REPL) to quickly execute multiple statements
on a single line. This can help when experimenting or testing code interactively

132
Copyright © 2021, ABES Engineering College
 Conditional Expressions: Semicolons can be used within conditional
expressions. For example:
 x = 5 if a > b else 10; y = 20 if a < b else 15
While this is possible, it's often more readable to use the regular if-
else statements.
Despite these limited use cases, it's important to note that the
Python community generally follows a coding style that favors
readability and clarity. The use of semicolons to write multiple
statements on a single line is discouraged in most cases.

133
Copyright © 2021, ABES Engineering College
Summary
 Python is an open-source, high level, interpreter- based language that can be used for scientific
and non-scientific computing purposes.
 Comments are non-executable statements in a program.
 An identifier is a user defined name given to a variable or a constant in a program.
 Datatype conversion can happen either explicitly or implicitly.
 Operators are constructs that manipulate the value of operands.
 Python has input() function for taking user input.
 Python has print() function to output data to a standard output device.
 There are several data types in Python — integer, boolean, float, complex, string, list, tuple, sets,
None and dictionary.

134
Copyright © 2021, ABES Engineering College
References
1. https://docs.python.org/3/tutorial/controlflow.html

2. Think Python: An Introduction to Software Design, Book by Allen B. Downey

3. Head First Python, 2nd Edition, by Paul Barry

4. Python Basics: A Practical Introduction to Python, by David Amos, Dan Bader, Joanna Jablonski,
Fletcher Heisler

5. https://www.fullstackpython.com/turbogears.html

6. https://www.cubicweb.org

7. https://pypi.org/project/Pylons/

8. https://www.upgrad.com/blog/python-applications-in-real-world/

9. https://www.codementor.io/@edwardbailey/coding-vs-programming-what-s-the-difference-yr0aeug9o
135
Copyright © 2021, ABES Engineering College
Thank You

136
Copyright © 2021, ABES Engineering College

You might also like