0% found this document useful (0 votes)
8 views119 pages

Getting Started with Python Basics

This document serves as a training guide for learning Python, covering essential topics over six days, including installation, basic features, and advantages and disadvantages of Python. It outlines a structured session plan with review questions to reinforce learning. The document emphasizes Python's applications in various fields such as web development, data science, and artificial intelligence.

Uploaded by

Astha Panda
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)
8 views119 pages

Getting Started with Python Basics

This document serves as a training guide for learning Python, covering essential topics over six days, including installation, basic features, and advantages and disadvantages of Python. It outlines a structured session plan with review questions to reinforce learning. The document emphasizes Python's applications in various fields such as web development, data science, and artificial intelligence.

Uploaded by

Astha Panda
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

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
• 1.3.3 Python Literals
• 1.1.2 Why choose Python Environment
• 1.2.3 Installation of • 1.3.4 Data Types
Python • 1.1.8 Applications of
Python Python and Anaconda • 1.3.5 Variables
• 1.1.3 Scope of
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

?
[Link]

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;
[Link](“Hello, return 0;
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”)
▪ [Link](“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.,
[Link]. Refer to the current stable version 3.9.4 as of date 13 April
[Link] 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 [Link] (.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 [Link]
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 [Link].
• 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
[Link]
/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
[Link] 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 [Link]
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 [Link] 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
1.2.6 Online compilation support
There are various python online editors available in an open market. Here are
the few editors:

Programiz([Link]

52
Copyright © 2021, ABES Engineering College
Contd..

w3schools([Link]

53
Copyright © 2021, ABES Engineering College
Contd..

Onlinegdb ([Link]

54
Copyright © 2021, ABES Engineering College
Contd..

One compiler ([Link]

55
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

56
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

57
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

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

59
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

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

61
Copyright © 2021, ABES Engineering College
Python Statement and Comments
Python Comments –
❑ Comments are a set of statements that are ignored by the python interpreter.

❑ The use of comments makes it easy for humans to understand the source code.

Comments are of two types –


❑ Single-line Comments – A hash sign (#) is used to specify a single line comment

Example –

❑ Multi-line Comments – You can do it other way using a triple quotes, either ''' ''' or """ """ .

Example –

62
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

63
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'
Example - '123', '12.5'
"ABESEC" "Simple_interest"
"A1" "456 "

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

Example -
'ABES Engineering "ABES Engineering
College \ College \
NH-24 Delhi Hapur NH-24 Delhi Hapur
Bypass \ Bypass \
Near Crossing Republic' Near Crossing Republic"
64
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

65
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

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

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


68
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 }
69
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

70
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

71
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

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

Example –

73
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

74
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

75
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 ()

76
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

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

78
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 Complex for complex
any string to Numbers.

79
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

80
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

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

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

Example –

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

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

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

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

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

What will be the output of the following -


a) 12 23.5 ABESEC

b) 12\n23.5\nABESEC
c)
12

23.5
ABESEC

88
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

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

In python operators are categorized


into six categories -

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

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

92
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 / equal
False ). >=
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

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

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

Example –

Note - The == and != operators can actually work with values of any data
type. 95
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

96
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

97
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

98
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

99
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

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

Example –

Explanation –

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


Step 2 – Shift 1001 towards left by one back to decimal 18
position and place Zero at end.
1 0 0
1
1 0 0
1 0
101
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.
1 0 0
1 1 0
0
1
0 0 1 1 will discarded
102
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

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
**= 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

103
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

104
Copyright © 2021, ABES Engineering College
Logical Operators

Example –

105
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

106
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

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

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

109
Copyright © 2021, ABES Engineering College
print (9 + 2 - 6 * 4)
10 - 4 * 2
print(5 * 2 // 3)
print(5 * (2 // 3))
print(2 ** 3 ** 2)
print((2 ** 3) ** 2)

110
Copyright © 2021, ABES Engineering College
num1, num2, num3 = 2, 3, 4
print ((num1 + num2) * num3)

num1, num2, num3 = 2, 3, 4


print (num1 ** num2 + num3)

num1, num2, num3, num4 = 8, 2, 3, 6


num5 = ((num1 * num2) - (num3 + num4))
print(num5)
num1, num2, num3 = 2, 3, 2
num4 = num1 ** num2 ** num3
print(num4)
111
Copyright © 2021, ABES Engineering College
112
Copyright © 2021, ABES Engineering College
Print(~4)

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

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

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

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

117
Copyright © 2021, ABES Engineering College
References
1. [Link]

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. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link]

118
Copyright © 2021, ABES Engineering College
Thank You

119
Copyright © 2021, ABES Engineering College

You might also like