0% found this document useful (0 votes)
19 views

Full Stack Python YT

Chapter 1 introduces programming languages, distinguishing between low-level and high-level languages, and explains the roles of translators like interpreters and compilers. It covers the features and applications of Python, its history, versions, and key characteristics such as being open-source and platform-independent. Additionally, it discusses Python's programming paradigms, libraries, frameworks, and working modes including interactive and scripting modes.

Uploaded by

edigamythri4
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)
19 views

Full Stack Python YT

Chapter 1 introduces programming languages, distinguishing between low-level and high-level languages, and explains the roles of translators like interpreters and compilers. It covers the features and applications of Python, its history, versions, and key characteristics such as being open-source and platform-independent. Additionally, it discusses Python's programming paradigms, libraries, frameworks, and working modes including interactive and scripting modes.

Uploaded by

edigamythri4
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/ 232

Chapter-1

Topics
======
Introduction to Languages
 What is Language?
 Types of Programming Languages
 Translators
o Interpreter
o Compiler
 Scripting Language
 Difference between Programming Language and Scripting Language
 Programming Paradigms
o Procedural Oriented Programming
o Object Oriented Programming

What is language?
A language is software, which provides set of instructions for developing
software’s.
Language acts as mediator between user and computer.

Computer languages are classified into two categories.


1. Low Level Programming Languages
2. High Level Programming Languages

Low Level Programming Languages


Computer understandable languages are called low level programming
languages.

1. Machine Language
2. Assembly Language

Machine Language
Machine language instructions are represented in 0’s and 1’s.
Computer understands only one language called machine language.
Machine language instructions are machine dependent (OR) hardware
dependent.
Machine language instructions are not easy to understand.
Machine Language does not require any translator.

Assembly Language
Assembly language is low level language, but instructions are not given in
0’s and 1’s but instructions are represented in mnemonics (verbs).

ML AL
1010 1111 MOVE

What is assembler?
Assembler is a translator used by assembly language for converting
assembly language instructions into machine language.

Low level languages are non portable or hardware dependent.

High Level Programming Languages


All high level programming languages are in simple English.
High level programming languages are hardware independent.
Using high level programming languages, programmer can develop and
run applications on different hardware architecture.

Example: C,C++,COBOL,PASCAL,Java,Python,.Net,JavaScript

What is translator?
Translator is software, which convert instructions of one language to
another language.

1. Interpreter
2. Compiler
What is translator?
Translator is software, which converts instructions of one language to
another language.

1. Interpreter
2. Compiler

What is program?
A program is set of instructions.

What is source program?


A program written in high level programming language is called source
program.

What is interpreter?
Interpreter is a translator, which translates and executes instructions line
by line.
Interpreter stops translating and executing, if there is an error in one
line. Interpreted code executed by machine directly. Interpreter displays
one error at a time. Debugging program is complex.
Scripting languages uses interpreter as a translator.

What is compiler?
Compiler is a translator, which translates whole program and execute.

Compiler display all error exist within program. If there is error within
program, compiler not generates executable code/file.
What is scripting language?
A scripting language is one type of programming language which is used
for writing scripts.

What is a script?
A script is a small program executed within another program.
Scripts are embedded within another program.
Scripts are used for automation.

Example: Java script, VBscript, typescript, Perl, PHP,..

A script cannot execute individually. It is embedded within another


program and executed.
A programming language can be used as a scripting language.
Scripting language cannot be used as a programming language.

Programming paradigm
A programming paradigm defines a set of rules and regulations for writing
programs.
1. Procedural Oriented Programming (POP)
2. Modular Oriented Programming (MOP)
3. Object Oriented Programming (OOP)
4. Functional Oriented Programming (FOP)

C is a Procedural oriented programming language


C++ is Object Oriented Programming Language
Java is Object Oriented Programming Language
Python is Object Oriented Programming Language
C#.Net is Object Oriented Programming Language
Introduction to Python
● What is Python?
● Applications of Python
● History of Python
● Python Features
● Limitations of Python
● Python Versions
● Python Implementations

What is Python?
Python is a programming language.
Python is a general purpose programming language. This language is used
for developing any type of software or application.
Python is high level programming language. All high level languages are in
simple English. High level languages are portable. Portability allows
developing and running applications on different hardware architecture.
Python is multi paradigm programming language. A programming
paradigm defines set of rules and regulations for writing program. Python
is object oriented programming language and also supports other
programming paradigms (POP, MOP, FOP, SOP).

“Python is general purpose, high level and multi paradigm programming


language”

Applications of Python
In real time or software companies uses python for developing which type
of software’s or applications or projects.

For developing software or project a person required 2 things


1. Python
2. Libraries or Framework

What is library?
A library is set of predefined programs with pre-written functionality.
Python provides huge set of libraries.
A language uses libraries for developing different types of applications.

What is Framework?
Framework is software which provides libraries.
Framework provides development environment and execution
environment.

1. Web Applications or Internet Applications


2. Mobile Applications
3. Web Scraping
4. Cloud Computing (AWS) or AWS Data Engineering
5. Data Science or BA or DA
6. Machine Learning (AI)
7. Testing (Selenium)
8. Automation
9. Games
10. Embedded Application
11. Cyber Security
12. Audio and Video Processing
13. Image Processing
14. Language Development
15. Operating Systems
16. CAD/CAM
17. Block Chain
18. DEVOPS with Python

Python History
Python History
Python was conceived in the late 1980s by Guido van Rossum at Centrum
Wiskunde & Informatica (CWI) in the Netherlands as a successor to the
ABC programming language, which was inspired by SETL, capable of
exception handling and interfacing with the Amoeba operating system. Its
implementation began in December 1989.
First Version of python is released in the year 1991.
Python is product of or Python language is managed by non-profit
organization called PSF (Python Software Foundation).
Python language is implemented or developed in C language.
Python language is developed by taking features from various
programming languages.
1. C (Procedural Oriented Programming)
2. C++ (Object Oriented Programming)
3. Perl (Scripting Language)
4. Modula7 (Modular Programming)

Python name is taken from a comedy series called “Monty Python’s Flying
Circus”

Python Versions
Versions are nothing but changes within python language or software.
Python comes in 3 Versions.

1. Python 1
2. Python 2
3. Python 3

1,2,3 are called major releases or versions of python language. There is


no compatibility between major versions.
Python 1 à python 1.0,Python 1.1,Python 1.2, Python 1.3
Python 2 à Python 2.0,Python 2.1,Python 2.2,…. 2.7
Python 3 à Python 3.0,Python 3.1,Python 3.2,Python 3.4 .. Python 3.12

Python 1 and 2 are outdated and not used by software companies.


Software companies currently using python3 version. There is
compatibility between minor versions ( Python 3.1 à Python 3.2).

What is PEP?
PEP stands for Python Enhancement Proposal. It is a technical document
which consists of changes done within python language.

Python 3.12 à PEP 693


Python 3.11 à PEP 664

Python Features
Python features are nothing but facilities provided by python language to
software developers.

1. Easy or Simple
2. Free and Open Source
3. Large Standard Libraries
4. Platform Independent
5. Dynamic
6. Portable
7. High Level
8. Object Oriented
9. Extensible
10. Embeddable
11. Robust

Easy or Simple
Python Features
Python features are nothing but facilities provided by python language to
software developers.

1. Easy or Simple
2. Free and Open Source
3. Large Standard Libraries
4. Platform Independent
5. Dynamic
6. Portable
7. High Level
8. Object Oriented
9. Extensible
10. Embeddable
11. Robust

Easy or Simple
Python is easy or simple because it provides the following features which
makes python is easy or simple.
1. Python Syntax is Simple
2. Python is user/programmers friendly programming language, It
allows you to write programs using multiple programming
paradigms.
3. Less Coding, python provides large standard libraries, which
provides predefine code.
4. Automatic memory management. In application development
memory managed consist of two things
a. Allocation of memory
b. De-Allocation of memory
In python memory management is automatic; python provides a
service called garbage collection.

Free and Open Source


Python software is free to download.
Python software can be downloaded from www.python.org

What is open source?


Python language is written in “C” language.
Python software source code is given to public. If source code is given to
public, it can modified and develop new languages, frameworks.

Large Standard Libraries


Python provides large number of libraries. A library is predefined
program, with pre-written functionality. Libraries make application
development easy.
Python libraries are available in website or repository called,

www.pypi.org

pypi stands python package index


python libraries are divided into two,

1. Modules
2. Packages

A module is python program.


A collection of module is called packages.

Platform Independent
Programming languages are two types
1. Platform dependent languages
2. Platform independent languages

What is platform?
Platform is software, which provides development environment and
execution environment. Operating System is called platform. Operating
system acts as an interface between software and hardware.

Platform dependent languages


C,C++ are called platform dependent language.
Platform Independent
Programming languages are two types
1. Platform dependent languages
2. Platform independent languages

What is platform?
Platform is software, which provides development environment and
execution environment. Operating System is called platform. Operating
system acts as an interface between software and hardware.

Platform dependent languages


C,C++ are called platform dependent language.
In platform dependent languages, development environment and
execution environment must same.

Why C,C++ are called platform dependent?


1. C,C++ compilers generate native code (OR) binary code respective
to operating system. This code is platform (OR) OS dependent.

2. C,C++ programming languages data representation is not same for


all operating systems.
Problem with platform dependent languages
1. Need to develop same application for every operating system
2. Increases development cost

Platform independent language


In platform independent languages development environment and
execution environment may not be same.

What is byte code?


Compiled code of python source program is called byte code.
Byte code is python virtual machine code (PVM).
Byte code is platform independent code.
Byte code is not 0’s and 1’s. Byte code collection of mnemonics.
What is PVM?
PVM stands for Python Virtual Machine. It is software provided by python.
PVM having translator called interpreter, which translate byte code in
executable machine binary code.

Data representation in python is same for all operating systems.


Advantage of platform independent languages are write once run
anywhere or compile once and run anywhere.

Dynamic
Programming languages are two types
1. Statically typed programming languages
2. Dynamically typed programming languages

C,C++,Java,C#.net are called statically typed programming languages.


In statically programming languages, variables are created with data type
(OR) variables are bind with one data type (OR) variables declaration is
required.

Python is a dynamically typed programming language, In python there is


no variable declaration. Variables in python not bind with one data type.
Its type changes based on value assigned.

Object Oriented Programming


Object oriented is not language; it is a programming paradigm which
defines set of rules and regulations for writing programs. All modern
language uses OOP for developing applications or programs. It also
supports other programming paradigm.

High Level
Portable
Embeddable
Extensible
Robust
High Level
Python is high level programming language and all high level programming
language is in simple English.

Portable
Portability allows developing and running python program on any device
or hardware architecture.

Embeddable and Extensible


Using python code inside other programming languages is called
embeddable.
Using other languages code within python is called extensible

Robust
Robust means strong
Python is very strong in error checking.
Python provides an exception handling, using which a program can handle
runtime error to avoid abnormal termination program.

Python Software
Python software is free to download.

www.python.org
How to verify python software is installed or not?

1. Open command prompt


a. Search à CMD

2.

Python software provides


1. Editor/IDE à IDLE (Integrated Development Learning Environment) is
a code editor provided by python software
2. Python Virtual Machine (PVM)
3. Python Shell
4. Standard Libraries Or Language related libraries but application
specific libraries does not comes with python software.
5. Tools (Python Library Installer (PIP), Python Debugger,…)

IDE’s
1. Pycharm
2. Spyder
3. VSCode
4. Google Collab
5. Jupiter Notebook

Python Distributions
Python distribution is python software bundle which consists of,
1. Python software
2. Application Specific Libraries
3. Editors or IDE

 ActiveState ActivePython (commercial and community versions,


including scientific computing modules)
 pythonxy (Scientific-oriented Python Distribution based on Qt and
Spyder)
 winpython (WinPython is a portable scientific Python distribution
for Windows)
 Conceptive Python SDK (targets business, desktop and database
applications)
 Enthought Canopy (a commercial distribution for scientific
computing)
 PyIMSL Studio (a commercial distribution for numerical analysis –
free for non-commercial use)
 Anaconda Python (a full Python distribution for data management,
analysis and visualization of large data sets)
 eGenix PyRun (a portable Python runtime, complete with stdlib,
frozen into a single 3.5MB - 13MB executable file)

Python Implementations
IronPython (Python running on .NET)
Jython (Python running on the Java Virtual Machine)
PyPy (A fast python implementation with a JIT compiler)
Stackless Python (Branch of CPython supporting microthreads)
MicroPython (Python running on micro controllers)

Python working modes


Python working modes are two,
1. Interactive mode
2. Scripting mode/programming mode

Interactive mode
Python working modes
Python working modes are two,
1. Interactive mode
2. Scripting mode/programming mode

Interactive mode
In interactive mode python developer or programmer works with python
shell.
Python shell is command line interface or python shell is REPL tool
REPL stands for Read-Evaluate-Print-Loop.
Python shell is single line command line interface.
In interactive mode programmer cannot develop or write programs.

What is use of interactive mode?


1. Configurations
2. Testing command executed properly or not
3. Learners starts learning giving commands in interactive mode

How to work in interactive mode?


1. Without using Editor/IDE
2. Using IDE/Editor

How to work in interactive mode without using editor?


1. Open Command prompt Or DOS Environment

2.
3.
Working with interactive mode using IDE or Editor
Every editor allows working in two modes.
1. Interactive mode
2. Scripting mode or Programming mode

 Open IDLE
 Search à IDLE
Programming Mode or Scripting Mode
In programming mode, python developer creates a program or file by
storing all the instructions. This file or program can be executed one or
more than one time. Every python program is saved with extension .py
(source file or source program).
Every python program is called module.

1. Writing python program in non python editor (Notepad)

 Open Notepad
 Type program and save with extension .py

 Open command prompt


 Search à cmd
2. Writing python program using editor (IDLE)

 Open IDLE
 Select File à New File
 Type Python Program

 Save Program à File à Save


 Run Program à Run à Run Module
Programming Fundamentals

1. Character set of Python


2. Tokens
a. Keywords
b. Identifiers
c. Literals
d. Data Types
e. Operators

Character set of python

Character set defines encoding and decoding standard used by python


programming language.
Character set defines set of characters supported by python programming
language.

There are two encoding standards supported by python language


1. ASCII à American Standard Code for information Interchange
2. UNICODE à Universal code

ASCII support 256 characters 0-255, these 256 characters includes


Characters in English (a-z,A-Z), Digits (0-9), Sepcial characters
(+,-,*,/,%#!,…)

UNICODE super set of ASCII, It support characters of ASCII and also having
more number of characters support from other languages.

UNICODE support more than 1,00,000 characters.

Python and all modern languages support ascii and Unicode character
set.
Uppercase Letters A – 65
B -66

Z – 90
Lowercase Letters a -97
b-98

z-122
Tokens
A token is smallest individual unit within program.
Without tokens a statement cannot created.

1. Keywords
2. Identifiers
3. Literals
4. Data types
5. Operators

Keywords
Keywords are language related words. The meaning of keyword is
reserved by python translator.
Each keyword is used to perform specific operation.

How to find keywords of python?

>>> import keyword


>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']

How many keywords are in python?


>>> len(keyword.kwlist)
35
Python 3.12 version supports 35 keywords.
Python is case-sensitive language; it finds the difference between
uppercase and lowercase.

Soft Keywords
Soft keywords can be used as user defined word or identifiers.

>>> keyword.softkwlist
['_', 'case', 'match', 'type']

Identifiers
Identifier is programmer defined words or user defined words. Identifier
is used to identify programming elements.

1. Variable names
2. Function names
3. Data type names
4. Program name / Module name
5. Package name

Identifier is a single word, this word is created using alphabets (a-z, A-Z),
digits (0-9) and one special character (_)
Identifiers
Identifier is programmer defined words or user defined words. Identifier
is used to identify programming elements.

1. Variable names
2. Function names
3. Data type names
4. Program name / Module name
5. Package name

Identifier is a single word, this word is created using alphabets (a-z, A-Z),
digits (0-9) and one special character (_)

1. Identifier should not be keyword

>>> a=10
>>> a
10
>>> rollno=1
>>> rollno
1
>>> pass=100
SyntaxError: invalid syntax
>>> break=1
SyntaxError: invalid syntax
>>> class=5
SyntaxError: invalid syntax
>>> Pass=1
>>> Pass
1

2. Identifier can be defined in uppercase or lowercase. Python is a


case sensitive language, which finds the difference between
uppercase and lowercase

>>> A=10
>>> a=20
>>> A
10
>>> a
20

3. There should not be any space between identifier

>>> student number=1


SyntaxError: invalid syntax

4. Identifier is allowed only one special character _

amt$=10
SyntaxError: invalid syntax
$amt=1
SyntaxError: invalid syntax
>>> a*mt=1
SyntaxError: cannot assign to expression here. Maybe you meant '=='
instead of '='?
>>> stud_rollno=1
>>> stud_rollno
1
>>> _=1
>>> _
1
>>> __x__=10
>>> __x__
10

5. Identifier should start with alphabet or _ but should not start with
digit

>>> number1=100
number2=200
>>> number1
100
>>> number2
200
>>> 3number=300
SyntaxError: invalid decimal literal
>>> _number=400
>>> _number
400

6. Length of identifier is unlimited

>>> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=10
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
10
>>> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb=100
>>> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
100
>>> a=10
>>> b=20
>>> a+b
30

Naming Conventions

Naming Conventions are nothing but naming rules, this naming convention
makes application easy to understand.

1. pascal case
2. snake case
3. camelcase

Pascal case is used to define class names.


Example: Student, Employee, CurrentAccount
Snake case is used to create variables
Example: rollno, employee_no,account_no,otp_no
Camel case is used to define functions
Example: mean(),mode(),median(),login(),deposit(),createAccount()

Data types and Literals

Data types

Data types are used to reserve memory for data/literals.


Python data types are classified into 2 categories
1. Scalar Data types
2. Collection Data types

Scalar data types are used to allocate memory for one value or single
value.

1. int
2. float
3. complex
4. bool
5. NoneType

Collection data types are used to allocate memory for more than one
value. Collection data types are classified into 3 categories

1. Sequences
a. List
b. Tuple
c. Range
d. Str
e. Bytes
f. Bytearray
2. Sets
a. Set
b. Frozenset
3. Mapping
a. Dict
These 14 data types are called python standard data types

Literals
Literals are values which never changed.
Python literals are classified into two categories
1. Numeric
2. Non-Numeric
Numeric : integer, float, complex
Non Numeric: str, None, bool

Python is pure object oriented programming language. Every data type in


python is a class and data is represented as objects.
What is class?
What is object?
Python is pure object oriented programming language. Every data type in
python is a class and data is represented as objects.

What is class?
A class represents data type.
Class is used to allocate memory for data or object.
Class defines structure of object.
Class is a blue print of object
Class defines properties and behavior of object.
Properties defines the values hold by object
Behavior defines the functionality of object

What is object?
An object is instance of a class
Allocating memory for members/properties of the class is process of
creating object.
Object is an implementation of a class.
Python is a dynamically typed programming language, variables are not
bind with specific data type or variables are not declared with any data
type.

Statically Typed Programming Dynamically typed programming


Language language

int a; a=10
a=10; type(a) 🡪 int
a=1.5; Error a=1.5
type(a) 🡪 float

What is variable?
Variable is an identifier, which is used to identify value/object.
Variable is named memory location.

int data type

int data type/class is used to construct integer objects.


Int data type is used by python virtual machine for allocating memory for
integer value/literal.
Integer is a numeric value without fractional part.

Eg: 1, 560, 5789

>>> a=123
>>> type(a)
<class 'int'>
>>> a
123
>>> b=560
>>> type(b)
<class 'int'>
>>> b
560
In python integer values are represented in 4 formats
1. Decimal
2. Octal
3. Hexadecimal
4. Binary

Number system define set of rules and regulations for representing


numbers in computer science.

Size of int data type is dynamic. The memory is allocated based value
size. Int data type size is unlimited.

>>>
x=9999999999999999999999999999999999999999999999999999999999999
999
>>> x
999999999999999999999999999999999999999999999999999999999999999
9
>>> import sys
>>> sys.getsizeof(x)
56
>>> y=100
>>> sys.getsizeof(y)
28
>>> z=8999999999999999999
>>> sys.getsizeof(z)
36

Decimal Integer
An integer value with base 10 is called decimal integer.
This integer is created using all the digits from 0-9.
This integer is not prefix with 0
This integer is prefix with + or –
Default representation of integer values are in decimal format.

>>> a=0123
SyntaxError: leading zeros in decimal integer literals are not permitted;
use an 0o prefix for octal integers
Decimal Integer
An integer value with base 10 is called decimal integer.
This integer is created using all the digits from 0-9.
This integer is not prefix with 0
This integer is prefix with + or –
Default representation of integer values are in decimal format.

>>> a=0123
SyntaxError: leading zeros in decimal integer literals are not permitted;
use an 0o prefix for octal integers

Integer is allowed only one special character _.


Grouping digits are done using _
_ cannot use as a prefix or suffix

>>> amt1=500
>>> amt1
500
>>> type(amt1)
<class 'int'>
>>> amt2=1_500
>>> amt2
1500
>>> amt3=1_50_000
>>> amt3
150000
>>> a=10_
SyntaxError: invalid decimal literal
>>> b=_10
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
b=_10
NameError: name '_10' is not defined

Octal Integer
An integer value with base 8 is called octal integer.
Octal integer is created using digits range from 0-7.
This integer is prefix with 0o or 0O

Applications of octal integers


1. Assembly Language/Embedded Applications
2. Representing an integer which does not allows digits 8 and 9

Example:
>>> a=0o45
>>> type(a)
<class 'int'>
>>> b=0o89
SyntaxError: invalid digit '8' in octal literal
>>> c=0o278
SyntaxError: invalid digit '8' in octal literal
>>> b=0o35
>>> b
29
>>> c=0o125
>>> c
85

Hexadecimal Integer
An integer value with base 16 is called hexadecimal integer.
This integer is created using 16 digits 0-9,a-f/A-F
This integer is prefix with 0x or 0X.
Larger integer values are represented in hexadecimal format.

Applications of hexadecimal integer


1. Color Values
2. Unicode Values
3. Memory Addresses

>>> n1=0xa
>>> n1
10
>>> n2=0xb
>>> n2
11
>>> n3=0xf
>>> n3
15
>>> n4=0xg
SyntaxError: invalid hexadecimal literal
>>> n5=0xabc
>>> n5
2748
>>> n6=0xff
>>> n6
255
>>> n6=0xbad
>>> n6
2989
Binary Integer
An integer value with base 2 is called binary integer.
Binary integer is created using two digits 0 and 1
Binary integer is prefix with 0b or 0B

Applications of binary integer


1. Internal data representation
2. Machine language
3. Image Processing
4. Audio or video processing

>>> n1=0b10
>>> n1
2
>>> n2=0b1010
>>> n2
10
>>> n3=0b1012
SyntaxError: invalid digit '2' in binary literal
Binary Integer
An integer value with base 2 is called binary integer.
Binary integer is created using two digits 0 and 1
Binary integer is prefix with 0b or 0B

Applications of binary integer


1. Internal data representation
2. Machine language
3. Image Processing
4. Audio or video processing

>>> n1=0b10
>>> n1
2
>>> n2=0b1010
>>> n2
10
>>> n3=0b1012
SyntaxError: invalid digit '2' in binary literal

>>> rollno=125
>>> rollno
125
>>> accountNo=123456999
>>> accountNo
123456999
>>> color=0xff0000
>>> color
16711680
>>> color=0xff
>>> color
255

All scalar data types are immutable.


After creating object, value cannot modify or after creating object
changes cannot be done.

How to find id or address of object?


Every object in memory is identified with unique number called id or
address. This id or address is generated by PVM.
Address of object is find using id() function.

Example:
>>> a=60
>>> a
60
>>> id(a)
140716079894808
>>> b=90
>>> id(b)
140716079895768
>>> a=80
>>> a
80
>>> id(a)
140716079895448

Immutable objects are sharable.

Example:
>>> x=10
>>> y=10
>>> z=10
>>> x
10
>>> y
10
>>> z
10
>>> id(x)
140716079893208
>>> id(y)
140716079893208
>>> id(z)
140716079893208
>>> p=5+5
>>> p
10
>>> id(p)
140716079893208

Base conversion functions


Python provides 3 base conversion functions
1. Oct() 🡪 This return octal representation of integer value
2. Hex() 🡪 This return hexadecimal representation of integer value
3. Bin() 🡪 This return binary representation of integer value

Example:
>>> a=12
>>> a
12
>>> bin(a)
'0b1100'
>>> hex(a)
'0xc'
>>> oct(a)
'0o14'
>>> b=0xc
>>> b
12
>>> bin(b)
'0b1100'
>>> oct(b)
'0o14'
>>> bin(4000)
'0b111110100000'
c=0o12
>>> c
10
>>> oct(c)
'0o12'
>>> hex(c)
'0xa'
>>> bin(c)
'0b1010'

float data type


float literal or value is represented in python using float data type or
class.
Float value is a numeric value with fractional part.
This size of float data type is 8bytes.

Finding information about float data type

>>> import sys


>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024,
max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021,
min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16,
radix=2, rounds=1)
Example:
>>> a=1.5
>>> a
1.5
>>> type(a)
<class 'float'>
>>> a=1.5
>>> a
1.5
>>> type(a)
<class 'float'>
>>> b=1.123123123123123123123123123123123
>>> b
1.1231231231231231
>>> c=1.123456789123456789123456789
>>> c
1.1234567891234568

Float value is represented in two formats or notations


1. Fixed notation or fixed format
2. Scientific notation/exponent notation or scientific format

>>> f1=12.456
>>> f1
12.456
>>> f2=12456e-3
>>> f2
12.456
>>> f3=1.234e2
>>> f3
123.4

In scientific notation one special character used in float value called “e”,
the value of “e” is 10.
>>> a=1.7976931348623157e+308
>>> a
1.7976931348623157e+308
>>> b=1.7976931348623157e+309
>>> b
inf
>>> c=0b1010.10
SyntaxError: incomplete input
>>> d=0xab.a
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
d=0xab.a
AttributeError: 'int' object has no attribute 'a'

Complex data type

Complex data type or class is used to represent complex number/literal.


Complex number is having two values
1. Real
2. Imag

>>> c1=1+2j
>>> c1
(1+2j)
>>> type(c1)
<class 'complex'>
>>> c1.real
1.0
>>> c1.imag
2.0
>>> c2=2j
>>> c2
2j
>>> type(c2)
<class 'complex'>
>>> c2.real
0.0
>>> c2.imag
2.0
>>> c2.real=1.0
Traceback (most recent call last):
File "<pyshell#78>", line 1, in <module>
c2.real=1.0
AttributeError: readonly attribute

bool data type


This data type is used to represent Boolean values.
In python Boolean values are represented using two keywords
1. True
2. False

Example:
>>> a=True
>>> a
True
>>> type(a)
<class 'bool'>
>>> b=False
>>> b
False
>>> type(b)
<class 'bool'>
>>> c=1
>>> c
1
>>> type(c)
<class 'int'>
>>> d=10>2
>>> d
True

NoneType
NoneType represent None value.
In python None is represented as missing value or no value.

>>> rollno=1
>>> name=None
>>> fee=4000.0
>>> feePaid=True
>>> rollno
1
>>> name
>>> fee
4000.0
>>> feePaid
True
>>> a=None
>>> a
>>> type(a)
<class 'NoneType'>

string
String

String is non numeric data type.


String is a collection of characters. These characters can be alphabets,
digits or special characters.
A string which consists of only alphabets is called alphabetic string.
A string which consists of alphabets or digits is called alphanumeric
string.
String is a collection type or sequence type.
String is an immutable sequence data type.

In python string is represented,


1. Within single quotes
2. Within double quotes
3. Within triple single quotes or double quotes

Within single quotes, python programmers represent single line string.


Within single quotes, we can insert double quotes.

Example:
>>> s1='python'
>>> s1
'python'
>>> s2='python 3.12'
s2
>>> 'python 3.12'
>>> s3='45'
>>> n1=45
>>> n1+10
55
>>> s3+10
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
s3+10
TypeError: can only concatenate str (not "int") to str
>>> s4='python is a
SyntaxError: incomplete input
>>> s4='python is "high" programming language'
>>> print(s4)
python is "high" programming language
>>> s5='python is a 'high level' programming language'
SyntaxError: invalid syntax

Within double quotes we can represent single line string

>>> str1="python"
>>> print(str1)
python
>>> str2="python 3.12"
>>> print(str2)
python 3.12
>>> str3="45"
>>> print(str3)
45
>>> str4="python is high level
SyntaxError: incomplete input

Within double quotes we can insert single quotes

>>> str5="python is 'high level' programming language"


>>> print(str5)
python is 'high level' programming language

Within triple single quotes or double quotes we can represent multiline


string.

>>> rollno=101
>>> name="nk"
>>> course="FSP"
>>> description=''' Full Stack Python consists of 5 Modules
Module1: Python
Module2: Database
Module3: UI
Module4: Backend
Module5: Tools'''
>>> print(rollno)
101
>>> print(name)
nk
>>> print(course)
FSP
>>> print(description)
Full Stack Python consists of 5 Modules
Module1: Python
Module2: Database
Module3: UI
Module4: Backend
Module5: Tools
>>> str1=""" Python is
... high level, multiparadigm
... programming language"""
>>> print(str1)
Python is
high level, multiparadigm
programming language

Comments in Python

In python comments are created using # (pound sign)


It is used to create single line comment.

test1.py
# This is my first program in python

print("Hello") # this statement is used to print a message Hello

Output:
Hello

test2.py
a=''' This is my first python program '''

print("Hello")
print(a)
Output:
Hello
This is my first python program

What is indent?
Space given at the beginning of the statement is called indent.
Indent is used to create block.

Every program required 3 things,


1. Output
2. Input
3. Process

print()
print() is a predefined function in python.
print() is a standard output function, this function is used to print data or
information on console/monitor.

Print function required input to print data or information.


Print function is having 3 inputs
1. data/values
2. sep
3. end
print()
print() is a predefined function in python.
print() is a standard output function, this function is used to print data or
information on console/monitor.

Print function required input to print data or information.


Print function is having 3 inputs
1. data/values
2. sep
3. end
if no input is given to print function, it insert blank line

Example:
print()
print()
print()
print()

Output:
4 blank lines

Example:
print(10)
print()
print(20)
print()
print(1.5)
print()
print("Hello")

Output:
10

20

1.5
Hello

Example:
print(10,20,30,40,50)
print(1,"nk","python",4000.0)
print(10,20,30,40,50,sep="$")
print(10,20,30,40,50,sep=",")
print(10,20,30,40,50)
print(1,2,3,4,5,sep="nit")

Output:
10 20 30 40 50
1 nk python 4000.0
10$20$30$40$50
10,20,30,40,50
10 20 30 40 50
1nit2nit3nit4nit5

Example:
rollno=101
name="Nk"
course="Python"
fee=5000.0
print("rollno",rollno)
print("name",name)
print("course",course)
print("fee",fee)

Output:
rollno 101
name Nk
course Python
fee 5000.0

Example:
a=10
b=20
c=30
print(a,b,c)
print("a","b","c")

Output:
10 20 30
abc

Default end value is \n 🡪 newline

Example:
print(10,20,30,end=';')
print(40,50,60)
print(70,80)

Output:
10 20 30;40 50 60
70 80

Escape Sequences
Escape sequences are special string
These are called backslash character literals

\n New line
\t Horizontal tab space
\v Vertical tab space
\\ \
\” “
\’ ‘
\b backspace
Example:
print('\\')
print("\"")
print('\'')
print("\n")
print("\t")

Output:
\
"
'

Example:
a=10
b=20
c=30
print(a,b,c,sep="\n")
x=100
y=200
z=300
print(x,y,z,sep="\t")

Output:
10
20
30
100 200 300

Example:
a=10
b=20
print("sum of ",a,b,"is",a+b)

Output:
sum of 10 20 is 30
format string
A string prefix with f or F is called format string.
This string contains replacement fields, which are replaced with values
(OR) format string allows to insert values within string.
Format string is used to format output.

Inside format string replacement fields are represented using curly braces
{}.

Example:
a=10
b=20
print(f'sum of {a} and {b} is {a+b}')

Output:
sum of 10 and 20 is 30

Example:
a=10
print(f'{a:d},{a:o},{a:x},{a:b}')
b=1.5
print(f'{b}')
print(f'{b:f}')
print(f'{b:.2f}')
print(f'{b:.30f}')
c=1.5e-2
print(f'{c:e}')
print(f'{c:.2e}')

Output:
10,12,a,1010
1.5
1.500000
1.50
1.500000000000000000000000000000
1.500000e-02
1.50e-02
format function of string data type
before 3.8 formatting of output is done using format function of string
data type.

Example:
a=10
b=20
print("sum of {} and {} is {}".format(a,b,a+b))
print("{:d},{:o},{:x},{:b}".format(a,a,a,a))
base=1.5
height=2.5
print("Area of triangle with base={} and height={} is
{}".format(base,height,0.5*base*height))
print("Area of triangle with base={:.2f} and height={:.2f} is
{:.2f}".format(base,height,0.5*base*height))

Output:
sum of 10 and 20 is 30
10,12,a,1010
Area of triangle with base=1.5 and height=2.5 is 1.875
Area of triangle with base=1.50 and height=2.50 is 1.88

Input() function
input() is standard input function, this function is used to input/read data
from keyboard.
Input() is function is used to input/read string value.
Input() function allows to input/read one value.

Syntax:
variable=input([prompt])

Example:
a=input("Enter First Value ")
b=input("Enter Second Value ")
c=input("Enter value of c ")

print(a,b,c)
print(type(a),type(b),type(c))

Output:
Enter First Value 100
Enter Second Value 200
Enter value of c 300
100 200 300
<class 'str'> <class 'str'> <class 'str'>
Example:
# Write a program to print sum of integers
# input two integers from keyboard

n1=input("Enter First Value ")


n2=input("Enter Second Value ")
n3=n1+n2
print(f'sum of {n1} and {n2} is {n3}')

Output:
Enter First Value 10
Enter Second Value 20
sum of 10 and 20 is 1020

How to see content of module/library?


>>> import calendar
>>> dir(calendar)
['APRIL', 'AUGUST', 'Calendar', 'DECEMBER', 'Day', 'EPOCH', 'FEBRUARY',
'FRIDAY', 'HTMLCalendar', 'IllegalMonthError', 'IllegalWeekdayError',
'IntEnum', 'JANUARY', 'JULY', 'JUNE', 'LocaleHTMLCalendar',
'LocaleTextCalendar', 'MARCH', 'MAY', 'MONDAY', 'Month', 'NOVEMBER',
'OCTOBER', 'SATURDAY', 'SEPTEMBER', 'SUNDAY', 'THURSDAY', 'TUESDAY',
'TextCalendar',

Type Conversion Function or Type Casting


Type conversion is a process of converting one type of object to another
type.

1. Int()
2. Float()
3. Complex()
4. Bool()
5. Str()

All these are in-built functions and available in default module imported
by any python program called __builtins__

int() function
This function is used to create integer object (OR) this function performs
the following conversions.
1. Int to int
2. Float to int
3. String to int
4. Bool to int

Syntax1: int(value)
Syntax2: int(value,base=10)

Syntax-1 is used to convert float,int,bool to integer object


Syntax-2 is used to convert string to integer object
Example:
# Write a program to print sum of integers
# input two integers from keyboard
n1=input("Enter First Value ")
n2=input("Enter Second Value ")
n3=int(n1)+int(n2)
print(f'sum of {n1} and {n2} is {n3}')

Output:
Enter First Value 100
Enter Second Value 200
sum of 100 and 200 is 300

Example:
>>> int(10)
10
>>> int(1.5)
1
>>> int(True)
1
>>> int(False)
0
>>> int(1+2j)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
int(1+2j)
TypeError: int() argument must be a string, a bytes-like object or a real
number, not 'complex'
>>> int("65")
65
>>> int("1.25")
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
int("1.25")
ValueError: invalid literal for int() with base 10: '1.25'
>>> int("a")
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
int("a")
ValueError: invalid literal for int() with base 10: 'a'
>>> int("a",base=16)
10
>>> int("ff",base=16)
255
>>> int("ffff",base=16)
65535
>>> int("1010",base=2)
10
>>> int("1010")
1010

float() function
This function is used to create float object or to perform the following
conversions
1. float to float
2. int to float
3. string to float
4. bool to float

Syntax: float(value)
Example
>>> float(1.5)
1.5
>>> float(1)
1.0
>>> float(True)
1.0
>>> float(False)
0.0
>>> float("1.5")
1.5
>>> float("15e-1")
1.5
>>> float("15")
15.0
>>> float("abc")
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
float("abc")
ValueError: could not convert string to float: 'abc'

Example:
# Write a program to swap/interchange two float values input from stdin

a=float(input("Enter value of a "))


b=float(input("Enter value of b "))
print(f'before swaping a={a} and b={b}')
c=a
a=b
b=c
print(f'after swaping a={a} and b={b}')
a,b=b,a
print(f'after swaping a={a} and b={b}')
a=a+b
b=a-b
a=a-b
print(f'after swaping a={a} and b={b}')

Output:
Enter value of a 1.5
Enter value of b 2.5
before swaping a=1.5 and b=2.5
after swaping a=2.5 and b=1.5
after swaping a=1.5 and b=2.5
after swaping a=2.5 and b=1.5

complex()
This function is used to create complex number (OR) perform the
following conversions

1. complex to complex
2. int to complex
3. float to complex
4. string to complex
5. bool to complex
complex()
This function is used to create complex number (OR) perform the
following conversions

1. complex to complex
2. int to complex
3. float to complex
4. string to complex
5. bool to complex

Example:
>>> comp1=complex(1+2j)
>>> print(comp1)
(1+2j)
>>> print(type(comp1))
<class 'complex'>
>>> comp2=complex("1+2j")
>>> print(comp2)
(1+2j)
>>> print(type(comp2))
<class 'complex'>
>>> comp3=complex("2j")
print(comp3)
2j
>>> print(type(comp3))
<class 'complex'>
>>> comp4=complex("4")
>>> print(comp4)
(4+0j)
>>> comp5=complex(1)
>>> print(comp5)
(1+0j)
>>> comp6=complex(2j)
>>> print(comp6)
2j
>>> print(comp6.real,comp6.imag)
0.0 2.0
>>> comp7=complex(True)
>>> print(comp7,type(comp7))
(1+0j) <class 'complex'>
>>> comp8=complex(False)
>>> print(comp8,type(comp8))
0j <class 'complex'>
>>> print(comp8.real,comp8.imag)
0.0 0.0

Example:
# Write a program for adding two complex numbers

comp1=complex(input("input complex number1 "))


comp2=complex(input("input complex number2 "))
comp3=comp1+comp2
print(f'sum of {comp1} and {comp2} is {comp3}')

Output:
input complex number1 1+2j
input complex number2 1+3j
sum of (1+2j) and (1+3j) is (2+5j)

bool() function
This function returns Boolean value (OR) this function performs the
following conversions.

1. Bool to bool
2. Int to bool
3. Float to bool
4. Complex to bool
5. String to bool

Example:
>>> b1=bool(True)
>>> print(b1)
True
>>> b2=bool(False)
>>> print(b2)
False
>>> b3=bool(0)
print(b3)
>>> False
>>> b4=bool(1)
>>> print(b4)
True
>>> b5=bool(100)
>>> print(b5)
True
>>> b6=bool(-5)
>>> print(b6)
True
>>> b7=bool(0.0)
>>> print(b7)
False
>>> b8=bool(0.5)
>>> print(b8)
True
>>> b9=bool(0+0j)
>>> print(b9)
False
>>> b10=bool(1+0j)
>>> print(b10)
True
>>> b11=bool("A")
>>> print(b11)
True
>>> b12=bool("NARESH")
>>> print(b12)
True
>>> b13=bool("False")
>>> print(b13)
True
>>> b14=bool("True")
>>> print(b14)
True

ord(),char()

ord(char) 🡪 This function return ASCII value of input character


chr(ascii) 🡪 This function return Character value of input ASCII value
Example:
>>> ord('A')
65
>>> ord('B')
66
>>> ord('C')
67
>>> ord('Z')
90
>>> ord('a')
97
>>> ord('b')
98
>>> ord('c')
99
>>> ord('z')
122
>>> chr(65)
'A'
>>> chr(66)
'B'
>>> chr(90)
'Z'
>>> chr(97)
'a'
>>> chr(98)
'b'
>>> chr(122)
'z'

Example:
# Write a program to convert given character from uppercase to
lowercase

char='B'
print(char)
value=ord(char) # 66
value=value+32
char1=chr(value)
print(char1)
value=ord(char1)
value=value-32
char2=chr(value)
print(char2)

Output:
B
b
B
B

str() function
This function returns string object (OR) this function is used to convert
other types into string type.

Syntax: str(value)

>>> s1=str()
print(s1)

>>> s2=str(25)
>>> print(s2)
25
>>> s3=str(1.5)
>>> print(s3)
1.5
>>> s2+s3
'251.5'
>>> print(type(s2),type(s3))
<class 'str'> <class 'str'>
>>> s4=str(1+2j)
>>> print(s4)
(1+2j)
>>> print(type(s4))
<class 'str'>
>>> s5=str(True)
>>> print(s5)
True
>>> s6=str(False)
>>> print(s6)
False
>>> print(type(s5),type(s6))
<class 'str'> <class 'str'>

Operators

What is operator?
Operator is a special symbol, which is used to perform operations.
Based on the numbers of operand used to perform operation, the
operators are classified into 3 categories
1. Unary Operator
2. Binary Operator
3. Ternary Operator

Types of operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Membership Operator
6. Identity Operator
7. Conditional Operator
8. Bitwise Operators
9. Walrus Operator (Python 3.8)

Arithmetic Operators

These operators are used to perform arithmetic operations.


All arithmetic operators are binary operators.

Operator Description
+ Adding or Concatenation
- Subtraction
* Multiplication or Repeat
/ Float Division
// Floor Division
% Modulo
** Exponent or Power

+ operator is used to perform two operations


1. Adding
2. Concatenating
It performs addition, if two operands are numbers
It performs concatenation, if two operands sequences (list, tuple,
string ,…)

Example:
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)
10 20 30
>>> x=1.5
>>> y=1.2
>>> z=x+y
>>> print(x,y,z)
1.5 1.2 2.7
>>> b1=True
>>> b2=False
>>> b3=b1+b2
>>> print(b1,b2,b3)
True False 1
>>> b4=True+15
>>> print(b4)
16
>>> c1=1+2j
>>> c2=1+1j
>>> c3=c1+c2
>>> print(c1,c2,c3)
(1+2j) (1+1j) (2+3j)
>>> s1="Python"
>>> s2="3.12"
>>> s3=s1+s2
>>> print(s1,s2,s3)
Python 3.12 Python3.12
>>> s4="10"
>>> s5="15"
>>> s6=s4+s5
>>> print(s4,s5,s6)
10 15 1015
>>> s7="python"
>>> s8=3.12
>>> print(s7+s8)
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
print(s7+s8)
TypeError: can only concatenate str (not "float") to str

eval() function
it is a predefined function of python. This function evaluate string
representation of expression and return value.

eval(expression)

>>> a=eval("1.5")
>>> print(a,type(a))
1.5 <class 'float'>
>>> b=eval("25")
>>> print(b,type(b))
25 <class 'int'>
>>> c=eval("1+2j")
>>> print(c,type(c))
(1+2j) <class 'complex'>
>>> d=eval("10+20+30")
>>> print(d)
60

Example:
# write a program to add two numbers

a=eval(input("Enter first number "))


b=eval(input("Enter second number "))
c=a+b
print(f'sum of {a} and {b} is {c}')

Output
Enter first number 10
Enter second number 20
sum of 10 and 20 is 30

Enter first number 1.5


Enter second number 1.2
sum of 1.5 and 1.2 is 2.7

Enter first number 1+2j


Enter second number 1+1j
sum of (1+2j) and (1+1j) is (2+3j)

- Operator (arithmetic subtract operator)

This operator is used for subtraction of two numbers.

>>> a=10
>>> b=1.5
>>> c=a-b
>>> print(a,b,c)
10 1.5 8.5
>>> c1=1+2j
>>> c2=1j
>>> c3=c1-c2
>>> print(c1,c2,c3)
(1+2j) 1j (1+1j)
>>> c3=c1-2
>>> print(c3)
(-1+2j)
complex()
This function is used to create complex number (OR) perform the
following conversions

1. complex to complex
2. int to complex
3. float to complex
4. string to complex
5. bool to complex

Example:
>>> comp1=complex(1+2j)
>>> print(comp1)
(1+2j)
>>> print(type(comp1))
<class 'complex'>
>>> comp2=complex("1+2j")
>>> print(comp2)
(1+2j)
>>> print(type(comp2))
<class 'complex'>
>>> comp3=complex("2j")
print(comp3)
2j
>>> print(type(comp3))
<class 'complex'>
>>> comp4=complex("4")
>>> print(comp4)
(4+0j)
>>> comp5=complex(1)
>>> print(comp5)
(1+0j)
>>> comp6=complex(2j)
>>> print(comp6)
2j
>>> print(comp6.real,comp6.imag)
0.0 2.0
>>> comp7=complex(True)
>>> print(comp7,type(comp7))
(1+0j) <class 'complex'>
>>> comp8=complex(False)
>>> print(comp8,type(comp8))
0j <class 'complex'>
>>> print(comp8.real,comp8.imag)
0.0 0.0

Example:
# Write a program for adding two complex numbers

comp1=complex(input("input complex number1 "))


comp2=complex(input("input complex number2 "))
comp3=comp1+comp2
print(f'sum of {comp1} and {comp2} is {comp3}')

Output:
input complex number1 1+2j
input complex number2 1+3j
sum of (1+2j) and (1+3j) is (2+5j)

bool() function
This function returns Boolean value (OR) this function performs the
following conversions.

1. Bool to bool
2. Int to bool
3. Float to bool
4. Complex to bool
5. String to bool

Example:
>>> b1=bool(True)
>>> print(b1)
True
>>> b2=bool(False)
>>> print(b2)
False
>>> b3=bool(0)
print(b3)
>>> False
>>> b4=bool(1)
>>> print(b4)
True
>>> b5=bool(100)
>>> print(b5)
True
>>> b6=bool(-5)
>>> print(b6)
True
>>> b7=bool(0.0)
>>> print(b7)
False
>>> b8=bool(0.5)
>>> print(b8)
True
>>> b9=bool(0+0j)
>>> print(b9)
False
>>> b10=bool(1+0j)
>>> print(b10)
True
>>> b11=bool("A")
>>> print(b11)
True
>>> b12=bool("NK")
>>> print(b12)
True
>>> b13=bool("False")
>>> print(b13)
True
>>> b14=bool("True")
>>> print(b14)
True

ord(),char()

ord(char) à This function return ASCII value of input character


chr(ascii) à This function return Character value of input ASCII value
Example:
>>> ord('A')
65
>>> ord('B')
66
>>> ord('C')
67
>>> ord('Z')
90
>>> ord('a')
97
>>> ord('b')
98
>>> ord('c')
99
>>> ord('z')
122
>>> chr(65)
'A'
>>> chr(66)
'B'
>>> chr(90)
'Z'
>>> chr(97)
'a'
>>> chr(98)
'b'
>>> chr(122)
'z'

Example:
# Write a program to convert given character from uppercase to
lowercase

char='B'
print(char)
value=ord(char) # 66
value=value+32
char1=chr(value)
print(char1)
value=ord(char1)
value=value-32
char2=chr(value)
print(char2)

Output:
B
b
B
B

str() function
This function returns string object (OR) this function is used to convert
other types into string type.

Syntax: str(value)

>>> s1=str()
print(s1)

>>> s2=str(25)
>>> print(s2)
25
>>> s3=str(1.5)
>>> print(s3)
1.5
>>> s2+s3
'251.5'
>>> print(type(s2),type(s3))
<class 'str'> <class 'str'>
>>> s4=str(1+2j)
>>> print(s4)
(1+2j)
>>> print(type(s4))
<class 'str'>
>>> s5=str(True)
>>> print(s5)
True
>>> s6=str(False)
>>> print(s6)
False
>>> print(type(s5),type(s6))
<class 'str'> <class 'str'>

Operators

What is operator?
Operator is a special symbol, which is used to perform operations.
Based on the numbers of operand used to perform operation, the
operators are classified into 3 categories
1. Unary Operator
2. Binary Operator
3. Ternary Operator

Types of operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Membership Operator
6. Identity Operator
7. Conditional Operator
8. Bitwise Operators
9. Walrus Operator (Python 3.8)
Arithmetic Operators

These operators are used to perform arithmetic operations.


All arithmetic operators are binary operators.

Operator Description
+ Adding or Concatenation
- Subtraction
* Multiplication or Repeat
/ Float Division
// Floor Division
% Modulo
** Exponent or Power

+ operator is used to perform two operations


1. Adding
2. Concatenating
It performs addition, if two operands are numbers
It performs concatenation, if two operands sequences (list, tuple,
string ,…)

Example:
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)
10 20 30
>>> x=1.5
>>> y=1.2
>>> z=x+y
>>> print(x,y,z)
1.5 1.2 2.7
>>> b1=True
>>> b2=False
>>> b3=b1+b2
>>> print(b1,b2,b3)
True False 1
>>> b4=True+15
>>> print(b4)
16
>>> c1=1+2j
>>> c2=1+1j
>>> c3=c1+c2
>>> print(c1,c2,c3)
(1+2j) (1+1j) (2+3j)
>>> s1="Python"
>>> s2="3.12"
>>> s3=s1+s2
>>> print(s1,s2,s3)
Python 3.12 Python3.12
>>> s4="10"
>>> s5="15"
>>> s6=s4+s5
>>> print(s4,s5,s6)
10 15 1015
>>> s7="python"
>>> s8=3.12
>>> print(s7+s8)
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
print(s7+s8)
TypeError: can only concatenate str (not "float") to str

eval() function
it is a predefined function of python. This function evaluate string
representation of expression and return value.

eval(expression)

>>> a=eval("1.5")
>>> print(a,type(a))
1.5 <class 'float'>
>>> b=eval("25")
>>> print(b,type(b))
25 <class 'int'>
>>> c=eval("1+2j")
>>> print(c,type(c))
(1+2j) <class 'complex'>
>>> d=eval("10+20+30")
>>> print(d)
60

Example:
# write a program to add two numbers

a=eval(input("Enter first number "))


b=eval(input("Enter second number "))
c=a+b
print(f'sum of {a} and {b} is {c}')
Output
Enter first number 10
Enter second number 20
sum of 10 and 20 is 30

Enter first number 1.5


Enter second number 1.2
sum of 1.5 and 1.2 is 2.7

Enter first number 1+2j


Enter second number 1+1j
sum of (1+2j) and (1+1j) is (2+3j)

- Operator (arithmetic subtract operator)

This operator is used for subtraction of two numbers.

>>> a=10
>>> b=1.5
>>> c=a-b
>>> print(a,b,c)
10 1.5 8.5
>>> c1=1+2j
>>> c2=1j
>>> c3=c1-c2
>>> print(c1,c2,c3)
(1+2j) 1j (1+1j)
>>> c3=c1-2
>>> print(c3)
(-1+2j)
“*” This operator is used to perform two operations
1. Multiplication
2. Repeating Sequence number of times

Example:

>>> n1=5
>>> n2=2
>>> n3=n1*n2
>>> print(n1,n2,n3)
5 2 10
>>> f1=1.5
>>> f2=2.5
>>> f3=f1*f2
>>> print(f1,f2,f3)
1.5 2.5 3.75
>>> r1=5*1.5
>>> print(r1)
7.5
>>> r2=5*True
>>> print(r2)
5

Example:

>>> list1=[0]
>>> list1=list1*10
>>> print(list1)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> s1="abc"
>>> s2=5*s1
>>> print(s2)
abcabcabcabcabc
>>> print("-"*30)
------------------------------
>>> print(30*"*")
******************************
>>> list2=[5]*20
>>> print(list2)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

Example:
# Write a program to find area of rectangle
# area=l*b

l=float(input("Enter value of l"))


b=float(input("Enter value of b"))
area=l*b
print(f'area of rectangle with l={l:.2f} and b={b:.2f} is {area:.2f}')

Output:
Enter value of l1.2
Enter value of b1.5
area of rectangle with l=1.20 and b=1.50 is 1.80

/ division operator or float division operator

This operator divide two numbers and return value as float type.

Example:
q1=5/2
print(q1)
2.5
>>> q2=4/2
>>> print(q2)
2.0
>>> q3=4/2.0
>>> print(q3)
2.0
>>> q4=4/0
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
q4=4/0
ZeroDivisionError: division by zero
>>> q5=0/5
>>> print(q5)
0.0
Example:
# Write a program to find simple interest
# si=ptr/100

p=float(input("Amount "))
t=int(input("Time "))
r=float(input("Rate "))
si=p*t*r/100
print(f'''Amount {p}
Time {t}
Rate {r}
Simple Interest {si:.2f}''')

Output:
Amount 5000
Time 12
Rate 1.5
Amount 5000.0
Time 12
Rate 1.5
Simple Interest 900.00

Example:
# Write a program to input rollno,name 3 subject marks
# calculate total and avg marks

rollno=int(input("Rollno "))
name=input("Name ")
sub1=int(input("Subject1 Marks "))
sub2=int(input("Subject2 Marks "))
sub3=int(input("Subject3 Marks "))
total=sub1+sub2+sub3
avg=total/3
print(f'''
Rollno {rollno}\tName {name}
Subject1 {sub1}\tSubject2 {sub2}\tSubject3 {sub3}
Total {total}\tAvg {avg:.2f}''')

Output:
Rollno 1
Name nk
Subject1 Marks 50
Subject2 Marks 70
Subject3 Marks 90

Rollno 1 Name nk
Subject1 50 Subject270 Subject390
Total 210 Avg 70.00

https://www.hackerrank.com/challenges/python-arithmetic-
operators/problem?isFullScreen=true

a=int(input())
b=int(input())
print(a+b)
print(a-b)
print(a*b)

// floor division operator or integer division

>>> r1=5//2
>>> print(r1)
2
>>> r2=5/2
>>> print(r2)
2.5
>>> r3=5//2.0
>>> print(r3)
2.0
>>> r4=5/2.0
>>> print(r4)
2.5

Example:
# Write a program to delete last digit of number

num=456
print(num)
num=num//10
print(num)

Output:
456
45

% modulo operator
This operator divides two numbers and return remainder

>>> rem1=5%3
>>> print(rem1)
2
>>> rem2=4%2
>>> print(rem2)
0

Example:
# Write a program to read last digit of number

num=456
lastdigit=num%10
print(num)
print(lastdigit)

Output:
456
6

**power of operator or exponent operator

>>> res1=5**2
>>> print(res1)
25
>>> res2=5**0
>>> print(res2)
1
>>> res3=10**-1
>>> print(res3)
0.1

Precedence of operators

The following table summarizes the operator precedence in Python, from


highest precedence (most binding) to lowest precedence (least binding).
Operators in the same box have the same precedence. Unless the syntax
is explicitly given, operators are binary. Operators in the same box group
left to right (except for exponentiation and conditional expressions,
which group from right to left).

Operator Description
(expressions...),
Binding or parenthesized expression, list
[expressions...], {key: value...
display, dictionary display, set display
}, {expressions...}
x[index], x[index:index], x(ar Subscription, slicing, call, attribute
guments...), x.attribute reference
await x Await expression
** Exponentiation 5
+x, -x, ~x Positive, negative, bitwise NOT
Multiplication, matrix multiplication,
*, @, /, //, %
division, floor division, remainder
+, - Addition and subtraction
<<, >> Shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, Comparisons, including membership tests
>=, !=, == and identity tests
not x Boolean NOT
Operator Description
and Boolean AND
or Boolean OR
if – else Conditional expression
lambda Lambda expression
:= Assignment expression
Relational Operators
Relational operators are used for comparing values. An expression
created using relational operators is called Boolean expression. Boolean
expression always returns Boolean value (True/False)

Operators Description
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
== Equal
!= Not equal

These operators are used to compare object values or state.

Example:
>>> 10>5
True
>>> 20>30
False
>>> 20<30
True
>>>10<5
False
>>>10>=10
True
>>>10>=5
True
>>>10<=10
True
>>> 5<=10
True
>>> 20<=10
False
>>> 10==10
True
>>> 10==20
False
>>> 10!=10
False
>>> 10!=20
True
>>> "A">"B"
False
>>> "B">"A"
True
>>> "a">"A"
True
>>> a=5
>>> 1<=a<=10
True
>>> a=20
>>> 1<=a<=10
False
>>> 5>=1<=10
True

Conditional Operator
Conditional operator is a ternary operator, this operator required 3
operands. Condition operator is used for creating conditional expression.
Conditional operators allow evaluating expression based on
condition/test.

Syntax:
<variable-name>=opr1 if opr2 else opr3

Example:
# Write a program to find a person is elg to vote or not
name=input("Enter Name ")
age=int(input("Enter Age "))
result=f'{name} is elg to vote ' if age>=18 else f'{name} is not elg vote'
print(result)

Output:
Enter Name suresh
Enter Age 30
suresh is elg to vote

Enter Name kishore


Enter Age 14
kishore is not elg vote

Example:
# Write a program to find input number is even or odd

num=int(input("Enter any number "))


rem=num%2
a=f'{num} is even' if rem==0 else f'{num} is odd'
print(a)

Output:
Enter any number 4
4 is even

Enter any number 9


9 is odd

Example:
# Write a program to find max of two numbers

num1=int(input("Enter First Number "))


num2=int(input("Enter Second Number "))
res=f'{num1} is max' if num1>num2 else f'{num2} is max'
print(res)

Output:
Enter First Number 10
Enter Second Number 5
10 is max

Enter First Number 5


Enter Second Number 20
20 is max

Enter First Number 10


Enter Second Number 10
10 is max

Logical Operators
Logical operators are used to combine two or more conditions or boolean
expressions. In python logical operators are represented using 3
keywords.

1. and 🡪 Binary Operator


2. or 🡪 Binary Operator
3. not 🡪 Unary Operator

and operator
truth table of and operator
Opr1 Opr2 Opr1 and Opr2
True False False
False True False
False False False
True True True

Example:
>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
False
>>> 10>5 and 10>20
False
>>> 10>20 and 10>5
False

Example:
# Write a program to read name and 2 subject marks
# calculate total,avg and result

name=input("Enter Name ")


sub1=int(input("Enter Subject1 Marks "))
sub2=int(input("Enter Subject2 Marks "))
total=sub1+sub2
avg=total/2
result="pass" if sub1>=40 and sub2>=40 else "fail"
print(f'''Name {name}
Subject1 {sub1}
Subject2 {sub2}
Total {total}
Avg {avg:.2f}
Result {result}''')

Output:
Enter Name nk
Enter Subject1 Marks 70
Enter Subject2 Marks 80
Name nk
Subject1 70
Subject2 80
Total 150
Avg 75.00
Result pass

Enter Name suresh


Enter Subject1 Marks 30
Enter Subject2 Marks 99
Name suresh
Subject1 30
Subject2 99
Total 129
Avg 64.50
Result fail

Example:
>>> 100 and 200
200
>>> 0 and 100
0
>>>100 and 200 and 300
300
>>>100 and 0 and 300
0
>>> "java" and "python"
'python'
>>> "A" and "B"
'B'
>>> bool(100)
True
>>> bool(0)
False

Example:
# Login Application

user=input("UserName :") # nit


pwd=input("Password :") # nit123

print("Welcome") if user=="nit" and pwd=="nit123" else print("invalid


username or password")

Output:
UserName :nk
Password :nit123
invalid username or password

UserName :nit
Password :nk
invalid username or password
>>>
UserName :nit
Password :nit123
Welcome

or operator
truth table
Opr1 Opr2 Opr1 or Opr2
True True True
True False True
False True True
False False False

If any operand is True, the complete expression return True.


If opr1 is True, PVM return result of opr1 without evaluating opr2
If opr1 is False, PVM evaluates opr2 and return result of opr2

True or False
True
>>> False or True
True
>>> False or False
False
>>> 100 or 200
100
>>> 100 or 200 or 300
100

Precedence of logical operator


1. not
2. and
3. or

Example:
>>> 100 or 200
100
>>> 100 or 200 or 300
100
>>> 100 or 200 and 300
100
>>> 200 and 300 or 100
300
>>> 0 and 100 or 200
200

t.me/fspy5
Using multiple conditional operator
Multiple conditional operators are used to check more than one
condition.

Example:
# Write a program to find input character is vowel or not

ch=input("Enter Single Character ")


print("Vowel") if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u' else
print("not vowel")

Output:
Enter Single Character i
Vowel

Enter Single Character x


not vowel

Example:
# Write a program to find input number is +ve,-ve or zero

num=int(input("Enter any number "))


print("+ve") if num>0 else print("-ve") if num<0 else print("zero")

Output:
Enter any number 5
+ve

Enter any number -6


-ve

Enter any number 0


Zero

Example:
# Write a program to find input character is alphabet,digit or special
character

ch=input("Enter any character ")


print("alphabet") if ch>='A' and ch<='Z' or ch>='a' and ch<='z' else
print("Digit") if ch>='0' and ch<='9' else print("special character")

Output:
Enter any character a
alphabet

Enter any character A


alphabet

Enter any character 7


Digit

Enter any character *


special character
ord('A')
65
>>> ord('Z')
90
>>> ord('a')
97
>>> ord('z')
122
>>> ord('0')
48
>>> ord('9')
57
>>> 'A'>'B'
False
>>> chr(65)
'A'
>>> chr(97)
'a'

not operator
not is a unary operator, this operator required 1 operand
truth table of not operator
Opr1 Not Opr1
True False
False True

Not operator is used with other operator.


Example: not>,not in, is not

Example:
>>> not True
False
>>> not False
True
>>> not 100
False
>>> not 0
True

Membership operator
Membership operator is binary operator
This operator required two operands
Membership operator is represented using “in” keyword

1. In
2. Not in

Membership operator is used with collection data types for searching


given value in collection values.

Syntax: value/object in collection

In operator returns Boolean value (True/False)

Example
>>> "a" in "java"
True
>>> "python" in "best programming language to learn is python"
True
>>> 10 in [10,20,30,40]
True
>>> 100 in [10,20,30,40]
False
>>> "nk@nkit.com" in ["suresh@gmail.com","kishore@nkit.com"]
False
>>> 10 not in [10,20,30,40,50]
False
>>> 100 not in [10,20,30,40,50]
True

Example:
# Write a program to find input character is vowel

ch=input("Enter any character ")


print("vowel") if ch in "aeiouAEIOU" else print("not vowel")

Output
Enter any character a
vowel

Enter any character x


not vowel

Identity Operator
Identity operator is a binary operator
Identity operator is represented using “is” keyword.
Identity operator is used to compare references or identity of object.

1. is
2. is not
is operator returns True, if two variables pointing to same object inside
memory, else return False
is not operator return True, if two variables are not pointing to same
object inside memory else return False

Every object is having identity, this identity is called address.


What is difference between == and is operator in python?
== Is
It is a relational operator It is identity operator
This operator is used to compare This operator is used to compare
values of object (OR) object identity of objects. If two variables
equality are pointing to same object in
memory this operator returns True
else return False.

>>> a=10
>>> b=10
>>> a==b
True
>>> id(a)
140715736550104
>>> id(b)
140715736550104
>>> a is b
True
>>> list1=[10,20,30]
>>> list2=[10,20,30]
>>> list1==list2
True
>>> list1 is list2
False
>>> list3=list1
>>> list1 is list3
True

Walrus Operator (Python 3.8)


:= is called walrus operator or assignment expression operator
Walrus Operator (Python 3.8)
:= is called walrus operator or assignment expression operator
It is a binary operator and this operator is used as part of expression.

>>> a=(b=1+5)*(c=5-2)
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
>>> a=(b:=1+5)*(c:=5-2)
>>> print(a)
18
>>> print(b)
6
>>> print(c)
3
>>> x:=10
SyntaxError: invalid syntax
>>> x=10
>>> x
10

Bitwise Operators
Bitwise operators are used to perform operation on binary data.
1. Shift operators
a. Left shift operator
b. Right shift operator
2. Bitwise & (and) operator
3. Bitwise | (or) operator
4. Bitwise ^ (XOR) operator
5. Bitwise ~ (NOT) operator

Shift Operators
Shift operators are used to shift or move bits towards left side or right
side.
These operators are used to increment or decrement value by adding bits
or removing bits.

Applications
Memory Management
Encryption and Decryption

1. Right shift operator >>


2. Left shift operator <<

>> right shift operator is used to shift number of bits towards right side.
The shifted bits are deleted.

Syntax: value>>n

>>> a=12
>>> b=a>>2
>>> print(a,b)
12 3
>>> print(bin(a),bin(b))
0b1100 0b11
>>> x=25
>>> y=x>>3
>>> print(bin(x),bin(y))
0b11001 0b11
>>> print(x,y)
25 3

Formula : value//2 pow n

>>> b=a>>5
>>> a=20
>>> b=a>>2
>>> print(a)
20
>>> print(b)
5

Left shift operator is used to shift number of bits towards left side. By
shifting number of bits toward left side the value get incremented.

Syntax: value<<n
Formula: value*2 pow n

>>> a=10
>>> print(bin(a))
0b1010
>>> b=a<<1
>>> print(bin(b))
0b10100
>>> print(b)
20
Logical Gates
A logic gate is a device that acts as a building block for digital circuits.
They perform basic logical functions that are fundamental to digital
circuits. Most electronic devices we use today will have some form of
logic gates in them. For example, logic gates can be used in technologies
such as smartphones, tablets or within memory devices.
.

Bitwise & (and) operator


This operator is used to apply and gate
Truth table of bitwise & (and) operator

Opr1 Opr2 Opr1 & Opr2


1 0 0
0 1 0
1 1 1
0 0 0

If any input bit is 0, output is 0

Note: bitwise operators are applied only one integer data types.
Example:
>>> a=5
>>> b=4
>>> c=a&b
>>> print(a,b,c)
544
>>> print(bin(a),bin(b),bin(c))
0b101 0b100 0b100
>>> x=0b1010
>>> y=0b1110
>>> z=x&y
>>> print(bin(x),bin(y),bin(z))
0b1010 0b1110 0b1010
>>> print(x,y,z)
10 14 10

Bitwise (|) or operator


This operator is used to apply or gate
Truth table of bitwise| operator

Opr1 Opr2 Opr1 | Opr2


1 0 1
0 1 1
1 1 1
0 0 0

If any input bit is 1, output 1

>>> x=0b101
>>> y=0b110
>>> z=x|y
>>> print(bin(x),bin(y),bin(z))
0b101 0b110 0b111
>>> a=12
>>> b=20
>>> c=a|b
>>> print(bin(a),bin(b),bin(c))
0b1100 0b10100 0b11100
>>> print(a,b,c)
12 20 28
>>> a and b
20

Bitwise XOR (^) Operator


This operator is used to apply XOR gate
Truth table of XOR operator

Opr1 Opr2 Opr1^opr2


1 0 1
0 1 1
0 0 0
1 1 0

>>> a=0b101
>>> b=0b100
>>> c=a^b
>>> print(bin(a),bin(b),bin(c))
0b101 0b100 0b1

Bitwise not (~) operator


Bitwise not operator is unary operator, this operator required 1 operand.
Formula –(value+1)
Truth table
Opr1 ~Opr1
1 0
0 1

>>> a=5
>>> b=~a
>>> print(a)
5
>>> print(b)
-6
>>> print(bin(a),bin(b))
0b101 -0b110

Assignment Operator OR Update operators

Any of the operators can be combined with assignment. The means


that += , -= , *= , /= , //= , %= , **= , >>= , <<= , &= , ^= , and |=

augmented assignment statement is a single operator perform two


operations.
1. Binary operation
2. Assignment

>>> a=5
>>> a=a+2
>>> print(a)
7
>>> a+=2
>>> print(a)
9
>>> b=10
>>> b-=1
>>> print(b)
9
>>> c=16
>>> c/=4
>>> print(c)
4.0
>>> a=12
>>> a>>=2
>>> print(a)
3
Command line arguments
The values send to python program from command prompt or command
line is called command line arguments.

Command line arguments are used to develop utilities or tools or


commands in python.

The values send from command prompt are stored in one variable called
argv. It is a predefined variable/object exists in sys module.
How to execute program with command line arguments in IDLE?

Select 🡪 Run 🡪 Run Customized

Control Statements

1. Conditional Control Statements


a. If
b. Match
2. Looping control Statements
a. While
b. For
c. Nested looping
3. Branching Statements
a. Break
b. Continue
c. Pass
d. Return

Control statements are used to control the flow of execution of program.

Control statements are three types

1. Conditional control statements


2. Looping control statements
3. Branching statements

Conditional Control Statements


Python support two conditional control statements
1. if
2. match (python 3.10)

Conditional control statements are used to execute block of statements


based on condition or selection.

If statement
if is keyword which represent conditional statement.

Types of if syntax
1. simple if
2. if..else
3. if..elif..else (if..else ladder)
4. nested if

simple if

if without else is called simple if.

Syntax:

If <condition>:
Statement-1
Statement-2
Statement-3

If condition is True, PVM executes


Statement-1,Statement-2 and
Statement-3
If condition is False, PVM executes
statement-3

In python block must have one statement.s

Example:
if 10>5:
print("Python")
print("Hello")

if 5>10:
print("Java")
print("Bye")

if 2>10:
print(".Net")
print("Good")

Output:
Python
Hello
Bye

Example:
if 10>5:
pass

print("a")
print("b")

Output:
a
b

pass keyword
The pass statement is used as a placeholder for future code. When the
pass statement is executed, nothing happens, but you avoid getting an
error when empty code is not allowed. Empty code is not allowed in
loops, function definitions, class definitions, or in if statements.

Example:
if 10>5:
pass
print("Hello")

Output:
Hello

If..else

This syntax is having two blocks


1. if block
2. else block

Syntax:

If <condition>:
Statement-1
Statement-2
else:
Statement-3
Statement-4

Statement-5

If condition is True, PVM executes


Statement-1,Statement-2 and
Statement-5
If condition is False, PVM executes
Statement-3, Statement4 and
Statement-5

Example:

# Write a program to verify input number divisible with 7 or not

num=int(input("Enter any number "))


if num%7==0:
print(f'{num} is divisible with 7')
else:
print(f'{num} is not divisible with 7')

Output:
Enter any number 14
14 is divisible with 7

Enter any number 12


12 is not divisible with 7

Example:

# Write a program to display "Hello" if input number is multiples of 5 else


display "Bye"

num=int(input("Enter any Number "))


if num%5==0:
print("Hello")
else:
print("Bye")

Output:
Enter any Number 20
Hello

Enter any Number 22


Bye
Home Work
1. Write a program to find input year is leap or not
2. Write a program to find input number last digit is even or odd
3. Write a program to check input number is 3 digit or not
4. Write a program to check a person is senior citizen or not
5. Write a program to find minimum value of input two values
6. Write a program to find input number is +ve or –ve
7. Write a program to find input number is divisible 2 and 3
if..elif..else (if..else ladder)

This syntax allows checking more than one condition.


Syntax:

If condition1:
Statement-1
elif condition2:
Statement-2
elif condition3:
Statement-3

else:
Statement-n

If condition1 is True PVM execute


Statement-1
If condition1 is False and Condition2
is True, PVM executes statement-2
If condition1,condition2 is False and
condition3 is True, PVM executes
Statement-3
If all conditions are False, PVM
executes Statement-n

Example:

# Write a program to find input character is alphabet,digit or sepcial


character

ch=input("Enter any character ")


if ch>='A' and ch<='Z' or ch>='a' and ch<='z':
print("alphabet")
elif ch>='0' and ch<='9':
print("digit")
else:
print("special character")

Output:
Enter any character a
alphabet

Enter any character 5


digit

Enter any character $


special character

https://www.hackerrank.com/challenges/py-if-
else/problem?isFullScreen=true

n=int(input())
if n%2!=0:
print("Weird")
elif n>=2 and n<=5:
print("Not Weird")
elif n>=6 and n<=20:
print("Weird")
elif n>20:
print("Not Weird")
units=int(input("Enter units"))
if units<=100:
amt=0
elif units>100 and units<=200:
amt=(units-100)*5
else:
amt=0+500+(units-200)*10
print(f'Amount {amt}')

p=int(input("Enter Percentage"))
if p>90:
print("A")
elif p>80 and p<=90:
print("B")
elif p>=60 and p<=80:
print("C")
else:
print("D")
cost=int(input("Enter Bike Price :"))
if cost>100000:
tax=cost*15/100
elif cost>50000 and cost<=100000:
tax=cost*10/100
else:
tax=cost*5/100

print(f'Bike Price {cost}')


print(f'Road Tax {tax:.2f}')
salary=int(input("Enter Salary "))
service=int(input("Enter Service "))
if service>10:
bonus=salary*10/100
elif service>=6 and service<=10:
bonus=salary*8/100
else:
bonus=salary*5/100

print(f'Salary {salary}')
print(f'Bonus {bonus}')

Output:
Enter Salary 50000
Enter Service 12
Salary 50000
Bonus 5000.0

Enter Salary 30000


Enter Service 7
Salary 30000
Bonus 2400.0

Example:
# Write a program to convert input alphabet into uppercase to lower
case,
# lowercase to uppercase
ch=input("Enter any character ")
if ch>='a' and ch<='z':
ch=chr(ord(ch)-32)
print(ch)
elif ch>='A' and ch<='Z':
ch=chr(ord(ch)+32)
print(ch)
else:
print("input character must be alphabet")

Output:
Enter any character $
input character must be alphabet

Enter any character 7


input character must be alphabet

Enter any character a


A

Enter any character A


A

Nested if

If within if is called nested if.


Syntax:

If condition1:
If condition2:
Statement-1
else:
Statement-2
elif condition3:
if condition4:
Statement-3
Else:
Statement-4
else:
Statement-5

Example:
# Login Application

user=input("UserName ")
if user=="nit":
pwd=input("Password ")
if pwd=="nit123":
print("Welcome")
else:
print("invalid password")
else:
print("invalid username")

Output:
UserName abc
invalid username

UserName nit
Password nit123
Welcome

Example:
# Write program to login with OTP

import random
user=input("UserName ")
otp=random.randint(1000,9999)
print(f'{user} please Login with OTP {otp}')
otp1=int(input("OTP :"))
if otp1==otp:
print(f'{user} welcome')
else:
print("invalid OTP")

Output:
UserName nk
nk please Login with OTP 2602
OTP :2602
nk welcome

UserName suresh
suresh please Login with OTP 9425
OTP :9424
invalid OTP

match statement
match statement
match is selection statement.
match statement execute block of statements based selection of value.
match is softkeyword in python.
match statement is introduced in python 3.10 version

Syntax:

match(expression/value):
case <pattern>:
statement-1
case <pattern>:
statement-2
case <pattern>:
statement-3
case _:
statement-x

PVM read value and compare with all the cases, if equals to any case,
PVM execute that block and terminates.
If value is not equal to any case, PVM executes default case which is
defined _

Example:

# Write a program to input digit [0-9] and print in word


# input : 4
# output :Four

digit=int(input("Enter any Digit (0-9): "))


match(digit):
case 0:
print("Zero")
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case 4:
print("Four")
case 5:
print("Five")
case 6:
print("Six")
case 7:
print("Seven")
case 8:
print("Eight")
case 9:
print("Nine")
case _:
print("Invalid Digit")

Output:
Enter any Digit (0-9): 3
Three

Enter any Digit (0-9): 9


Nine

Enter any Digit (0-9): 10


Invalid Digit

Example:
print("****Menu****")
print("1.Area of Circle")
print("2.Area of Triangle")
print("3.Area of Rectangle")
print("4.Exit")
opt=int(input("Enter Your Option [1-4] "))
match(opt):
case 1:
r=float(input("Enter R Value "))
area=3.147*r*r
print(f'Area of Circle is {area:.2f}')
case 2:
base=float(input("Enter Base Value "))
height=float(input("Enter Height Value "))
area=0.5*base*height
print(f'Area of Triangle {area:.2f}')
case 3:
l=float(input("Enter L Value "))
b=float(input("Enter B Value "))
area=l*b
print(f'Area of Rectangle {area:.2f}')

case 4:
print("Thank You...")
case _:
print("Invalid Option Try again...")

Output:
****Menu****
1.Area of Circle
2.Area of Triangle
3.Area of Rectangle
4.Exit
Enter Your Option [1-4] 2
Enter Base Value 1.2
Enter Height Value 1.5
Area of Triangle 0.90

****Menu****
1.Area of Circle
2.Area of Triangle
3.Area of Rectangle
4.Exit
Enter Your Option [1-4] 1
Enter R Value 1.5
Area of Circle is 7.08

Example:
# Write a program to find input character is vowel or not

ch=input("Enter any character ")


match(ch):
case 'a':
print("vowel")
case 'e':
print("vowel")
case 'i':
print("vowel")
case 'o':
print("vowel")
case 'u':
print("vowel")
case _:
print("not vowel")

Output:
Enter any character e
vowel

Enter any character x


not vowel
Example:
>>> list1=[10,20,30,40,50]
>>> match(list1):
... case [10,20,30,40,50]:
... print("Hello")

Looping Control Statements


Looping control statements are used to repeat one or more than one
statement number of times or until given condition.

Python support 2 Looping control statements


1. while
2. for

while loop

“while” keyword represents while loop


While loop execute given block of statements until given condition is
True.
Syntax:

while <condition>:
statement-1
statement-2

PVM repeat statement-1,statement-


2 until given condition is True.

While loop required 3 statements


1. initialization statement
2. condition
3. update statement

Initialization statement defines initial value of condition.


Condition is a Boolean expression which defines how many times while
loop has to execute.
Update statement, which updates condition.

Example:
# Write a program to input 5 numbers and print sum

i=1
s=0
while i<=5:
value=int(input("Enter Value "))
s=s+value
i=i+1

print(f'Sum is {s}')

Output:
Enter Value 10
Enter Value 40
Enter Value 20
Enter Value 40
Enter Value 50
Sum is 160

Example:
i=0
while i<=5:
print("Hello")
i=i+1

j=1
while j<=5:
print("Bye")
j=j+2

k=1
while k>=5:
print("java")
k=k+1

p=5
while p>=1:
print("Python")
p=p-1
Output:
Hello
Hello
Hello
Hello
Hello
Hello
Bye
Bye
Bye
Python
Python
Python
Python
Python
Full Stack Python (Part-26)
Example:
# Write a program to find length of number or count digits of input
number

num=int(input("Enter any number "))


c=0
if num==0:
c=1
else:
while num>0:
num=num//10
c=c+1

print(f'Count of digits {c}')

Output:
Enter any number 0
Count of digits 1

Enter any number 168


Count of digits 3

Example:

# Write a program to find sum of digits of input number

num=int(input("Enter any number "))


s=0
while num>0:
r=num%10
s=s+r
num=num//10

print(f'Sum of digits {s}')

Output:
Enter any number 123
Sum of digits 6

Enter any number 54


Sum of digits 9

Enter any number 0


Sum of digits 0

Example:

# Write a program to count how many even and odd digits exists within
input number

num=int(input("Enter any number ")) # 123


ecount=0
ocount=0

while num>0:
r=num%10
if r%2==0:
ecount=ecount+1
else:
ocount=ocount+1
num=num//10

print(f'Even count digits {ecount}')


print(f'Odd count digits {ocount}')

Output:
Enter any number 4893
Even count digits 2
Odd count digits 2

Enter any number 123


Even count digits 1
Odd count digits 2

Example:
# Write a program to find input number is armstrong or not (3digit
number)

num=int(input("Enter any number "))


num1=num
s=0
while num>0:
r=num%10
s=s+(r**3)
num=num//10

if s==num1:
print(f'{num1} armstrong')
else:
print(f'{num1} is not armstrong')

Output
Enter any number 153
153 armstrong
Enter any number 125
125 is not armstrong

Enter any number 370


370 armstrong

Example:
# Write a program to find an input number is perfect number or not

num=int(input("enter any number "))

s=0
i=1
while i<num:
r=num%i
if r==0:
s=s+i
i=i+1

if s==num:
print(f'{num} is perfect number ')
else:
print(f'{num} is not perfect number')

Output:
enter any number 6
6 is perfect number

enter any number 5


5 is not perfect number
Example:
# Write a program to find input number is palindrome or not

num=int(input("Enter any number "))


num1=num
rev=0

while num>0:
r=num%10
rev=(rev*10)+r
num=num//10

print(num1)
print(rev)
if rev==num1:
print(f'{num1} is palindrome')
else:
print(f'{num1} is not palindrome')

Output:
Enter any number 123
123
321
123 is not palindrome

HOME WORK

Write a program to print number in words


123

ONE TWO THREE

489

Four Eight Nine


Write a program to print number in words
123
ONE TWO THREE
489
Four Eight Nine

num=int(input("Enter any number "))


rev=0
while num>0:
r=num%10
rev=(rev*10)+r
num=num//10
while rev>0:
r=rev%10
match(r):
case 1:
print("one",end=' ')
case 2:
print("two",end=' ')
case 3:
print("three",end=' ')
case 4:
print("four",end=' ')
case 5:
print("five",end=' ')
case 6:
print("six",end=' ')
case 7:
print("seven",end=' ')
case 8:
print("eight",end=' ')
case 9:
print("nine",end=' ')
case 0:
print("zero",end=' ')
rev=rev//10

for loop
“for” keyword represents for loop.
For loop is used to repeat one or more than one statement number of
times.
For loop is called iterator, which iterate values from iterables (collections
(OR) for loop is used to read values from collections.

Syntax:
for variable-name in iterable:
statement-1
statement-2

for loop each time read one value from iterable and assign to a variable;
After assigning to variable, it execute block of statements.
Statement-1, statement-2 is executed until read all the values from
iterable.

Example:
str1="java"
for ch in str1:
print(ch)

Output:
j
a
v
a

Example:
# Write a program to find length of string
str1=input("Enter any string ")
c=0
for ch in str1:
c=c+1

print(f'Length of string {c}')

Output:
Enter any string python
Length of string 6

Enter any string java


Length of string 4

Example:
# Write a program to count
# alphabets, digits and sepcial character exists within input string

str1=input("Enter any string ")

ac=0
dc=0
sc=0

for ch in str1:
if ch>='a' and ch<='z' or ch>='A' and ch<='Z':
ac=ac+1
elif ch>='0' and ch<='9':
dc=dc+1
else:
sc=sc+1

print(f'Alphabet Count {ac}')


print(f'Digit Count {dc}')
print(f'Special Character Count {sc}')
Output:
Enter any string ab12$%c@34A
Alphabet Count 4
Digit Count 4
Special Character Count 3

range data type


range is an immutable sequence data type.
This data type is used to generate sequence of integer values.

Application development range data type is used,


1. To repeat for loop number of times
2. To generate values from other collection types or containers.

The range type represents an immutable sequence of numbers and is


commonly used for looping a specific number of times in for loops

How to create range object?


Syntax-1: range(stop)
Syntax-2: range(start,stop,step)

range object is having 3 attributes.


1. Start
2. Stop
3. Step

Start: starting value of range


Stop: stop value of range
Step: increment or decrement value

Start and Stop values are given based on Step value.


Step is +ve 🡪 start<stop
Step is –ve 🡪 start>stop

Syntax-1: range(stop)
This syntax is used to generate sequence of +ve integer values.
In this syntax default start=0,step=+1

Example:
r1=range(10) # creating range object start=0,stop=10,step=1 0 1 2 3 4 5 6
789

for a in r1:
print(a,end=' ')

print("\n-----------------------")
for b in range(5): # start=0,stop=5,step=1 --> 0 1 2 3 4
print(b,end=' ')

print("\n-------------------------")
for c in range(-5): # start=0,stop=-5,step=1
print(c,end=' ')

Output:
0123456789
-----------------------
01234
-------------------------

Syntax2: range(start,stop,[step])
This syntax is used to generate sequence of integers in increment or
decrement order.
If step value is not given it default to +1

Example:
for a in range(1,11): # start=1,stop=11,step=1 --> 1 2 3 4 5 6 7 8 9 10
print(a,end=' ')

print()
for b in range(1,11,2): # start=1,stop=11,step=2 --> 1 3 5 7 9
print(b,end=' ')

print()
for c in range(2,20,2): # start=2,stop=20,step=2 --> 2 4 6 8 10 12 14 16 18
print(c,end=' ')

print()
for d in range(10,0,-1): # start=10,stop=0,step=-1 --> 10 9 8 7 6 5 4 3 2 1
print(d,end=' ')

print()
for e in range(-1,-11,-1): # start=-1,stop=-11,step=-1
print(e,end=' ')

print()
for f in range(-10,0,1): # start=-10,stop=0,step=1
print(f,end=' ')

print()
for g in range(-5,6): # start=-5,stop=6,step=1
print(g,end=' ')

print()
for h in range(5,-6,-1): # start=5,stop=-6,step=-1
print(h,end=' ')

print()

# range required integer input


#for i in range(1.0,6.0):
# print(i)

# the step of value range should not be zero


#for i in range(1,10,0):
# print(i)

Output:
1 2 3 4 5 6 7 8 9 10
13579
2 4 6 8 10 12 14 16 18
10 9 8 7 6 5 4 3 2 1
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
-5 -4 -3 -2 -1 0 1 2 3 4 5
5 4 3 2 1 0 -1 -2 -3 -4 -5

Example:
# Write a program to generate math table of input number

# 5
# 5x1=5
# 5x2=10
# ...
# 5x10=50

num=int(input("Enter any number "))

for i in range(1,11): # 1 2 3 4 5 6 7 8 9 10
p=num*i
print(f'{num}x{i}={p}')
.
Output:
Enter any number 7
7x1=7
7x2=14
7x3=21
7x4=28
7x5=35
7x6=42
7x7=49
7x8=56
7x9=63
7x10=70
Example:
# Write a program to generate the following series
# 1 4 9 16 25 36 ... n**2

n=int(input("enter value of n"))


for num in range(1,n+1): # start=1,stop=5,step=1 --> 1 2 3 4 5
print(f'{num}-->{num**2}')

Output:
enter value of n5
1-->1
2-->4
3-->9
4-->16
5-->25

Example:
# write a program to generate even numbers between m,n

m=int(input("enter value of m")) # 5


n=int(input("enter value of n")) # 20
for num in range(m,n+1): # start=5,stop=21,step=1 --> 5 6 7 8 9 10 ... 20
if num%2==0:
print(num)

Output:
enter value of m5
enter value of n20
6
8
10
12
14
16
18
20
Example:
# Write a program to genreate ascii table for uppercase letter
# A --> 65
# B ---> 66
# C ---> 67
# Z --> 90

for num in range(65,91):


print(f'{chr(num)}-->{num}')

Output:
A-->65
B-->66
C-->67
D-->68
E-->69
F-->70
G-->71

Example:
# Write a program to find input number is prime or not

num=int(input("Enter any number "))


c=0
for i in range(1,num+1):
if num%i==0:
c=c+1

if c==2:
print(f'{num} is prime')
else:
print(f'{num} is not prime')
Output:
Enter any number 4
4 is not prime

Enter any number 7


7 is prime

Example:
# Write a program to print first 10 even numbers in reverse order

for num in range(20,0,-2): # start=20,stop=0,step=-2


print(num)

Output:
20
18
16
14
12
10
8
6
4
2

# Write a program to find factorial of input number

num=int(input("Enter any number ")) # 3


fact=1
for i in range(1,num+1): # start=1,stop=4,step=1 --> 1 2 3
fact=fact*i

print(f'{num} factorial is {fact}')

# Accept 10 numbers from user and display their avg

s=0
for i in range(10):
num=int(input("Enter any number "))
s=s+num

avg=s/10
print(f'Avg is {avg:.2f}')

Output:
Enter any number 10
Enter any number 20
Enter any number 30
Enter any number 40
Enter any number 50
Enter any number 60
Enter any number 70
Enter any number 80
Enter any number 90
Enter any number 100
Avg is 55.00
Example:
# Accept 10 numbers from user and find maximum and minimum value
max_value=0
min_value=0
for i in range(10):
num=int(input("Enter any number "))
if i==0:
max_value=num
min_value=num
else:
if num>max_value:
max_value=num
elif num<min_value:
min_value=num

print(f'Minimum Value {min_value}')


print(f'Maximum Value {max_value}')

Output:
Enter any number 1
Enter any number 7
Enter any number 3
Enter any number 9
Enter any number 2
Enter any number 5
Enter any number 4
Enter any number 77
Enter any number 1
Enter any number 0
Minimum Value 0
Maximum Value 77

# Write a program to display sum of odd numbers and even number


that fall between 12 and 37
even_sum=0
odd_sum=0
for num in range(12,38):
if num%2==0:
even_sum+=num
else:
odd_sum+=num

print(f'Even Numbers Sum {even_sum}')


print(f'Odd Numbers Sum {odd_sum}')

Output:

Even Numbers Sum 312


Odd Numbers Sum 325

Example:
# Write a program to display all the numbers which are divisible by 11 but
not by 2 between
# 100 and 500

for num in range(100,501):


if num%11==0 and num%2!=0:
print(num)

Output:
121
143
165
187
209
231
253
275
297
319
341
363
385
407
429
451
473
495
Full Stack Python (Part-29)

MCQ Practice
https://cbsepython.in/mcq-on-for-loop-
in-python-class-11/
Nested Looping Statements

Defining a looping statement within looping statement is called nested


looping statement.

1. Nested for
2. Nested while

Nested for loop


for loop inside for loop is called nested for loop.

Syntax:

for variable-name in iterable: # outer loop


for variable-name in iterable: # inner loop
statement-1
statement-2
statement-3

Example:
# Write a program to generate tables from 1 to 5

for num in range(1,6): # 1 2 3 4 5


for i in range(1,11): # 1 2 3 4 5 6 7 8 9 10
print(f'{num}x{i}={num*i}')

Output:
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
1x6=6
1x7=7
1x8=8
1x9=9
1x10=10
2x1=2
2x2=4
2x3=6
2x4=8
2x5=10
2x6=12
2x7=14
2x8=16
2x9=18
2x10=20
3x1=3
3x2=6
3x3=9
3x4=12
3x5=15
3x6=18
3x7=21
3x8=24
3x9=27
3x10=30
4x1=4
4x2=8
4x3=12
4x4=16
4x5=20
4x6=24
4x7=28
4x8=32
4x9=36
4x10=40
5x1=5
5x2=10
5x3=15
5x4=20
5x5=25
5x6=30
5x7=35
5x8=40
5x9=45
5x10=50
Example:
# write a program to generate factorials of all numbers from 1-5

# 1 --> 1
# 2 --> 2
# 3 --> 6
# 4 --> 24
# 5 --> 120

for num in range(1,6): # 1 2 3 4 5


fact=1
for i in range(1,num+1): # 1 2 3 4 5
fact=fact*i
print(f'Factorial of {num}-->{fact}')

Output:
Factorial of 1-->1
Factorial of 2-->2
Factorial of 3-->6
Factorial of 4-->24
Factorial of 5-->120

Example:
# write a program to print prime numbers from 2 to 20

for num in range(2,21): # 2 3 4 5 6 7 8 9 10 11 12 13 ... 20


c=0
for i in range(1,num+1):
if num%i==0:
c=c+1
if c==2:
print(f'{num} is prime')

Output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime

Example:
for j in range(1,6):
for i in range(1,6):
print(1,end=' ')
print()

for j in range(1,6):
for i in range(1,6): # 1 2 3 4 5
print(i,end=' ')
print()

Output:
11111
11111
11111
11111
11111
12345
12345
12345
12345
12345
Example:

spaces=4
for r in range(1,6):
for s in range(spaces):
print(" ",end='')
for c in range(1,r+1):
print("* ",end='')
print()
spaces=spaces-1

spaces=0
for r in range(5,0,-1):
for s in range(spaces):
print(" ",end='')
for c in range(1,r+1):
print("* ",end='')
print()
spaces=spaces+1

Output:
Nested while loop
While loop inside while loop is called nested while loop.

Syntax:
while <condition>: 🡪 Outer looping statement
statement-1
statement-2
while <condition>: 🡪 Inner looping statement
statement-3
statement-4

while loop is executed until given condition is True.

Example:
# using while loop generate numbers from 1 to 10

num=1
while num<=10:
print(num,end=' ')
num=num+1

Output:
1 2 3 4 5 6 7 8 9 10

Example:
# Write a program to generate the following output
#1 2 3 4 5 6 7 8 9 10
#2 4 6 8 10 12 14 16 18 20
# 3 6 9 12 15 18 21 24 27 30
#....
# 10 20 30 40 50 60 70 80 90 100

n=1
while n<=10: # Outer loop
i=1
while i<=10: # inner loop
print(n*i,end=' ')
i=i+1
print()
n=n+1

Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

Example:
a=int(input("enter starting value "))
b=int(input("enter ending value "))

while a<=b:
i=1
s=0
while i<a:
if a%i==0:
s=s+i
i=i+1
if s==a:
print(a)
a=a+1
Output:
enter starting value 6
enter ending value 500
6
28
496

What is difference between while and for loop?


while for
While loop repeat block of For loop repeat block of statements
statements until given condition number of times
Branching statements
Branching statements are used to control looping statements.
Python support the following branching statements
1. break
2. continue
3. return (functions)

break
break is branching statement or passes control statement.
break is a keyword.
break statement is used inside looping statements (while, for).
This statement is used to terminate execution of while or for
unconditionally or in between.

Example:
for num in range(1,11):
print("Hello")
break

num=1
while num<=10:
print("Bye")
num=num+1
break

Output:
Hello
Bye
Example:
# write a program to find input number is prime or not

num=int(input("Enter any number "))


c=0
for i in range(1,num+1):
print("Hello")
if num%i==0:
c=c+1
if c>2:
break

if c==2:
print(f'{num} is prime')
else:
print(f'{num} is not prime')

Output:
Enter any number 6
Hello
Hello
Hello
6 is not prime

Example of Login app


while True:
user=input("UserName :")
pwd=input("Password :")
if user=="nit" and pwd=="nit123":
print("Welcome")
break
else:
print("invalid username or password pls try again...")

Output:
UserName :nit
Password :abc
invalid username or password pls try again...
UserName :abc
Password :nit123
invalid username or password pls try again...
UserName :nit
Password :nit123
Welcome

Example:
# Write a program to generate first 10 prime numbers

num=2
prime_count=0
while True:
c=0
for i in range(1,num+1):
if num%i==0:
c=c+1
if c>2:
break
if c==2:
print(num)
prime_count=prime_count+1
if prime_count==10:
break
num=num+1

Output:
2
3
5
7
11
13
17
19
23
29

continue

continue is a keyword or branching statement or passes control


statement.
Continue statement is included with in looping statements (for, while)
This statement continue the execution of while or for.

Example:
for num in range(1,11): # 1 2 3 4 5 6 7 8 9 10
if num%2==0:
continue
print(num)

Output:
1
3
5
7
9
Full Stack Python (Part-33)

while…else and for ..else

while and for loops are defined with else block.


Syntax of while..else Syntax of for..else

while <condition>: for variable in iterable:


statement-1 statement-1
statement-2 statement-2
else: else:
statement-3 statement-3

else block is executed after execution of while and for loop.


else block is not executed when for,while loop are terminated using
break statement.

Example:
n=1
while n<=5:
print(n)
n=n+1
else:
print("inside else block")

n=1
while n<=5:
print(n)
break
else:
print("Inside else block")
Output:
1
2
3
4
5
inside else block
1

Example:
for num in range(1,6): # 1 2 3 4 5
print(num)
else:
print("inside else block")

for num in range(1,6):


print(num)
break
else:
print("inside else block")

Output:
1
2
3
4
5
inside else block
1

Collections or data structures


Python data types are classified into two categories
1. Scalar data types
2. Collection types
Scalar data types are used to represent one value.
1. Int
2. Float
3. Complex
4. Bool
5. NoneType

Collection data types are used to represent more than value


1. Sequences
a. List
b. Tuple
c. Range
d. String
e. Bytes
f. Bytearray
2. Sets
a. Set
b. Frozenset
3. Mapping
a. Dictionary

Collection types are called containers.


Collection types allow to group individual objects and represent as one
object.
Collection types are called iterable.
Iterable objects implements iteration protocol.
Collections are used store more than one value or object.
Every collection uses a data structure for organizing data.

Sequences
Sequences are ordered collections, where objects are organized in
sequential order (OR) insertion order is preserved.

Properties of sequences
1. Index based
2. Allows duplicates
3. Slicing
4. Homogenous or Heterogeneous

Python support the following sequence data types


1. List (Mutable)
2. Tuple (Immutable)
3. Range (Immutable)
4. String (Immutable)
5. Bytes (Immutable)
6. Bytesarray (mutable)

list datatype or collection


list is a mutable sequence data type.
Lists are mutable sequences, typically used to store collection of
homogeneous items.
List is a linear data structure, which is mutable and ordered sequence of
element/items.
Each value/object in list is called element or item.

In application development list is used to represent group of individual


objects where duplicates are allowed and reading/writing is done
sequential and random.

“list” is name of class or data type represents list object.

How to create list?


1. Using a pair of square brackets to denote the empty list: []
2. Using square brackets, separating items with commas: [a], [a, b, c]
3. Using a list comprehension: [x for x in iterable]
4. Using the type constructor or function: list() or list(iterable)

Example:
>>> list1=[]
>>> print(list1)
[]
>>> print(type(list1))
<class 'list'>
>>> list2=[10]
>>> print(list2)
[10]
>>> print(type(list2))
<class 'list'>
>>> list3=[10,20,30,40,50]
>>> print(list3)
[10, 20, 30, 40, 50]
>>> print(type(list3))
<class 'list'>

>>> sales=[10000,20000,30000,40000,50000]
>>> stud=[1,"Nk","python",6000.0]
>>> print(sales)
[10000, 20000, 30000, 40000, 50000]
>>> print(stud)
[1, 'Nk', 'python', 6000.0]

Creating list using list() function


It type is a type conversion function, which convert other iterables or
collections into list type.

1. list() 🡪 Create empty list


2. list(iterable) 🡪 Create list by using existing iterable or collection.

Example:
>>> list4=list()
>>> print(list4)
[]
>>> print(type(list4))
<class 'list'>
>>> list5=list(range(1,6))
>>> print(list5)
[1, 2, 3, 4, 5]
>>> list6=list(range(10,110,10))
>>> print(list6)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list7=list("PYTHON")
>>> print(list7)
['P', 'Y', 'T', 'H', 'O', 'N']

>>> list8=list("NIT")
>>> print(list8)
['N', 'I', 'T']
>>> list9=list([10,20,30])
>>> list10=list(list9)
>>> print(list9)
[10, 20, 30]
>>> print(list10)
[10, 20, 30]

Reading content of list/sequences

Python allows reading content of sequence in different ways


1. index
2. slicing
3. for loop
4. iterator
5. enumerate

index

What is index?
Index is an integer value.
Each element/item in list/sequence identified with index.
Index is element position OR each location in list/sequence is identified
with integer value called index.
Index is used to read elements from sequence in sequentially or
randomly.

Index values are two types


1. +ve Index
2. –ve index

+ve index start at 0, which is used to read items left to right (forward
direction)
-ve index start at -1, which is used to read items in right to left
(backward direction)

This index is used as a subscript to read value from list.

Syntax: list-name[index]

Example
>>> L=[10,20,30,40,50]
>>> print(L)
[10, 20, 30, 40, 50]
>>> L[0]
10
>>> L[-1]
50
>>> L[2]
30
>>> L[-2]
40
>>> L[5]
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
L[5]
IndexError: list index out of range
>>> L[-5]
10
Full Stack Python (Part-34)
len() : This function returns count elements or length of iterable

Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> print(len(list1))
5

Example:
Displaying +ve and –ve values from list

list1=[1,2,-4,5,-6,6,7,8,9,-10,-12,11,-14,-13]
print(list1)
a=len(list1)
print("Reading -Ve Values from List")
for i in range(a): # start=0,stop=10,step=1 0 1 2 3 4 5 6 7 8 9
if list1[i]<0:
print(list1[i],end=' ')

print()
print("Reading +Ve values from List")
for i in range(a):
if list1[i]>=0:
print(list1[i],end=' ')

Output:
[1, 2, -4, 5, -6, 6, 7, 8, 9, -10, -12, 11, -14, -13]
Reading -Ve Values from List
-4 -6 -10 -12 -14 -13
Reading +Ve values from List
1 2 5 6 7 8 9 11
Example:
# Count of even and odd number of list
list1=[4,8,9,1,2,3,4,12,15,17,19,24,35,76,77,45,54,34,21]
print(list1)
a=len(list1)
ecount,ocount=0,0
for i in range(a): # start=0,stop=15,step=1 0 1 2 3 4 5 6 7 8 9 ... 14
if list1[i]%2==0:
ecount+=1
else:
ocount+=1

print(f'Even number count {ecount}')


print(f'Odd number count {ocount}')

Output:
[4, 8, 9, 1, 2, 3, 4, 12, 15, 17, 19, 24, 35, 76, 77, 45, 54, 34, 21]
Even number count 9
Odd number count 10

Example:
list1=[1,2,-4,5,-6,6,7,8,9,-10,-12,11,-14,-13]
a=len(list1)
for i in range(-1,-(a+1),-1): # start=-1,stop=-15,step=-1 -1 -2 -3 -4 -5 ... -
14
print(list1[i],end=' ')

print()
for i in range(a): # start=0,stop=14,step=1
print(list1[i],end='')

Output:
-13 -14 11 -12 -10 9 8 7 6 -6 5 -4 2 1
12-45-66789-10-1211-14-13

Example:
# Write a program to add all the values of list

list1=list(range(10,110,10))
print(list1)
a=len(list1)
total=0
for i in range(a):# start=0,stop=10,step=1 0123456789
total=total+list1[i]

print(f'Total is {total}')
print(f'Avg is {total/a}')

Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Total is 550
Avg is 55.0

Example:
# Python program to find smallest number in a list

scores=[50,30,20,10,50,60]
a=len(scores)

for i in range(a): # start=0,stop=6,step=1 --> 0 1 2 3 4 5


if i==0:
min_score=scores[i]
elif scores[i]<min_score:
min_score=scores[i]

print(scores)
print(f'Minimum Score {min_score}')

# Finding maximum score


for i in range(a): # start=0,stop=6,step=1 --> 0 1 2 3 4 5
if i==0:
max_score=scores[i]
elif scores[i]>max_score:
max_score=scores[i]

print(f'Maximum Score {max_score}')


print(f'Minimum Score {min(scores)}')
print(f'Maximum Score {max(scores)}')
print(f'Total Score {sum(scores)}')

Output:
[50, 30, 20, 10, 50, 60]
Minimum Score 10
Maximum Score 60
Minimum Score 10
Maximum Score 60
Total Score 220

max(iterable) Return maximum value of iterable


min(iterable) Return minimum value of iterable
sum(iterable) Add all the values of iterable and return
len(iterable) Return count of values or elements or items

Sort
sort(*, key=None, reverse=False)
This method sorts the list in place. It is a mutable method of list.
Reverse argument:
Default value of reverse is False, which mean it sort in ascending
order
If reserve value is given True, it sort elements in descending order
Key is a function which is applied to each element.

Example:
>>> list1=[4,5,1,8,3,9,2,7,11,66,12,15,10]
>>> print(list1)
[4, 5, 1, 8, 3, 9, 2, 7, 11, 66, 12, 15, 10]
>>> list1.sort()
>>> print(list1)
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 15, 66]
>>> list1.sort(reverse=True)
>>> print(list1)
[66, 15, 12, 11, 10, 9, 8, 7, 5, 4, 3, 2, 1]
>>> list1=["d","a","B","c","A","D","C","b"]
>>> print(list1)
['d', 'a', 'B', 'c', 'A', 'D', 'C', 'b']
>>> list1.sort()
>>> print(list1)
['A', 'B', 'C', 'D', 'a', 'b', 'c', 'd']
>>> list1.sort(key=str.upper)
>>> print(list1)
['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd']
>>> list1.sort(key=str.upper,reverse=True)
>>> print(list1)
['D', 'd', 'C', 'c', 'B', 'b', 'A', 'a']

count(value)
This method return count of given value inside iterable.

>>> list1=[1,2,3,4,1,2,3,1,2,3,5,6,7]
>>> list1.count(1)
3
>>> list1.count(5)
1
>>> list1.count(3)
3

Example:
# finding second maximum
list1=[4,8,1,9,1,2,3,4,12,15,17,19,24,35,76,77,45,54,34,21,77]
print(list1)
list1.sort()
print(list1)
fmax=list1[-1]
k=list1.count(fmax)
smax=list1[-(k+1)]
print(fmax)
print(smax)
fmin=list1[0]
k=list1.count(fmin)
smin=list1[k]
print(fmin)
print(smin)

Output:
[4, 8, 1, 9, 1, 2, 3, 4, 12, 15, 17, 19, 24, 35, 76, 77, 45, 54, 34, 21, 77]
[1, 1, 2, 3, 4, 4, 8, 9, 12, 15, 17, 19, 21, 24, 34, 35, 45, 54, 76, 77, 77]
77
76
1
2
Slicing
“Slicing” means getting a subset of elements from an iterable/sequence
based on their indices.
Slicing allows reading more than one value from sequences.

Slicing is done using two approaches


1. Using slice operator
2. Using slice object

What is difference between indexing and slicing?


Index Slicing
Index allows to read one value Slicing allows reading more than
one value by generating multiple
indices.

Slice operator
Syntax: sequence-name[start:stop:step]

Slice operator internally uses range for generating multiple indices.

Syntax1: sequence-name[::] or seqnece-name[:]


This syntax create copy of sequence by using default start,stop and step.
Default start=0,stop=len(sequence),step=+1

Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list2=list1[::]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list1[:]
>>> print(list3)
[10, 20, 30, 40, 50]

Syntax2: sequence-name[::step]
In this syntax start and stop values are generated based on step value.
If step=+ve, start=0,stop=len(sequence)
If step=-ve, start=-1,stop=-(len(sequence)+1)

Example:
>>> list1=list(range(10,110,10))
print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[::1]
>>> print(list2)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list3=list1[::2]
>>> print(list3)
[10, 30, 50, 70, 90]
>>> list4=list1[::-1]
>>> print(list4)
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
>>> list5=list1[::-2]
>>> print(list5)
[100, 80, 60, 40, 20]

Syntax3: sequence-name[start::] or sequence-name[start:]


This syntax read values from left to right.
In this syntax default step value is +1
Default stop is till end of list.

>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[5:]
>>> print(list2)
[60, 70, 80, 90, 100]
>>> list3=list1[-5:]
>>> print(list3)
[60, 70, 80, 90, 100]
Syntax4: sequence-name[:stop:] or sequence-name[:stop]
This syntax read values from left to right
Default start=0,step=1

>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[:5:]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list1[:-5:]
>>> print(list3)
[10, 20, 30, 40, 50]
>>> list4=list1[:-3:]
>>> print(list4)
[10, 20, 30, 40, 50, 60, 70]
>>> list5=list1[:-8:]
>>> print(list5)
[10, 20]

Syntax5: sequence-name[start:stop:]
This syntax read values from left to right
Defaults step is +1

>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[0:5]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list1[-5:-3]
>>> print(list3)
[60, 70]
>>> list4=list1[-3:-6]
>>> print(list4)
[]
>>> list5=list1[3:-3]
>>> print(list5)
[40, 50, 60, 70]

Syntax-6: sequence-name[start:stop:step]

>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[2:8:2]
>>> print(list2)
[30, 50, 70]
>>> list3=list1[-2:-8:-2]
>>> print(list3)
[90, 70, 50]

Using for loop


For loop is used to iterate or read values from any iterable.

Syntax:
for variable in iterable:
statement-1
statement2

Example:
>>> list1=[10,20,30,40,50]
>>> for a in list1:
print(a)

10
20
30
40
50
>>> for i in range(len(list1)):
... print(list1[i])
10
20
30
40
50
Full Stack Python (Part-36)

Reading data from list using for loop


list1=[10,20,30,40,50,60,70,80,90,100]

# Add all the values of list


s=0
for x in list1:
s=s+x

print(f'Sum of {list1} is {s}')

# Find maximum value of list


max_value=list1[0]
for x in list1:
if x>max_value:
max_value=x

print(f'Maximum value of {list1} is {max_value}')

# Find Median

list1=[1,2,3,4,5]
a=len(list1)
if a%2!=0:
mid=len(list1)//2
print(f"Median {list1[mid]}")
else:
mid=len(list1)//2
print(f"Median {(list1[mid]+list1[mid-1])/2}")

# Find length of list without using len function


list1=[1,2,3,4,5,6,7,8]
c=0
for x in list1:
c=c+1
print(f'Length of {list1} is {c}')

# Find Output
list1=[10,20,30,40,50]
for x in list1[::-1]: # [50,40,30,20,10]
print(x,end=' ')

print()
# Find Output
list1=[10,20,30,40,50,60,70,80,90,100]
for x in list1[-5:]: # [60,70,80,90,100]
print(x,end=' ')
print()
for x in list1[:-5]: # [10,20,30,40,50]
print(x,end=' ')
print()
for x in list1[3:-3]: # [40,50,60,70]
print(x,end=' ')
print()
for x in list1[0]: # Error 10
print(x,end=' ')

Output:
Sum of [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] is 550
Maximum value of [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] is 100
Median 3
Length of [1, 2, 3, 4, 5, 6, 7, 8] is 8
50 40 30 20 10
60 70 80 90 100
10 20 30 40 50
40 50 60 70
Traceback (most recent call last):
File "E:/student drive/FSP7PM/test120.py", line 53, in <module>
for x in list1[0]: # Error 10
TypeError: 'int' object is not iterable
Iterator object
iter(iterable) this function receives iterable object and return iterator
object. This iterator object is used to read values from iterables.
__next__() this method read and return next value from iterable.

Example:
names_list=["naresh","ramesh","suresh","kishore"]
a=iter(names_list)
n1=a.__next__()
print(n1)
for n in a:
print(n,end=' ')

Output:
naresh
ramesh suresh kishore

Example:
>>> list1=[10,20,30,40,50]
>>> a=iter(list1)
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list2=list(a)
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list(range(10,110,10))
>>> print(list3)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list4=list("abc")
>>> print(list4)
['a', 'b', 'c']

Q: what is difference between iterator and iterable in python?


An Iterable is basically an object that any user can iterate over. An
Iterator is also an object that helps a user in iterating over another
object (that is iterable). We can generate an iterator when we pass the
object to the iter() method. We use the __next__() method for iterating.

enumerate object
enumerate(iterable,start=0), this function returns enumerate object.
Enumerate is also iterator object, which iterate value and count.

Example:
sales=[10000,20000,30000,40000,5000]
e=enumerate(sales,1999)
for x in e:
print(x)

names_list=["naresh","suresh","ramesh"]
a=enumerate(names_list,1)
for stud in a:
print(stud)

Output:
(1999, 10000)
(2000, 20000)
(2001, 30000)
(2002, 40000)
(2003, 5000)
(1, 'naresh')
(2, 'suresh')
(3, 'ramesh')

Mutable Operations of list


List is a mutable collection/iterable. It means after creating list object
changes can be done.
Full Stack Python (Part-37)
Mutable Operations of list
List is a mutable collection/iterable. It means after creating list object
changes can be done.

1. append(element/value)
This method add element/value at the end of list

Syntax: list-name.append(value)

Example:
>>> list1=[]
>>> print(list1)
[]
>>> list1.append(10)
>>> list1.append(20)
>>> list1.append(30)
>>> print(list1)
[10, 20, 30]
>>> list1.append(40)
>>> print(list1)
[10, 20, 30, 40]

Example:
# Write a program to append 5 values in list

list1=[] # empty list

for i in range(5): # start=0,stop=5,step=1 --> 0 1 2 3 4


value=int(input("Input integer value "))
list1.append(value)

print(list1)

Output:
Input integer value 10
Input integer value 20
Input integer value 30
Input integer value 40
Input integer value 50
[10, 20, 30, 40, 50]

Example:
# Write a program read scores of n players and display

scores=[]

n=int(input("How many players?"))

for i in range(n):
s=int(input("Enter Score "))
scores.append(s)

print(f'Scores {scores}')
print(f'Maximum Score {max(scores)}')
print(f'Minimum Score {min(scores)}')
print(f'Total Score {sum(scores)}')

Output:
How many players?4
Enter Score 10
Enter Score 50
Enter Score 20
Enter Score 40
Scores [10, 50, 20, 40]
Maximum Score 50
Minimum Score 10
Total Score 120

Example:
# Write a program to filter data

num_list=[2,8,1,2,9,5,11,15,17,18,21,89,34,56,87,23,32,37,87,56,45,34,2
3,12]
even_list=[]
odd_list=[]
for value in num_list:
if value%2==0:
even_list.append(value)
else:
odd_list.append(value)

print(f'Number List {num_list}')


print(f'Even numbers List {even_list}')
print(f'Odd numbers List {odd_list}')

Output:
Number List [2, 8, 1, 2, 9, 5, 11, 15, 17, 18, 21, 89, 34, 56, 87, 23, 32,
37, 87, 56, 45, 34, 23, 12]
Even numbers List [2, 8, 2, 18, 34, 56, 32, 56, 34, 12]
Odd numbers List [1, 9, 5, 11, 15, 17, 21, 89, 87, 23, 37, 87, 45, 23]

Example:
>>> list1=[]
>>> list1.append(10,20)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
list1.append(10,20)
TypeError: list.append() takes exactly one argument (2 given)

append() method is used to add one object or value.


In order to append more than one value or object python uses slicing
operator.

Syntax: list-name[len(list):]=iterable

Example:
>>> list1=[10,20,30]
>>> print(list1)
[10, 20, 30]
>> list1[3:]=40,50
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1[5:]=100,200,300
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300]
>>> list1[len(list1):]="NIT"
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300, 'N', 'I', 'T']
>>> list1[len(list1):]=[1,2,3,4,5]
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300, 'N', 'I', 'T', 1, 2, 3, 4, 5]
>>> list1[len(list1):]=range(-1,-6,-1)
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300, 'N', 'I', 'T', 1, 2, 3, 4, 5, -1, -2, -3, -4, -
5]

Replacing value/Updating value


Replacing values of list are done using,
1. index
2. slicing

using index one value is replaced


using slicing more than one value is replaced

Syntax1: list-name[index]=value
Syntax2: list-name[startindex:stopindex:step]=iterable

Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1[0]=99
print(list1)
>>> [99, 20, 30, 40, 50]
>>> list1[-1]=88
>>> print(list1)
[99, 20, 30, 40, 88]
>>> list1[2]=44
>>> print(list1)
[99, 20, 44, 40, 88]
>>> list1[5]=66
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
list1[5]=66
IndexError: list assignment index out of range
>>> list1[-5]=10
>>> print(list1)
[10, 20, 44, 40, 88]
>>> list1[-6]=100
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
list1[-6]=100
IndexError: list assignment index out of range

Example:
# Python program to interchange first and last elements in a list
# Input : [12, 35, 9, 56, 24]
# Output : [24, 35, 9, 56, 12]

list1=[12, 35, 9, 56, 24]

# 1st approch
x=list1[0]
list1[0]=list1[-1]
list1[-1]=x

print(f'After Swaping {list1}')

# 2nd approch
list1[0],list1[-1]=list1[-1],list1[0]
print(f'After Swaping {list1}')

Output:
After Swaping [24, 35, 9, 56, 12]
After Swaping [12, 35, 9, 56, 24]
Replacing more than one value

Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1[:2]=99,88
>>> print(list1)
[99, 88, 30, 40, 50]
>>> list1[2:]=1,2
>>> print(list1)
[99, 88, 1, 2]
>>> list1[2:]=1,2,3
>>> print(list1)
[99, 88, 1, 2, 3]
>>> list1[2:]=10,20,30,40,50,60,70,80,90,100
>>> print(list1)
[99, 88, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1[3:6]=11,22,33
>>> print(list1)
[99, 88, 10, 11, 22, 33, 50, 60, 70, 80, 90, 100]
>>> list1[-10::-1]=[1,2,3,4,5]
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
list1[-10::-1]=[1,2,3,4,5]
ValueError: attempt to assign sequence of size 5 to extended slice of size
3
>>> list1[-1:-4:-1]=1,2,3
>>> print(list1)
[99, 88, 10, 11, 22, 33, 50, 60, 70, 3, 2, 1]

Example:
# Given a list in Python and provided the positions of the elements, write
a program to swap the two elements in the list.
# Examples:
# Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
# Output : [19, 65, 23, 90]
# Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5
# Output : [1, 5, 3, 4, 2]

list1=[]
n=int(input("How many values ?"))
for i in range(n):
value=int(input("Enter any value "))
list1.append(value)
print(f'Before Swaping {list1}')
pos1=int(input("Enter Pos1 "))
pos2=int(input("Enter Pos2 "))
temp=list1[pos1-1]
list1[pos1-1]=list1[pos2-1]
list1[pos2-1]=temp

print(f'After Swaping {list1}')

Output:
How many values ?5
Enter any value 10
Enter any value 20
Enter any value 30
Enter any value 40
Enter any value 50
Before Swaping [10, 20, 30, 40, 50]
Enter Pos1 1
Enter Pos2 2
After Swaping [20, 10, 30, 40, 50]

Example:
# Reverse list in place
list1=[10,20,30,40,50]
print(list1)
list1[::]=list1[::-1] # [50,40,30,20,10]
print(list1)

list1=[10,20,30,40,50]
print(list1)
list1[:3]=list1[:-4:-1] # [50,40,30]
print(list1)

Output:
[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]
[10, 20, 30, 40, 50]
[50, 40, 30, 40, 50]
Example:
list1=[10,20,30,40,50]
i=0
for list1[i] in list1[::-1]:
i=i+1

print(list1)

list1=[10,20,30,40,50]
list2=[60,70,80,90,100]
list1[:3]=list2[:3]
print(list1)

Output
[50, 40, 30, 20, 10]
[60, 70, 80, 40, 50]

Example:
# Sorting list values using Bubble Sort

n=int(input("Enter how many values ?"))


list1=[]
for i in range(n):
value=int(input("Enter value "))
list1.append(value)

print(f'before sorting values {list1}')

for i in range(n):
for j in range(0,n-1): # 0 1 2 3
if list1[j]>list1[j+1]:
temp=list1[j]
list1[j]=list1[j+1]
list1[j+1]=temp

print(f'After sorting {list1}')


Output:
Enter how many values ?5
Enter value 5
Enter value 1
Enter value 3
Enter value 2
Enter value 4
before sorting values [5, 1, 3, 2, 4]
After sorting [1, 2, 3, 4, 5]
How to delete or remove values/elements from list?
For deleting elements or values from list, python provides the following
approaches.

1. Using del keyword


2. Using remove method
3. Using pop method
4. Using clear method

del keyword
“del” keyword is used to delete one or more than one value from list.
Del keyword required,
1. Index for deleting one value/element
2. Slicing for deleting more than one value/element

Syntax1: list-name[index]
Syntax2: list-name[start-index:stop-index:step]

Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> del list1[0]
>>> print(list1)
[20, 30, 40, 50]
>>> del list1[-2]
>>> print(list1)
[20, 30, 50]
>>> del list1[3]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
del list1[3]
IndexError: list assignment index out of range

index (ele,start,stop)
This return index of given element/value.
By defining start and stop value, it will search in slice notation.
>>> list1=[10,20,30,40,50,60,70]
>>> a=list1.index(40)
>>> print(a)
3
>>> a=list1.index(100)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a=list1.index(100)
ValueError: 100 is not in list
>>> list2=[10,20,30,40,50,10,20,30,40,50,10,20,30,40,50]
>>> a=list2.index(10,-10)
>>> print(a)
5

Example:
# Write a program to read n values into list
# remove given value from list

list1=[]
n=int(input("Enter how many values?"))
for i in range(n):
value=int(input("Enter value"))
list1.append(value)

print(f'Before deleting value {list1}')


value=int(input("Enter value to delete "))
if value in list1:
i=list1.index(value)
del list1[i]
print(f"{value} is deleted from list")
print(f'After deleting list is {list1}')
else:
print(f'{value} not exists within list')
Output:
Enter how many values?5
Enter value10
Enter value20
Enter value20
Enter value30
Enter value20
Before deleting value [10, 20, 20, 30, 20]
Enter value to delete 20
20 is deleted from list
After deleting list is [10, 20, 30, 20]

Example:
# Write a program to read n values into list
# remove given value from list

list1=[]
n=int(input("Enter how many values?"))
for i in range(n):
value=int(input("Enter value"))
list1.append(value)

print(f'Before deleting values {list1}')


value=int(input("Enter value to delete "))
found=False
while True:
if value in list1:
i=list1.index(value)
del list1[i]
found=True
else:
break

if found==True:
print(f'After deleting values {list1}')
else:
print(f'{value} not exists in list')
Output:
Enter how many values?5
Enter value10
Enter value10
Enter value20
Enter value30
Enter value20
Before deleting values [10, 10, 20, 30, 20]
Enter value to delete 10
After deleting values [20, 30, 20]

Syntax-2: del list-name[start-index:stop-index:step]


This syntax is used to delete more than one value/element from list.
This syntax uses multiple indexes from list.

>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list1[0:3]
>>> print(list1)
[40, 50, 60, 70, 80, 90, 100]
>>> del list1[-3:]
>>> print(list1)
[40, 50, 60, 70]
>>> del list1[1:-1]
>>> print(list1)
[40, 70]
>>> list2=list(range(10,110,10))
>>> print(list2)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list2[::2]
>>> print(list2)
[20, 40, 60, 80, 100]
>>> list3=list(range(10,110,10))
>>> print(list3)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list3[::-2]
>>> print(list3)
[10, 30, 50, 70, 90]

s.remove(x) remove the first item from s where s[i] is equal to x

Example:
>>> list1=[10,20,30,40,50,60,70,80,90,100]
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1.remove(10)
>>> print(list1)
[20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1.remove(90)
>>> print(list1)
[20, 30, 40, 50, 60, 70, 80, 100]
>>> list1.remove(10)
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
list1.remove(10)
ValueError: list.remove(x): x not in list
>>> list1=[10,10,10,20,20]
>>> list1.remove(10)
>>> print(list1)
[10, 10, 20, 20]

Remove multiple elements from a list in Python

# Remove elements which even numbers

list1=[4,9,2,3,5,1,11,13,17,23,8,12,16,18,20,22]

print(f'Before Deleting values {list1}')


i=0
l=len(list1)
while i<l:
if list1[i]%2==0:
del list1[i]
l=l-1
continue
i=i+1

print(f'After Deleting values {list1}')

Output:
Before Deleting values [4, 9, 2, 3, 5, 1, 11, 13, 17, 23, 8, 12, 16, 18, 20,
22]
After Deleting values [9, 3, 5, 1, 11, 13, 17, 23]
clear()
Empty the list or remove all the values or elements from list

Example:
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1.clear()
>>> print(list1)
[]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list1[:]
>>> print(list1)
[]

pop()
pop()
list can be used as a data structure called stack.
Stack is data structure which follows LIFO (Last In First Out). The
element/value added last is removed first.
Stack allows two operations
1. Push
2. Pop
Push is operation of adding/appending element
Pop is operation of removing and returning element

Example:
>>> list1=[]
>>> list1.append(10)
>>> list1.append(20)
>>> list1.append(30)
>>> print(list1)
[10, 20, 30]
>>> list1.pop()
30
>>> print(list1)
[10, 20]
>>> list1.pop()
20
>>> print(list1)
[10]
>>> list1.pop()
10
>>> print(list1)
[]
list1.pop()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
list1.pop()
IndexError: pop from empty list
>>> undo=[]
>>> undo.append("format")
>>> undo.append("inserting image")
>>> undo.append("inserting table")
>>> print(undo)
['format', 'inserting image', 'inserting table']
>>> undo.pop()
'inserting table'
>>> print(undo)
['format', 'inserting image']
>>> undo.pop()
'inserting image'
>>> print(undo)
['format']
>>> undo.pop()
'format'
>>> print(undo)
[]
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1.pop(2)
30
>>> print(list1)
[10, 20, 40, 50]

Implementing Queue Data structure using list


Queue data structure follows FIFO (First In First Out), the element added
first is removed first. Queue allows two operations
1. Adding à append()
2. Removing à del
Example:
Q=[]
while True:
print("1. Adding")
print("2. Removing")
print("3. Display")
print("4. Exit")
opt=int(input("Enter your option "))
if opt==1:
value=int(input("Enter any value"))
Q.append(value)
print(f'{value} added inside Q')
elif opt==2:
if len(Q)==0:
print("Queue is empty")
else:
value=Q[0]
del Q[0]
print(f'{value} deleted from Queue')
elif opt==3:
print(f'{Q}')
elif opt==4:
break
else:
print("invalid option")

Output:
1. Adding
2. Removing
3. Display
4. Exit
Enter your option 1
Enter any value10
10 added inside Q

extends s with the contents of t (for the most part


s.extend(t) or s += t
the same as s[len(s):len(s)] = t)

Example:
>>> list1=[]
>>> list1.append(10)
>>> print(list1)
[10]
>>> list1.append(20,30)
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
>>> list1.append(20,30)
TypeError: list.append() takes exactly one argument (2 given)
>>> list1.extend((20,30))
>>> print(list1)
[10, 20, 30]
>>> list1.extend([40,50,60])
>>> print(list1)
[10, 20, 30, 40, 50, 60]
>>> list1.extend("NIT")
>>> print(list1)
[10, 20, 30, 40, 50, 60, 'N', 'I', 'T']

inserts x into s at the index given by i (same


s.insert(i, x)
as s[i:i] = [x])

Example:
>>> list1=[10,20,30]
>>> print(list1)
[10, 20, 30]
>>> list1.insert(1,99)
>>> print(list1)
[10, 99, 20, 30]
>>> list1.insert(0,88)
>>> print(list1)
[88, 10, 99, 20, 30]
>>> list1.insert(-1,77)
>>> print(list1)
[88, 10, 99, 20, 77, 30]
>>> list1.insert(9,44)
>>> print(list1)
[88, 10, 99, 20, 77, 30, 44]
>>> list1.insert(-9,33)
>>> print(list1)
[33, 88, 10, 99, 20, 77, 30, 44]
>>> list1.insert(0,100,200)
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
list1.insert(0,100,200)
TypeError: insert expected 2 arguments, got 3

Example of inserting more than one value

>>> list2=[10,20,30]
>>> print(list2)
[10, 20, 30]
>>> list2[2:2]=[40,50,60]
>>> print(list2)
[10, 20, 40, 50, 60, 30]
>>> list2[1:1]=[11,22,33,44,55]
>>> print(list2)
[10, 11, 22, 33, 44, 55, 20, 40, 50, 60, 30]

s.reverse() reverses the items of s in place

>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1.reverse()
>>> print(list1)
[50, 40, 30, 20, 10]
>>> list2=[10,20,30,40,50]
>>> list3=list2[::-1]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> print(list3)
[50, 40, 30, 20, 10]

Creating copy of the collection or list or iterable

Creating copy is done using different methods


1. Shallow Copy
2. Deep Copy

Shallow Copy
s.copy() creates a shallow copy of s (same as s[:])
Shallow copy is called reference copy. In shallow copy a new list created
by copying address/references of objects found in original list.
Example:
>>> list1=[[10,20],30]
>>> list2=list1.copy()
>>> print(list1)
[[10, 20], 30]
>>> print(list2)
[[10, 20], 30]
>>> list1[0].append(40)
>>> print(list1)
[[10, 20, 40], 30]
>>> print(list2)
[[10, 20, 40], 30]
list2[0][0]=99
>>> print(list2)
[[99, 20, 40], 30]
>>> print(list1)
[[99, 20, 40], 30]
>>> list1[1]=88
>>> print(list1)
[[99, 20, 40], 88]
>>> print(list2)
[[99, 20, 40], 30]

copy module

copy module provides a function to perform deep copy.

copy.deepcopy(iterable)

This function returns copy of iterable.


copy is a default module which comes with python software.

>>> list1=[[10,20],30]
>>> print(list1)
[[10, 20], 30]
>>> import copy
>>> list2=copy.deepcopy(list1)
>>> print(list2)
[[10, 20], 30]
>>> list1[0].append(90)
>>> print(list1)
[[10, 20, 90], 30]
>>> print(list2)
[[10, 20], 30]
>>> list2[0][0]=99
>>> print(list2)
[[99, 20], 30]
>>> print(list1)
[[10, 20, 90], 30]
Full Stack Python (Part-40)

Nested List
Defining list as element inside list is called nested list (OR) defining list
inside list is called nested list.
Using nested list data can be organized in rows and columns (OR) nested
list can be used to represent matrix.

Syntax:
<list-name>=[[v1,v2,v3],[v1,v2],[v1,v2,v3,v4]]
Example:
list1=[[10,20,30],[40,50,60],[70,80,90]]
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[0][0],list1[0][1],list1[0][2])
print(list1[1][0],list1[1][1],list1[1][2])
print(list1[2][0],list1[2][1],list1[2][2])
print(list1[-1])
print(list1[-1][-1],list1[-1][-2],list1[-1][-3])
print(list1[-1][0],list1[-1][1],list1[-1][2])

Output:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
10 20 30
40 50 60
70 80 90
[70, 80, 90]
90 80 70
70 80 90
Example:
# Reading elements from nested list using index
list1=[[10,20,30],[40,50,60],[70,80,90]]
for i in range(3): # start=0,stop=3,step=1 --> 0 1 2
print(list1[i])

for i in range(3): # start=0,stop=3,step=1 --> 0 1 2


for j in range(3): # start=0,stop=3,step=1 --> 0 1 2
print(list1[i][j],end=' ')
print()

Output:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
10 20 30
40 50 60
70 80 90

Example:
# Reading elements from nested list without using index

list1=[[1,2,3],[4,5,6],[7,8,9]]

for x in list1:
print(x)

for x in list1:
for y in x:
print(y,end=' ')
print()

Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
123
456
789

Example:
# Creating nested list by input values at runtime (OR) create 2x2 matrix

matrix=[]

print("Enter elements of matrix")


for i in range(2):
row=[]
for j in range(2):
value=int(input("Enter value "))
row.append(value)

matrix.append(row)

print(matrix)

Output:
Enter elements of matrix
Enter value 1
Enter value 2
Enter value 3
Enter value 4
[[1, 2], [3, 4]]

Example:
# write a program to read marks for 3 students and 3 subjects (3x3)
stud=[]
print("enter marks of students")
for i in range(3):
marks=[]
for j in range(3):
m=int(input("Enter Marks "))
marks.append(m)
stud.append(marks)

print(stud)

Output:
enter marks of students
Enter Marks 50
Enter Marks 60
Enter Marks 70
Enter Marks 80
Enter Marks 90
Enter Marks 60
Enter Marks 40
Enter Marks 50
Enter Marks 60
[[50, 60, 70], [80, 90, 60], [40, 50, 60]]

Example:
# Write a program to add two matrices

matrix1=[]
matrix2=[]
matrix3=[]

print("Enter Elements of matrix1")


for i in range(2):
row=[]
for j in range(2):
value=int(input("Enter Value "))
row.append(value)
matrix1.append(row)

print("Enter Elements of matrix2")


for i in range(2):
row=[]
for j in range(2):
value=int(input("Enter Value "))
row.append(value)
matrix2.append(row)

for i in range(2):
row=[]
for j in range(2):
row.append(matrix1[i][j]+matrix2[i][j])
matrix3.append(row)

print(matrix1)
print(matrix2)
print(matrix3)

Output:
Enter Elements of matrix1
Enter Value 1
Enter Value 2
Enter Value 3
Enter Value 4
Enter Elements of matrix2
Enter Value 5
Enter Value 6
Enter Value 7
Enter Value 8
[[1, 2], [3, 4]]
[[5, 6], [7, 8]]
[[6, 8], [10, 12]]

Comprehension

Comprehensions in Python provide us with a short and concise way to


construct new sequences (such as lists, sets, dictionaries, etc.) using
previously defined sequences. Python supports the following 4 types of
comprehension:

● List Comprehensions
● Dictionary Comprehensions
● Set Comprehensions
● Generator Comprehensions

Comprehensions are a powerful and concise way to create and


manipulate lists , sets , and dictionaries .

List Comprehension
Creating list using comprehension

Syntax1: [expression/value for variable in iterable]


Syntax2: [expression/value for variable in iterable if test]
Example:
# Create List with 0 filled 100 values

list1=[0 for i in range(100)]


print(list1)

# Create List with Alphabets from A-Z

list2=[chr(value) for value in range(65,91)]


print(list2)

# Create List with Alphabets from a-z


list3=[chr(value) for value in range(97,123)]
print(list3)

namesList=["nk","ramesh","suresh","kishore"]
# Create copy of list by converting all the names in upper case
namesList1=[ name.upper() for name in namesList]
print(namesList)
print(namesList1)

Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
['nk', 'ramesh', 'suresh', 'kishore']
['NK', 'RAMESH', 'SURESH', 'KISHORE']

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy