You are on page 1of 230

Introduction to Languages

What is Language?

Language is a mediator between user and computer.

Language is a medium of communication between user and


computer.

Language is a software which provide set of predefined instructions


in order to communicate with computer.

Language is an interface to communicate with computer.

Types of Languages

1. Low Level Languages


2. High Level Languages

Low Level Languages

The languages which understand by computer are called low level


languages.

These low level languages are two types.

1. Machine Language
2. Assembly Language

Machine language is a collection of 0’s and 1’s. This language is


understand by computer. It does not required any translator.

Machine language is hardware dependent (OR) Machine language


is non portable.
Assembly language is a machine language which is not in 0’s and
1’s. It is collection of nemonics(verbs).

Assembly language uses a translator called assembler to translate


assembly language code into machine code.

The problem with low level languages are non portable (hardware
dependent).

High Level Programming Languages

All High level languages are english like, easy to understand. High
level languages are portable or hardware independent.

EG: C,C++,Java,Pythonl,C#.net,….

What is translator?

Translator is a software which is used to convert instructions written in


one language to another language.

Types of translator

1. Interpreter
2. Compiler
What is translator?

Translator is a software which is used to convert instructions written in


one language to another language.

Types of translator

1. Interpreter
2. Compiler

Interpreter

Interpreter is translator, which translates the instructions of one


language to another language.

Interpreter translate and execute line by line.


Interpreter perform the following operations.

1. Fetch/Reading
2. Syntax Verification
3. Translating
4. Executing
If there is an error in one line rest of the lines are not interpreted and
executed. It terminates the execution of program.

Compiler

Compiler is a translator which translates the instructions written in one


language to another language.
Compiler translate whole program and execute.
Compiler performs the following operations.
1. Read/Fetch
2. Syntax Verification
3. Translate
4. Store
5. Execute

If there is an error in one line it does not stop translating. It moves to


the next line and find all the errors.
Q: What Is difference between interpreter and compiler?

Interpreter Compiler

Interpreter translate and execute line by line.


Compiler translate whole program and
execute.
Interpreter does not store the translated code.
Compiler store the translate code into a file.
Interpreter has translate the program every time before execution.
Compiler stores because of this it can translate one
time and can executed number of times.
Interpreter shows only one error.
Compiler shows all the errors.
Interpreter is used for scripting languages.
Compiler is used by programming languages.

C ➔ Programming Language
C++ ➔ Programming Language
Java ➔ Programming Language
Python ➔ Programming Language
Scripting Language

Scripting language is one type of programming language. These are


used to write scripts.
Script is a small program which is executed inside another program.
Ex: JavaScript, VBScript, Shell Script, PHP,Perl,..

Automation Purpose ➔ scripting language is used.

Q: What is difference between Programming language and scripting


language?
Scripting Language

Scripting language is one type of programming language. These are


used to write scripts.
Script is a small program which is executed inside another program.
Ex: JavaScript, VBScript, Shell Script, PHP,Perl,..

Automation Purpose ➔ scripting language is used.

Q: What is difference between Programming language and scripting


language?

Programming Languages Scripting Languages

C,C++,Java,Python are programming Languages.

JavaScript,VBScript,Perl,PHP are scripting languages.

The programs developed using programming languages are


executed individual or independently.

The programs developed using scripting languages


are not executed individually or independently.

Programming languages uses compilers.

Scripting languages uses interpreter for translation.

Statically typed languages.

Dynamically typed languages.


AWS +Python

DevOPS ➔ Docker ➔ Software ➔ scripts ➔ Scripting language

Selenium ➔ Testing Tool ➔ software ➔ scripts ➔ Scripting Languages

What is programming paradigm?

A programming paradigm define set of rules and regulations for


organization of data and instructions.

1. Monolithic Programming/Unstructured Programming


2. Procedural Oriented Programming
3. Modular Oriented Programming
4. Object Oriented Programming
5. Functional Programming

Q: What is program?

A program set of data and instructions.

Programming elements are two,

1. Data
2. Instructions

Q: What is programming?

Organizing of data and instructions according to given problem.


Introduction to Python

What is python?

Python is a programming language.

Python is a general purpose programming language. A


programming language which is used for developing any type of
application or software is called general purpose or multipurpose
programming language.

Python is a high level programming language. All high level


languages are in english and hardware independent.

Python is multiparadigm programming language. In python we can


write programs using difference programming concepts or
approaches.

Python is programming language and having some of the features


of scripting language.

Python is a general purpose, multiparadigm and high level


programming language.

Purpose based languages ➔ Cobol (Business Applications for IBM)

PASCAL(Scientific Applications)

Fortran (Mathematical Applications)

R (Statistics)
Python Features

1. Easy : Python is easy.


a. Easy to learn
b. Easy to code/program
Python is easy to lean because, it is high level programming
language. All high level languages are english like.
Python is easy to code because, it is having simple syntax
compare to other programming languages.
1. Statements in python not end with ;
2. There is curly braces { } for defining blocks.
3. Less coding
2. Large Number of Libraries

What is library?

Library is a set of predefined programs/functions/components. These


libraries are also called API(Application Programming Interface).

Python community provide large number of libraries.


1. Windows based or GUI applications : Tkinter,
WxPython,Kivy,PyQT,PySide.
2. Web Applications : Django,Flask, Pyramid,Bottle,TurboGears are
called Frameworks. Framework is a collection of libraries and it
define the architecture of developing and executing
applications.
3. Machine Learning : TernsorFlow,Keras,PyTorch,Scikit
4. DataScience : Pandas,Numpy,SciPy,Plotly
5. Image Processing :OpenCV,Scikit_image,Pillow
6. WebScrping : Beautiful Soap,scrappy
7. Automation Testing : PyUnit,PyTest
8. Cloud Computing
9. IOT

www.pypi.org ➔ python package index (repository) or the place


where all python libraries are exists.
3. Free and Open Source

Python is free to download. This software can be downloaded from


www.python.org

Q: What is open source?


Open source code to the public.
Q: What is source code/program?
A program written in any high level language is source program.
Ex: The programs written in C,C++,Java,Python,…

Open source technologies provide source code of that software


open to the public.
Using open source technologies, we can develop new technologies
by adding some features to existing technologies. Allows to develop
new frameworks or integrated with existing technologies.
4. Extensible and Embeddable
Python is embeddable, other languages allows to use python code.
Python is extensible, with in python we can use code of other
programming languages(C,Java,.Net,…)
5. Dynamically Typed Language
Dynamically typed languages allows to create variables or
memory without specifying data type. In python data type is
taken care at runtime. This feature allows to use one variable to
assign multiple types of values. Programmer does not think
about syntax of creating variables and allocating memory.
6. Portable or Cross Platform

Python is a portable language, portability allows to develop and run


python applications on different operating system. Python is also
platform independent language. The compiled code of python can
be moved to different operating systems and execute.
Python History

Python laid its foundation in the late 1980’s


The implementation of python was started in December 1989 by
Gudio Van Rossum at CWI in Netherlands.
In February 1991, the first python source code is published.
The name python is taken from one popular comic serial which
broadcasted in BBC in 1980’s called “Monty Python Flying Circus”.
Python is a language which is derived from two languages.
1. ABC
2. Modula-3
Gudio Van Rossum was program of ABC language. This language is
used to develop an operating system called Amoeba.

Python Versions

Versions are changes done in the language.


1. Language Changes
2. Library Changes

Python 3.7 Library Changes


= assignment operator sys module/lib
Python 3.8 x()
:= walrus operator y()
z()
Alpha Version ➔ partly implemented features
Beta Version ➔ fully implemented features with bugs/errors
Final Version ➔ complete version/fully implemented without any
bugs or errors

1.0 ➔ version number/major version number


2.0 ➔ version number/major version number
2.1➔ version number/major version
3.0➔ version number/major version number
3.0.1
3.0.2
3.1 ➔ version number/major version
3.1.1 ➔ minor version
3.2 ➔ version number/major version

If there is major changes they release with major number.

Stable Version(LTS)
Un-Stable Version

Python Language

Python 2.x Python 3.x

Python language comes with two different versions.


What is difference between python 2.x and python 3.x?

Python 2.x Python 3.x

1. print is a statement in python 2.x


ex: print “Hello World”
print is a function in python 3.x
ex: print(“Hello World”)
2. int,long datatypes are supported in this version.
There is no long datatype, there is only int
3. xrange() is used to create range of values.
range() is to generate to range of values.

Current version of python is 3.9

Python implementations

Cpython : CPython is the reference implementation of the Python


programming language. Written in C and Python, CPython is the
default and most widely used implementation of the language.
CPython can be defined as both an interpreter and a compiler as it
compiles Python code into bytecode before interpreting it.

Python Program ➔ compiler ➔ bytecode ➔ pvm(interpreter)

Jython (Python running on the Java Virtual Machine)


Python implementation of java language.

Python program ➔ compiler ➔ bytecode ➔ jvm(java virtual


machine)
IronPython (Python running on .NET)
Python implementation of .net framework
Python program ➔ compiler ➔ MSIL ➔ CLR(Common Language
Runtime)

PyPy (A fast python implementation with a JIT compiler)


Stackless Python (Branch of CPython supporting microthreads)
MicroPython (Python running on micro controllers)

Python Distributions

Other parties have re-packaged CPython. These re-packagings


often include more libraries or are specialized for a particular
application:

▪ Anaconda Python (a full Python distribution for data


management, analysis and visualization of large data sets)
▪ 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 IDE’s

Q: What is IDE?

IDE stands for Integrated Development Environment.


IDE is code editor or software which provide development and
execution environments.

1. IDLE (Integrated Development Learning Environment) default


editor which comes with python software.
2. PyCharm is a python ide which will provide good environment
for developing web applications and python standalone
applications.
3. PyDev is a python is used to execute python programs in
eclipse. PyDev is plugin.

4. Jupyter notebook : The Jupyter Notebook is an open-source


web application that allows you to create and share
documents that contain live code, equations, visualizations
and narrative text. Uses include: data cleaning and
transformation, numerical simulation, statistical modeling, data
visualization, machine learning, and much more.

5. Google Colab : Colaboratory, or "Colab" for short, allows you to


write and execute Python in your browser, with

• Zero configuration required


• Free access to GPUs
• Easy sharing

Whether you're a student, a data scientist or an AI researcher,


Colab can make your work easier.
6. Spyder : Spyder is a powerful scientific environment written in
Python, for Python, and designed by and for scientists,
engineers and data analysts. It features a unique combination
of the advanced editing, analysis, debugging, and profiling
functionality of a comprehensive development tool with the
data exploration, interactive execution, deep inspection, and
beautiful visualization capabilities of a scientific package.

Python Ide’s for Andoriod or Apps

1. Pydroid 3
2. Sololearn
3. Python for android
4. Qpython

Python for IOS


1. Pythonista

Python Software ➔ Python compiler,Python interpreter,Lib


Python Distribution ➔ Python Software+Extra Lib
Python IDE ➔ Code Editor
Installing python software

1. Download python software from www.python.org


2.
Python software provide the following things.

1. IDLE : This default IDE/Editor which comes with python


software.
2. Lib : python libraries are called modules and packages.
A module is a python program which contain set of
predefined functions. A package is collection of modules.
3. PIP tool : python package installer. Using this tool we can
install and uninstall libraries
4. Python Shell : Python shell allows to work in interactive mode.

How to work with Python?

1. Open IDLE (GUI/Windows)


a. Search for Python IDLE 3.9.0
Programmer can work with python in 2 modes.

1. Interactive Mode
2. Scripting Mode/Programming Mode

Interactive Mode

In interactive mode your work with python shell. Python shell is a tool
or a program which receive the commands given at prompt and
interpret and give the result.

In interactive mode we give the command at the prompt(>>>),


which is called chevron prompt. It is also called command line
interface. Where we type the commands and these commands are
interpreted and executed python shell.

>>>

help: This will provide help or documentation of any object related


with python.

Ex: >>> help(“modules”)

>>> help(“os”)

>>>help(“while”)

>>>help(“print”)

>>> print("hello")

hello
Scripting Mode

In scripting mode we write a python program and save with ext .py.
This scripting mode also called programming mode.

File menu ➔ new File

print("Hello World")
print("Welcome to python")
print("This is my first program in python")

File menu ➔ Save ➔ py1.py


Run Menu ➔ Run Module(F5)

Writing python program in notepad and executing in command


prompt.
Character set of python

Python is a universal language. It support characters available in


different languages. Python uses two encoding standards.

1. ASCII
2. UNICODE

ASCII stands for American Standard Code for Information


Interchange. ASCII support 256 character which include alphabets in
english(A-Z,a-z),digits(0-9) and special characters. It does support
characters in other languages.

UNICode stands for universal code is another encoding standard


which support 65536 characters, which include alphabets in different
languages.

>>> name="naresh"
>>> name
'naresh'
>>> x=100
>>> x
100
>>> name="नरे श"
>>> name
'नरे श'
>>>
>>> name="నరేశ్"
>>> name
'నరేశ్'
>>>

Unicode character set is super set of ascii code.

Tokens

A token is smallest individual unit within program. A token set of


characters. Without tokens we cannot write a statement or program.

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

Keywords

Keywords are called reserved words. Keywords are language related


words and special meaning within language. These words cannot
used as user defined words/identifiers. Every keyword is one
command having syntax.
35 keywords are exists in python.
>>> import keyword
>>> keyword.kwlist

Keyword is a predefined library in python.


Import is keyword which is used to import module.
In keyword module there is a list whose name is kwlist, this contain all
keywords supported by python.

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

>>> len(keyword.kwlist)
35

Identifiers

Identifier is a user defined word. Which is used to identify


programming elements or constructs. Identifier is a collection of
alphabets,digits and allows only special character _
Eg: variable name, function name, class name, module name,
package name.
Identifiers

Identifier is a user defined word. Which is used to identify


programming elements or constructs. Identifier is a collection of
alphabets,digits and allows only special character _

Eg: variable name, function name, class name, module name,


package name.

Rules
1. Identifier should not be a keyword
Example:
>>> from=100
SyntaxError: invalid syntax
>>> x=100
>>> y=200
>>> base=1.5
>>> break=1
SyntaxError: invalid syntax
2. Identifier should not start with digit.
>>> no1=100
>>> no2=200
>>> 3no=300
SyntaxError: invalid syntax
3. There should not be any space in identifier
>>> account number=101
SyntaxError: invalid syntax
>>> student rollno=1
SyntaxError: invalid syntax
>>> account_number=101
>>> student_rollno=102
4. It allows only one special character _, This _ should be a prefix
or in between or suffix
>>> _no1=100
>>> no1_=200
>>> no_1=300
>>> _no1
100
>>> no1_
200
>>> no_1
300
>>> _=400
>>> _
400
>>> __=500
>>> _no_=600
>>> __
500
>>> _no_
600
5. There is no restriction of length of identifier. Preferred length is 8
or 16.
>>>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaa=100
>>>
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbb=200
>>>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaa
100
>>>
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbb
200
6. Identifier can be in uppercase or lowercase. Python case
sensitive language it finds the difference between uppercase
and lowercase.
>>> A=100
>>> a=200
>>> A
100
>>> a
200
>>> ROLLNO=1
>>> rollno=2
>>> ROLLNO
1
>>> rollno
2

Data types

Data types are used to reserve memory for data.


Python data types are classified into different categories.

1. Standard Data types


a. int
b. float
c. complex
d. bool
2. Collection Data types or Data Structures
a. Sequence Data types
i. List
ii. Tuple
iii. String
iv. Range
v. Bytes
vi. Bytesarray
b. Non Sequence Datatypes
i. Set
ii. Frozenset
iii. Dictionary

Python is a object oriented programming language. Object


oriented is a programming paradigm. In object oriented
application development data is represented as objects.
An object is real world entity. Every object is having two
characteristics.
1. Properties
2. Behavior
Properties define the state of the object and behavior defines
functionality of object.
Every data type in python is a class and instances are object.
Class allocates memory for object.
Class is a blueprint of object.
Class defines properties and behavior of object.
Class defines the structure of object.

int

This data type is used to reserve memory of integer value.


int is predefined class which is exists in built-ins module. This is a
default module imported any python application of program.
A numeric value which does not have decimal point.

Q: What is variable?
A variable is named memory location.
A variable is identifier which is used to identity value/object.
In python memory is allocated or reserved by creating variables.
In python variables are created by assigning value.
In python memory is reserved by assigning value to variable.
In python variables are reference type, which does not hold value it
hold address.
This variables are dynamic in type.

Integer variable is created by assigning integer value.

Ex:
>>> n1=100
>>> n1
100
>>> n2=200
>>> n2
200
>>> type(n1)
<class 'int'>
>>> type(n2)
<class 'int'>

type() function

it is a predefined function in python, which return type of variable


(OR) type of object hold by variable.

Id() function

Every object is having an identity (address). To find an address of


object we use id() function.

>>> n1=100
>>> n1
100
>>> n2=200
>>> n2
200
>>> type(n1)
<class 'int'>
>>> type(n2)
<class 'int'>
>>> id(n1)
1494265312
>>> id(n2)
1494266912
int is an immutable data type. A data type which does not allows to
modify value after creating object.
An object whose state/value cannot be changed is called
immutable object or class.

Integers are immutable they can be shared ( object pooling )


Ex:
>>> x=100
>>> y=200
>>> z=100
>>> id(x)
1494265312
>>> id(y)
1494266912
>>> id(z)
1494265312
Size of integer data type is unlimited length. Memory is allocated
dynamically. The memory is reserved based one value.

>>> num1=999999999999999999999999999999999999999999999999
>>> num1
999999999999999999999999999999999999999999999999
>>>
num2=999999999999999999999999999999999999999999999999999999
999999999999999999999999
>>> num2
999999999999999999999999999999999999999999999999999999999999
999999999999999999
>>>
float

float is a standard data type in python.


This data type is used allocate memory for float value or real
numbers.
A numeric value which is having decimal point is called float value
(OR) a number with decimal point or precision is called float number.
float is a predefined class which is exists in built-ins module.
float variable is created by assigning float value.
float value is represented in two formats.
1. Standard format
2. Expo format
float is constant or immutable, which cannot modified after creating
object. Because of immutability they can be shared.
Example
>>> n1=1.5
>>> type(n1)
<class 'float'>
>>> n2=2.5
>>> type(n2)
<class 'float'>
>>> n1
1.5
>>> n2
2.5
>>> n3=14e-1
>>> n3
1.4
>>> type(n3)
<class 'float'>
>>> 1.4e2
140.0
>>> n4=1.4e4
>>> n4
14000.0
>>> type(n4)
<class 'float'>
The value “e” is 10

x.py
x=1.5
y=1.5
print(id(x))
print(id(y))

>>> n1=200
>>> n2=200
>>> id(n1)
527528321680
>>> id(n2)
527528321680
>>> n3=257
>>> n4=257
>>> id(n3)
527572892784
>>> id(n4)
527572892720
>>> x=256
>>> y=256
>>> id(x)
730607020432
>>> id(y)
730607020432

>>>
complex

complex is a standard datatype.


This datatype is used to allocate memory for complex number.
Complex number consist of two values 1. Real 2. Imag
Complex number is constant whose value is never changed (OR)
complex is an immutable data type.
Complex number is created with the following syntax.
real+imagj ➔ imag value is suffix with j
complex is a name of the class. This class is exists in built-ins module.

>>> comp1=1+2j
>>> comp2=1+4j
>>> comp1
(1+2j)
>>> comp2
(1+4j)
>>> type(comp1)
<class 'complex'>
>>> type(comp2)
<class 'complex'>
>>> comp1.real (. Is called member access operator)
1.0
>>> comp1.imag
2.0
>>> comp2.real
1.0
>>> comp2.imag
4.0
>>>
>>> c1=1+2j+3k
SyntaxError: invalid syntax
>>> c1=1+2i
SyntaxError: invalid syntax
>>>
>>> comp1.real=2.0
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
comp1.real=2.0
AttributeError: readonly attribute
>>> c1=2j
>>> c1.real
0.0
>>> c1.imag
2.0
>>> c2=1+2j+3j
>>> c2
(1+5j)
>>>

Python Shell
>>> c3=1+2j
>>> c4=1+2j
>>> id(c3)
730654438448
>>> id(c4)
730654438736
>>>
Pogramming Mode/Scripting Mode
c1=1+2j
c2=1+2j
print(id(c1))
print(id(c2))

Output:
4342971440
4342971440

Note: int, float, complex all these data types sizes are unlimited
length.
bool

bool is a standard data type.


This datatype is used to represent Boolean values.
These Boolean values are represented using two keywords.
1. True
2. False

101 4000.0 True


102 4000.0 False

bool is a name of the class.


>>> b1=True
>>> b2=False
>>> b1
True
>>> b2
False
>>> x=0
>>> y=1
>>> type(x)
<class 'int'>
>>> type(y)
<class 'int'>
>>> type(b1)
<class 'bool'>
>>> type(b2)
<class 'bool'>
>>>

>>> id(b2)
140714985945224
>>> z=True
>>> id(z)
140714985945192
>>>

Booleans are immutable, because of immutability they can be


shared.

str

string is a collection of characters. These characters can be


alphabets,digits or special characters. This string which contain only
alphabets are alphabetic string. This string which contain
alphabets,digits or special characters is called alphanumeric string.

String is sequence data type or string is an iterable.


String object is created using str class. String is an immutable after
creating string we cannot modify characters or string.

How to represent string object?

In python string is represented in 3 types.

1. Within single quotes ‘ ‘


2. Within double quotes “ “
3. Within triple quotes ‘’’ ‘’’ or “”” “””

Name1=”naresh”
Name2=’naresh’
Name3=’’’naresh’’’
Name4=”””naresh”””
>>> name1="naresh"
>>> name2='naresh'
>>> name3='''naresh'''
>>> name4="""naresh"""
>>> type(name1)
<class 'str'>
>>> type(name2)
<class 'str'>
>>> type(name3)
<class 'str'>
>>> type(name4)
<class 'str'>
>>> name1
'naresh'
>>> name2
'naresh'
>>> name3
'naresh'
>>> name4
'naresh'
>>>
1. Within single quotes ‘ ‘
2. Within double quotes “ “
3. Within triple quotes ‘’’ ‘’’ or “”” “””
Within single quotes we can embed double quotes.
With in double quotes we can embed single quotes
Within three single quotes we can embed double quotes
Within three double quotes we can embed single quotes

comedy_series= “Monty Python's Flying Circus “


python_feature= ‘Python is a “OOP” language’

Three single and double quotes are used to represent multiline string.

python_defination=’’’ python is general purpose


programming language, python is oop programming language,
python is high level language’’’

python_history=”””Monty Python's Flying Circus is a British surreal


sketch comedy series created by and starring the comedy group
Monty Python, consisting of Graham Chapman”””

>>> s1='pythoon is a
SyntaxError: EOL while scanning string literal
>>> s2="python is a
SyntaxError: EOL while scanning string literal
>>> s3='''python is a
programming langauge'''
>>> s3="""python is a programming
Language"""
>>>
Escape Sequences
\’ Single quotes
\” Double quotes
\\ \ character
\n new line
\t tab space
\v vertical table space

>>> str1="python is developed by \"Gudio Van Rossum \""


>>> str1
'python is developed by "Gudio Van Rossum "'
>>> print(str1)
python is developed by "Gudio Van Rossum "
>>>
>>> str2='python is \'OOP\' language'
>>> print(str2)
python is 'OOP' language
>>>
>>> str4="python\nis\na\nhigh level\nlangauge"
>>> str4
'python\nis\na\nhigh level\nlangauge'
>>> print(str4)
python
is
a
high level
langauge
>>>
Q: What is program?
A program is collection of data and instructions.
Every program required input, process and output.
Input is the data or information given to the program.
Process is doing calculations or applying some logic.
Output is the result given by program.
Programming elements are two,
1. Data
2. Instructions
Every program in python is called module. Every python program is
given extension .py

.py ➔ Python Source Program


.pyc ➔ Python compiled Program (ByteCode)
.pyo ➔ Python optimized code
.pyd ➔ Python DLL(Dynamic Linked Lib)
.ipynb ➔ Python Notebook
.pyw ➔ Python file in window mode
.pyz ➔ Python zip file
print()

print function is used to print values on standard output(stdout)


monitor.
Print is inbuilt function or predefined function exists in built-ins module.
Print function is having 5 arguments.
1. Value
2. Sep
3. End
4. File
5. Flush

Value argument receives 0 or more values.


Sep : the default separator is space, print function uses separator
when it receives more than one value. The value which is inserted
between more than one value.
End: The default end value is \n, after printing all the value insert
new line.

print(10,20,30,40,50) ➔ 10 20 30 40 50\n
print(10) ➔ 10\n
print() ➔ \n
Only for reference or internal logic of print or custom print function

import sys
def display(*value,sep=' ',end='\n',file=sys.stdout,flush=False):
str1=''
if len(value)==0:
file.write(end)
if len(value)==1:
str1=str1+str(value[0])+end
file.write(str1)
if len(value)>1:
value1=[str(v) for v in value]
str1=sep.join(value1)
str1=str1+end
file.write(str1)

display()
display(10)
display(10,20,30,40,50)
display(100,200,300,400,500,600,700,800)
# printing values inside userdefined file

f=open("d:\\output","w")
print("Hello Python",file=f,flush=True)
print("Hello Java")
print("Hello ML",file=f,flush=True)
print("Hello DS")

Buffer and Flush

# Find outputs

print(10,20,30,40,50,sep=',')
print(10,20,30,40,50)
print(10,20,30,40,50,sep='\n')
n1=100
n2=200
n3=300
print(n1,n2,n3,sep='\n')
print(100,200,300,end=",",sep="\n")
print("Hello")

# find outputs

print(10,20,end=':') # 10 20:python 3.9


print("python",3.9) # programming language
print("programming language")

#Find output

print(10,end=',')
print(20,end=',')
print(30)

Find output
print(100,200,300,end=",",sep="\n")
print("Hello")
input()

input() is a predefined function in python. This function is exists inside


built-ins module.
Input function is introduced in python 3.x version

input(prompt=None, /)
Read a string from standard input(keyboard).

>>> x=input()
100
>>> x
'100'
>>> type(x)
<class 'str'>
>>> x=input("Sohel please enter value")
Sohel please enter value100
>>> x
'100'
>>> x=input("enter x value:")
enter x value:100
>>> user=input("UserName :")
UserName :nit

Prompt is a string which is displayed before reading value. It prompts


the end user which values have to be entered.
n1=input("Enter n1 value")
n2=input("Enter n2 value")
print(n1,n2)
print(type(n1),type(n2))

Output:
Enter n1 value10
Enter n2 value20
10 20
<class 'str'> <class 'str'>
>>> x="10"
>>> y="25"
>>> x+y
'1025'
>>> n1=10
>>> n2=20
>>> n1+n2
30
>>>

int class or type


this class is used to constructor or creating integer object using three
types of values.
1. Integer value
2. Float value
3. String value
Note: this type is used to convert other values to integer type.

int() ➔ int is a class and () indicates a function/constructor which


receive value and construct object.
Number System

Number system or numerical system is way of representing numbers.


There are 4 number systems.
1. Decimal Number
2. Octal Number
3. Hexa Deciaml Number
4. Binary Number
1. Decimal number : A numeric value with base 10 is called
decimal number. This number consist of digits from 0-9. This
number is not prefix any special character. It prefix with + or –
Eg:
N1=65
N2=+75
N3=-85
2. Octal number: A numberic value with base 8 is called octal
number. This number consist of digits from 0-7. This number is
prefix with 0o or 0O.
Number System

Number system or numerical system is way of representing numbers.


There are 4 number systems.
1. Decimal Number
2. Octal Number
3. Hexa Decimal Number
4. Binary Number
1. Decimal number : A numeric value with base 10 is called
decimal number. This number consist of digits from 0-9. This
number is not prefix any special character. It prefix with + or –
Eg:
N1=65
N2=+75
N3=-85
2. Octal number: A numeric value with base 8 is called octal
number. This number consist of digits from 0-7. This number is
prefix with 0o or 0O.
Eg:
N1=0o12
N2=0o45

3. HexaDecimal number: A numeric value with base 16 is called


hexa decimal number. This number consist of digits from 0-9
and a-f. This number is prefix with 0x or 0X.
Larger numeric values are represented in hexa decimal format.
Eg: memory address, colors
Eg: n1=0x123
n2=0xab

4. Binary Number : A numeric value with base 2 is called binary


number. This number consist of two digits 0’s and 1’s. binary
number is prefix with 0b or 0B.
Eg: Computer Organization(Logical Gates)

>>> a=65
>>> type(a)
<class 'int'>
>>> a
65
>>> b=0o45
>>> type(b)
<class 'int'>
>>> b
37
>>> oct(b)
'0o45'
>>> c=0xa
>>> type(c)
<class 'int'>
>>> c
10
>>> hex(c)
'0xa'
>>> d=0b101
>>> type(d)
<class 'int'>
>>> d
5
>>> bin(d)
'0b101'
>>>
Syntax1:
Int([x])
X is value is not defined, the default value of x is 0
X value can be integer(decimal,octal,hexa,binary), float
Syntax2:
Int(str,base=10)
String required integer value with base of 10. If string not
having integer with base 10, we need to define the base value of
integer represented within string.
Without type we can create integer with integer value.
Eg: n1=65
n2=0o45
n3=0xab
n4=0b1010
With type we can create integer with different types of values.
Eg:
n1=int(1.5) # creating integer with float value
n2=int(“65”) # creating integer with string value contain
integer with base 10
n3=int(“0o45”) # error
n4=int(“0o45”,base=8)
n5=int(“0xab”) # error
n6=int(“0xab”,base=16)
n7=int(“0b101”) # error
n8=int(“0b101”,base=2)

# write a program to add two integers


a=input("enter first number")
b=input("enter second number")
print(type(a),type(b))
c=a+b
print(a,b,c)
n1=int(a)
n2=int(b)
n3=n1+n2
print(n1,n2,n3)
# Write program to input two hexa decimal and add
a=input("enter first hexa decimal number")
b=input("enter second hexa decimal number")
c=a+b
print(a,b,c)
print(type(a),type(b),type(c))
n1=int(a,base=16)
n2=int(b,base=16)
n3=n1+n2
print(hex(n1),hex(n2),hex(n3))
Example
x="0xa"
y="0xb"
n1=int(x,base=16)
n2=int(y,base=16)
n3=n1+n2
print(n1,n2,n3)
# write a program to input two binary integers and add
a=input("enter first binary number")
b=input("enter second binary number")
c=a+b
print(a,b,c)
n1=int(a,base=2)
n2=int(b,base=2)
n3=n1+n2
print(n1,n2,n3)
print(bin(n1),bin(n2),bin(n3))
# write a program to add two numbers
a=input("enter first number")
b=input("enter second number")
c=a+b
print(a,b,c)
n1=int(a)
n2=int(b)
n3=n1+n2
print(n1,n2,n3)
# write a program to add two numbers
a=int(input("enter first number"))
b=int(input("enter second number"))
c=a+b
print(a,b,c)

>>> x=int("1.5")
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
x=int("1.5")
ValueError: invalid literal for int() with base 10: '1.5'
>>> y=int(1.5)
>>> y
1
>>>
float() type

this type is used to construct float object. It allows to create float


object in two ways.
1. Float and integer
2. Float value represented as string/String which contain float
value.
Example

n1="1.2" # float value of type string


n2="15" # int value of type string
f1=float(n1) # converting type string to float
f2=float(n2) # converting type string to float
print(type(n1),type(n2),type(f1),type(f2))
print(n1,n2,f1,f2)
n3=n1+n2
f3=f1+f2
print(n3)
print(f3)

Example
f1=float(1.5) # constructing float using float value
f2=float(25) # constructing float using int value
print(f1,f2)
Example
f1=float("1.5") # converting string to float(standard format)
f2=float("1.5e1") # converting string to float(expo format)
print(f1,f2)
# write a program to add two float numbers
n1=float(input("Enter first float number"))
n2=float(input("Enter second float number"))
n3=n1+n2
print(n3)
# write a program to find area of triangle
base=float(input("enter base"))
height=float(input("enter height"))
area=0.5*base*height
print("area is ",area)

complex() type
This type is used to construct complex number. It allows to create
complex number using different types of values.
1. Using real and imag of type float or integer
2. Using string

Example of code converting string to complex number

c1="1+2j" # complex number represented as string type


c2="2+3j" # complex number represented as string type
c3=c1+c2
print(c1,c2,c3,sep='\n')
comp1=complex(c1) # converting complex number represented as
string to complex
comp2=complex(c2) # converting string to complex type
comp3=comp1+comp2
print(comp1,comp2,comp3,sep='\n')

c1="1"
comp4=complex(c1) # create complex number using real value of
type string
print(comp4)
c2="2j"
comp5=complex(c2) # create complex number using imag value of
type string
print(comp5)
c3="1+3j"
comp6=complex(c3) # create complex number using both real and
imag
print(comp6)

Converting other types to complex number


x=1 # integer type
y=2 # integer type
comp1=complex(x,y)
print(comp1)
p=1.2
q=2.5
comp2=complex(p,q)
print(comp2)
print(comp2.real,comp2.imag)
# write a program to add two complex numbers
print("Enter first complex number")
real1=float(input("Enter real value"))
imag1=float(input("Enter imag value"))
print("Enter second complex number")
real2=float(input("Enter real value"))
imag2=float(input("Enter imag value"))
comp1=complex(real1,imag1)
comp2=complex(real2,imag2)
comp3=comp1+comp2
print(comp1,comp2,comp3,sep='\n')
Output
Enter first complex number
Enter real value1.2
Enter imag value1.0
Enter second complex number
Enter real value1.4
Enter imag value1.1
(1.2+1j)
(1.4+1.1j)
(2.5999999999999996+2.1j)

# write a program to add two complex numbers


comp1=complex(input("Enter complex number1"))
comp2=complex(input("Enter complex number2"))
comp3=comp1+comp2
print(comp1,comp2,comp3,sep='\n')
Output:
Enter complex number11+2j
Enter complex number21+3j
(1+2j)
(1+3j)
(2+5j)

bool() datatype
This data type is used to construct Boolean objects. It allows to
create Boolean object using integers.

>>> b1=bool(1)
>>> b2=bool(0)
>>> b1
True
>>> b2
False
>>> b3=bool(100)
>>> b3
True
>>> b4=bool(45)
>>> b4
True
>>> b5=bool(0)
>>> b5
False
>>> b6=bool(True)
>>> b7=bool(False)
>>> b6
True
>>> b7
False
>>> b8=bool("True")
>>> b8
True
>>> b9=bool("False")
>>> b9
True
>>> b10=bool("a")
>>> b10
True
>>>

str() type

This type is used to construct string object using other types (OR)
converting other types to string.

Example
x=10
y=20
z=x+y
print(x,y,z)
s1=str(x) # converting integer to string
s2=str(y) # converting integer to string
s3=s1+s2
print(s1,s2,s3)

f1=1.5
f2=2.5
f3=f1+f2
print(f1,f2,f3,sep='\n')
s4=str(f1) # converting float to string
s5=str(f2) # converting float to string
s6=s4+s5
print(s4,s5,s6)
c1=1+2j
c2=2+3j
c3=c1+c2
print(c1,c2,c3)
s7=str(c1) # converting complex number to string
s8=str(c2) # converting complex number to string
s9=s7+s8
print(s7,s8,s9)

Operators

Operator is a special symbol which is used to perform some


operation.
Python operators are classified into 3 categories.
1. Unary Operators
2. Binary Operators
3. Ternary Operator
Based on the operands on which it perform operation.
A operator which operates on one operand is called unary operand.
A binary operator which perform operation on two operands.
A ternary operator perform operation on three operands.

10+20=30
1+2+3+4+5
3+3+4+5
6+4+5
10+5 =15
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Identity Operators
7. Membership Operators
8. Conditional Operators

Arithmetic Operators
These operators are used to perform arithmetic operations. These are
binary operators.
Operator Meaning
+ Addition, Concatenation
- Subtraction
* Multiplication, Repeating
sequence number of times
/ Float Division
// Floor division or integer division
% Modular Operator
** Expo
+ operator is used to perform two operations.
1. Adding numbers
2. Concatenating string
If two operands are numbers it performs addition.
If two operands are strings it perform concatenation

Example:
a1=10
a2=20
a3=a1+a2
print(a1,a2,a3)
s1="Python"
s2="Language"
s3=s1+s2
print(s1,s2,s3)

Example
s1="Python"
f1=3.9
s2=s1+f1
print(s1,f1,s2)
Output:
Traceback (most recent call last):
File "C:/Users/admin/Desktop/py11am/py27.py", line 3, in <module>
s2=s1+f1
TypeError: can only concatenate str (not "float") to str

Example
s1="Python"
f1=3.9
s2=s1+str(f1)
print(s1,f1,s2)
Output:
Python 3.9 Python 3.9
Example
res1=100+200
res2=1.5+2.5
res3=1+2j+1+3j
res4="python"+"language"
res5=True+True
res6=False+False
print(res1,res2,res3,res4,res5,res6,sep='\n')

If Arithmetic operation is performed on multiple types of operands


always result is return as broader type.

10+2.5 ➔ 12.5
10+20 ➔ 30
1.5+2.5 ➔ 4.0
1+2+3.5+1.2 ➔ 7.7
1+2j+1 ➔ 2+2j

Int< float< complex


1+2.5+4+3j ➔ complex
Example
>>> x=1+2.5+4+3j
>>> type(x)
<class 'complex'>
>>> x
(7.5+3j)
>>>
- Operator , this operator is used to perform binary subtraction.
res1=100-50
res2=1.5-1.2
res3=True-False
res4=False-True
res5=100-1.5
print(res1,res2,res3,res4,res5)
print(type(res1),type(res2),type(res3),type(res4),type(res5))

*Operator, this operator is used to perform binary multiplication. It


can be used two types.
1. numbers
2. sequences(list,string,…)
If it is used with numbers if perform multiplication, if it is used with
sequence it perform repeation

Note: Every operator is bind with a function/method of that


class/data type. Whenever we use operator on operands, based on
operand type it calls the function of that data type.

Q: Write an expression which add two float numbers and assign


result to variable in integer.
Res1=1.5+2.5 ➔ 4.0
Res2=int(1.5+2.5) ➔ 4
Res3=float(10+20) ➔ 30.0
True+True ➔ 2 ➔ int ➔ bool(True+True) ➔ True
Example
res1=10*5
res2=1.5*2
res3=1+2j*1+3j
res4=True*False
res5="Python"*2
print(res1,res2,res3,res4,res5,sep="\n")
res6=[10,20,30,40,50]*2
print(res6)
res7=2*"Python"
print(res7)

/ division operator, this operator is used to divide two numbers. This


operator divide two integer and return result as a float.
Example
res1=5/3
print(res1)
res2=2.5/1
print(res2)

// floor division operator or integer division operator. This operator


divide two numbers and return result as integer.

Int//int ➔ int ➔ 3//2 ➔ 1


float//float ➔ int ➔ float

3.0/2.0 ➔ 1.5
3.0//2.0 ➔ 1 ➔ 1.0
res1=3/2
res2=3//2
print(res1,res2,sep='\n')
res3=3.0/2.0
res4=3.0//2.0
print(res3,res4,sep="\n")

% modular operator, this operator is used to get the rem.

res1=10%2
res2=9%2
print(res1)
print(res2)

** is called expo operator or power of operator, it is find power of


given number.

res1=10**2
res2=1.5**3
print(res1)
print(res2)

Operator precedence

The following table summarizes the operator precedence in Python,


from lowest precedence (least binding) to highest precedence
(most 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, which
groups from right to left).

Operator Description
:= Assignment expression
lambda Lambda expression
if – else Conditional expression
Operator Description
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in, is, is not, <, <=, >, Comparisons, including membership
>=, !=, == tests and identity tests
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
<<, >> Shifts
+, - Addition and subtraction
Multiplication, matrix multiplication,
*, @, /, //, %
division, floor division, remainder
+x, -x, ~x Positive, negative, bitwise NOT
** Exponentiation
await x Await expression
x[index], x[index:index], Subscription, slicing, call, attribute
x(arguments...), x.attribute reference
(expressions...),
Binding or parenthesized expression, list
[expressions...], {key: display, dictionary display, set display
value...}, {expressions...}
Relational Operators
These operators are used to find relation between two
values/objects. Relational operators are used to compare objects.
Operator Meaning
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
== Equality operator
!= Not Equal
All relational operator return Boolean value(True/False).
An expression which is having relational operators is called Boolean
expression.
10+20-5 ➔ Arithmetic Expression
10>20 ➔ Boolean Expression
In python relational operators are used on standard data
type(int,float,complex,bool) and sequence datatypes(list,set,str,..)
Example
b1=100>50
b2=50<100
b3=100>200
b4=100<50
b5=100>=200
b6=100<=200
print(b1,b2,b3,b4,b5,b6)
b7="A">"B" # ==> 65>66
b8="B">"A" # ==> 66>65
b9="A"<"B" # ==> 65<66
print(b7,b8,b9)
b10=1.5<1.7
b11=1.7>1.5
print(b10,b11)
Example
b1=100==100
b2="nit"=="nit"
b3=True==True
b4=True!=True
print(b1,b2,b3,b4)

Logical Operator
Logical operators are used to combine more than one Boolean
expression (OR) these operators are used to combine two conditions
or test.
Logical operators are represented using keywords.

Operator Meaning
and Logical and operator
or Logical or operator
not Logical not operator
Truth table of and operator
Operand1 Operand2 Operand1 and
operand2
True True True
True False False
False True False
False False False
Truth table of or operator
Operand1 Operand2 Operand1 or
Operand2
True True True
True False True
False True True
False False False
Truth table of not operator
Operand1 not operand1
True False
False True
Precedence of Logical Operators least to highest.
or Boolean OR
and Boolean AND
not x Boolean NOT
Example
x=100 and 200
print(x)
y=100 and 200 and 300
print(y)
z=100 and 0 and 300
print(z)
t1=100>50 and 50<100
print(t1)
Output
200
300
0
True
Example
x=True or True
y=True or False
z=False or True
p=False or False
print(x,y,z,p)
a=100 or 200
b=0 or 200
c=200 or 300 or 0
d=0 or 200 or 300
print(a,b,c,d)
e=0 or 0
print(e)
Output:
True True True False
100 200 200 200
0
Example:
a=100 and 200 or 300
b=100 or 200 and 300
c=0 or 200 and 300
print(a,b,c)
p=100>50 or 100>50 and 50<100
print(p)
Output:
200 100 300
True

Example:
x=not True
print(x)
y=not False
print(y)
a=not 100
b=not 0
print(a,b)

c=100 or 200 and 300 and not 100


print(c)
Output:
False
True
False True
100
Bitwise Operators
Bitwise operators are used to perform operation on binary data.
Some of the bitwise operators are used to apply logical gates.
Some of the bitwise operators are used to increment or decrement
values by adding and removing bits.

Operator Meaning
>> Right shift operator
<< Left shift operator
& Bitwise and operator
| Bitwise or operator
^ Bitwise xor operator
~ Bitwise not operator

>> right shift operator is used to shift number of bits toward right side.
By shift number bits towards right the value get decremented.
Shifting bits towards right side is deleting bits at right side.
Example
n=30
m=n>>2
print(n,m)
Output
30 7
Formula => num//2**bits ➔ 30//2**2 ➔ 30//4 ➔ 7

<< Lift shift operator


This operator is used to shift number of bits towards left side. It add
number of bits at right side. By shifting number of bits towards leftside
the value get incremented.

30 ➔ 11110 <<2 ➔ 1111000


Formula ➔ num*2**bits ➔ 30*2**2 ➔ 120
Example
n=30
m=n<<2
print(n,m)

Output:
30 120
& Bitwise and operator
| Bitwise or operator
^ Bitwise xor operator
~ Bitwise not operator

Logic gates are the basic building blocks of any digital system. It is
an electronic circuit having one or more than one input and only
one output. The relationship between the input and the output is
based on a certain logic. Based on this, logic gates are named as
AND gate, OR gate, NOT gate etc.

Bitwise & operator is used for applying and gate.


Opr1 Opr2 Opr1&Opr2
1 1 1
1 0 0
0 1 0
0 0 0
Bitwise | operator used to applying or gate
Opr1 Opr2 Opr1|Opr2
1 1 1
0 1 1
1 0 1
0 0 0
Bitwise ~ not operator for applying not gate
Opr1 ~opr1
1 0
0 1
Bitwise ^ XOR operator for applying XOR gate
Opr1 Opr2 Opr1^Opr2
1 0 1
0 1 1
1 1 0
0 0 0
Example
b1=0b1010
b2=0b1010
b3=b1&b2
print(b1,b2,b3)
print(bin(b1),bin(b2),bin(b3))
b4=0b100
b5=0b101
b6=b4&b5
print(b4,b5,b5)
print(bin(b4),bin(b5),bin(b6))
Example
b1=0b1010
b2=0b1000
b3=b1|b2
print(b1,b2,b3)
print(bin(b1),bin(b2),bin(b3))
Example
b1=0b1010
b2=0b1001
b3=b1^b2
print(b1,b2,b3)
print(bin(b1),bin(b2),bin(b3))
Example
b1=0b1010
b2=~b1 # -(num+1)
print(b1)
print(b2)
Assignment operators or update operators or Augmented
assignment statements

Augmented assignment is the combination, in a single statement, of


a binary operation and an assignment statement.
Operator Description
+= a=10
a+=10 ➔ a=a+10
-= a=5
a-=2➔ a=a-2
*= a=5
a*=2 ➔ a=a*2
/= a=5
a/=2 ➔ a=a/2
//= a=10
a//=3 ➔ a=a//3
%= a=5
a%=3 ➔ a=a%3
**= a=3
a**=2 ➔ a=a**2
>>= a=10
a>>=2 ➔ a=a>>2
<<= a=10
a<<=2 ➔ a=a<<2
&= a=10
a&=5 ➔ a=a&5
|= a=10
a|=3 ➔ a=a|3
^= a=10
a^=5 ➔ a=a^5

Example:
a=10
b=5
a+=b
print(a,b)
Output:
15 5

Identity Operators
Every object in python is having identity. This identity is called
address. Identity operators are used to compare addresses.
1. is
2. is not
These operators return Boolean value(True/False).
If two variables hold address of same object it return True otherwise
return False.
== operator is used to compare the state/values of the object.
Example
>>> f1=1.5
>>> f2=1.5
>>> id(f1)
1012338075920
>>> id(f2)
1012338076944
>>> f1==f2
True
>>> f1 is f2
False
>>>
Example
>>> x=1.5
>>> y=x
>>> id(x)
1012338815120
>>> id(y)
1012338815120
>>> x==y
True
>>> x is y
True
>>>

Membership Operators

Membership operators are used with collections (sequences and


non sequences). Membership operators are used to search or find
given element/item exists in collection. If given item/element exists in
collection it return True otherwise it return False.
1. in
2. not in
These both operators return Boolean values.
Example:
>>> namesList=["naresh","suresh","kishore","suresh","rajesh"]
>>> "rajesh" in namesList
True
>>> "ramesh" in namesList
False
>>> "ramesh" not in namesList
True
>>> "a" in "amar"
True
>>> "s" in "rajesh"
True
>>> "k" in "shubham"
False
>>>
Conditional Operator
It is an operator which is used to define one statement.
Conditional operator is ternary operator.
Syntax1:
opr2 if opr1 else opr3
opr1 ➔ Boolean expression, which return True of False
opr2➔ statement which is executed if opr1 is True
opr3 ➔ statement which is executed if opr1 is False

# find input number is even or odd


num=int(input("Enter any number")) # 3 4
print("even") if num%2==0 else print("odd")
Control Statements
Conditional control statements
o If
o If-else
o If-elif-else
o Nested-if
Loop control statements
o for
o while
o Nested loops
Branching statements
o Break
o Continue
o Pass
o Return
Case studies

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


The process of executing the individual statements in a given order is called control
flow.
The control can be executed in three ways

1. sequence
2. selection
3. iteration

Conditional control statements


Conditional control statements are used in order to execute block of statements
based on condition or test. As part of python there is only one conditional
statement called if.
1. Simple if
2. If..else
3. If..elif..else
4. nested if
simple if
if without else is called simple if. It is having only true block.
Syntax:
if <condition>/<test>:
statement-1
statement-2
statement-3

if condition is True it execute statement-1,statement-2 and statement-3


if condition false it execute statement-3

If..else
This syntax define two block 1. If block 2. Else block
Syntax:
If <condition>/<test>:
Statement-1
Statement-2
else:
statement-3
statement-4
statement-5

if condition is True, it execute statement-1,statement-2 and statement-5


if condition is False, it execute statement-3, statement-4 and statement-5
Example
if True:
print("Hello")
print("Bye")

if False:
print("Hello")
print("Bye")
Output:
Hello
Bye
Bye
Example
if 100>50:
print("Python")

if 100<50:
print("Python")

output:
Python
Example
if True:
print("Python")
else:
print("Jython")

if False:
print("Python")
else:
print("Jython")
Output:
Python
Jython
Example
# Develop login application
user=input("UserName :")
pwd=input("Password :")
if user=="nit" and pwd=="nit123":
print("welcome to my application")
else:
print("invalid username or password")
# write a program to find input number is even or odd
num=int(input("enter any number"))
if num%2==0:
print(num,"is even")
else:
print(num,"is odd")
# write a program to find input character is vowel or not
ch=input("enter any character")
if ch in "aeiouAEIOU":
print(ch,"is vowel")
else:
print(ch,"is not vowel")

ch=input("enter charCTER")
if(ch=='A' or ch=='E'or ch=='I' or ch=='O' or ch=='U' or ch=='a' or ch=='e' or ch=='i' or
ch=='o'or ch=='u' ):
print("chara is vowel")
else:
print("not vowel")

# write a program to find input character is alphabet or not


ch=input("enter any character")
if ch>='A' and ch<='Z' or ch>='a' and ch<='z':
print("Alphabet")
else:
print("not alphabet")
If..elif..else
This is checking multiple conditions.
Syntax:
if condition1:
statement-1
statement-2
elif condition2:
statement-3
statement-4
elif condition3:
statement-5
statement-6
else:
statement-7
statement-8

if condition1 is True, it execute statement-1 and statement-2 and


statement-8.
If condition1 is False and condition2 is True, it execute statement-
3,statement-4 and statement-8
If condition1,condition2 are false and condition3 is True, it execute
statement-5,statement-6 and statement8
If condition1,condition2,condition3 are false it execute statement-7
and statement-8.

# write a program to find input number is +ve,-ve or zero


num=int(input("enter any number"))
if num>0:
print("+ve number")
elif num<0:
print("-ve number")
else:
print("zero")
# write a program to find input character is alphabet,digit or special
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")

ord() : ord() is a predefined function in python. This function return


ascii value of given character.
chr() : chr() is a predefined function in python. This function return a
character of given ascii value.

>>> ord('A') >>> chr(65)


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

# write a program to convert input character from lowercase to


uppercase and uppercase to lowercase
ch=input("enter any character")
if ch>='A' and ch<='Z':
x=ord(ch)+32
ch=chr(x)
print(ch)
elif ch>='a' and ch<='z':
x=ord(ch)-32
ch=chr(x)
print(ch)
else:
print("input character is not alphabet")
# write a program to read sales of a sales person and calculate
comm based
# the following conditions
# sales>=50000 ==> 5%
# sales>=30000<50000 ==> 2%
# sales<30000 ==> 0
name=input("Enter name")
sales=float(input("Enter sales"))
comm=0
if sales>=50000:
comm=sales*5/100
elif sales>=30000 and sales<50000:
comm=sales*2/100
else:
comm=0
print("Name :",name)
print("Sales :",sales)
print("Comm :",comm)
# write a program to find max of 3 numbers
a=int(input("enter first number"))
b=int(input("enter second number"))
c=int(input("enter third number"))
if a>b and a>c:
print(a,"is max")
elif b>c and b>a:
print(b,"is max")
elif c>b and c>a:
print(c,"is max")
else:
print("equal")

nested if
if within if or if followed by if is called nested if.
Syntax:
If condition1:
If condition2:
Statement-1
else:
statement-2
else:
statement-3

# login application

user=input("UserName :") # ==> xyz


pwd=input("Password :") # ==> nit456
if user=='nit':
if pwd=='nit123':
print("welcome to my application")
else:
print("invalid password")
else:
print("invalid username")
# write a program to read accno,balance and perform
transactions(deposit/withdraw)

accno=int(input("Enter accno"))
bal=float(input("Enter balance"))
ttype=input("Enter transaction type")
tamt=float(input("Enter transaction amount"))
if ttype=='withdraw':
if tamt<bal:
bal=bal-tamt
else:
print("insuff balance")
elif ttype=='deposit':
bal=bal+tamt
else:
print("invalid transaction type")

print("AccountNo ",accno)
print("Balance ",bal)
print("TransactionType ",ttype)
print("TransactionAmt ",tamt)

# write a program to find the max of 3 numbers without using and,or


operators

n1=int(input("enter first number"))


n2=int(input("enter second number"))
n3=int(input("enter third number"))
if n1>n2:
if n1>n3:
print(n1,"is max")
else:
print(n3,"is max")
elif n2>n3:
print(n2,"is max")
else:
print(n3,"is max")
Looping Statements

Looping statements are used to repeat one or more than one


statement number of times or until given condition.

1. While
2. For

While loop or statement

The while statement is used for repeated execution as long as an


expression is true.

Syntax-1:

while <expression>/<condition>:
statement-1
statement-2
statement-3

while loop execute statement-1 and statement-2 until expression or


condition is True. If condition is false it stop executing loop and
continue statement-3.
Syntax-2:

while <condition>:
statement-1
statement-2
else:
statement-3
statement-4
statement-5

While loop execute statement-1,statement-2 until condition is True. If


condition is False it execute statement-3, statement-4 and
statement-5
Example
# write a program to print Natural numbers 1 2 3 4 5 ... 10
num=1 # init
while num<=10: # condition
print(num)
num=num+1 # updation
In order to work with looping statement, we required 3 statements.
1. Initialization
2. Condition
3. Updation
Initialization define initial value of condition.
Condition define how many times the loop has to be repeated.
Update statement which update condition.
# write a program to print even numbers from 2 4 6 8 10 12 14 ...20
num=2
while num<=20:
print(num)
num=num+2
num=1
while num<=20:
if num%2==0:
print(num)
num+=1

# write a program to print all odd numbers between 1 to 20


num=1
while num<=20:
if num%2!=0:
print(num,end=' ')
num=num+1
print()
num=1
while num<=20:
print(num,end=' ')
num+=2
# write a program to print table for input number
#5
# 5*1=5
# 5*2=10
num=int(input("enter any number"))
i=1
while i<=10:
p=num*i
print(num,"*",i,"=",p)
i=i+1
# write a program to find factorial of input number
# 4 ==> 4*3*2*1 =24
num=int(input("enter any number"))
fact=1
while num>=1:
fact=fact*num
num=num-1
print("Factorial is ",fact)
# write a program to find input number is prime or not
# num=5
# 5%1 5%2 5%3 5%4 5%5
num=int(input("enter any number"))
i=1
c=0
while i<=num:
if num%i==0:
c=c+1
i=i+1
if c==2:
print(num,"is prime")
else:
print(num,"is not prime")

# write a program to find input number is prime or not


# num=5
# 5%1 5%2
num=int(input("enter any number"))
i=1
c=0
while i<=num//2:
if num%i==0:
c=c+1
i=i+1
if c==1:
print(num,"is prime")
else:
print(num,"is not prime")

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


# 345 ==> 3+4+5 ==> 12
# 345%10 = 5
# 345//10 = 34
# 34%10 = 4
# 34//10 =3
# 3%10 =3
# 3//10 =0
num=int(input("enter any number"))
s=0
while num!=0:
r=num%10
s=s+r
num=num//10
print(s)
for loop

The for statement is used to iterate over the elements of a sequence


(such as a string, tuple or list) or other iterable object:

Iteable object generate each time one value or iterable is one


collection which allows to each time one value.

Syntax1:

for variable in iterable/sequence/collection:


statement-1
statement-2
statement-3

for loop each time it read value from iterable/sequence/collection


and assign to variable and execute statement-1 and statement-2.
Statement-1 and Statement-2 are executed until all the values read
from iterable/sequence/collection.

range()

The range type represents an immutable sequence of numbers and


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

Syntax1:range(stop)
Syntax2:range(start,stop,step)

Syntax1: range(stop) ➔ the default start is 0 and default step is +1


Syntax2: range(start,stop,[step]) ➔ the default step is +1
If step value is +ve the start<stop
If step value is –ve the start>stop
Note: stop value is not included in the range
If step is zero, ValueError is raised

Example:
r1=range(1,21)
print(r1)
for value in r1:
print(value,end=' ')
Example
r=range(1,6,1)
it=iter(r)
value1=next(it)
value2=next(it)
value3=next(it)
value4=next(it)
value5=next(it)
print(value1,value2,value3,value4,value5)

r1=range(1,6,1)
for value in r1:
print(value)

Example
e1=range(1.5,4.5)
for value in e1:
print(value)
The above code display error because range can be used only with
integers.
# write a program to generate even numbers between 1 to n

n=int(input("enter the value n")) # 5


for value in range(1,n+1):# range(1,6) ==> 1 2 3 4 5
if value%2==0:
print(value)

# write a program to generate odd numbers between 1 to n

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


for value in range(1,n+1):
if value%2!=0:
print(value)

Example:
n=int(input("enter n value"))
for value in range(2,n+1,2):
print(value)
for value in range(1,n+1,2):
print(value)

Example:
r1=range(10,0,-1)
r2=range(-1,-11,-1)
r3=range(-10,0,1)
for value in r1:
print(value,end=' ')
print()
for value in r2:
print(value,end=' ')
print()
for value in r3:
print(value,end=' ')
print()

# write a program to generate table for given number

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(num,"*",i,"=",p)
# write a program to generate sqr of the all the numbers between 1
to n
# 1=1
# 2=4

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


for value in range(1,n+1):
print(value,value**2,sep="=")
for value in range(1,n+1):
print(value,value**value,sep="=")

# write a program to find given 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(num,"is prime")
else:
print(num,"is not prime")
Nested Loops
Writing a loop inside loop is called nested loop.
Nested loop can be,
1. Nested while loop
2. Nested for loop
While loop inside while loop is called nested while.
For loop inside for loop is called nested for.
Syntax of nested while Syntax of nested for loop
while <condition>: # outer loop for variable in iteralbe:
statement-1: statement-1
statement-2: statement-2
while <condition>: # inner loop for variable in iterable:
statement-3 statement-3
statement-4 statement-4
statement-5 statement-5
statement-6 statement-6

# write a program to print tables from 1 to 10

for num in range(1,11): # 1 2 3 4 5 6 7 8 9 10 # reading number


for i in range(1,11): # multiplying that number 10 times
p=num*i
print(num,"*",i,'=',p)
input()

# write a program to generate prime numbers between given range

start=int(input("enter start value")) # 3


stop=int(input("enter stop value")) # 7
for num in range(start,stop+1): # 3 4 5 6 7
c=0
for i in range(1,num+1): # 1 2 3
if num%i==0:
c=c+1
if c==2:
print(num)

# write a program to print factorial of all the numbers between given


range

start=int(input("enter start value")) # 3


stop=int(input("enter stop value")) # 5
for num in range(start,stop+1): # 3 4 5
fact=1
for i in range(1,num+1):
fact=fact*i
print(num,fact)
Patterns

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

A
A B
A B C
A B C D
A B C D E
1 for i in range(1,6):
1 2 for j in range(1,6):
1 2 3 if j<=i:
1 2 3 4 print(j,end=' ')
1 2 3 4 5 print()
1 2 3 4 5 for i in range(5,0,-1):
1 2 3 4 for j in range(1,6):
1 2 3 if j<=i:
1 2 print(j,end=' ')
1 print()

A for i in range(65,70):
A B for j in range(65,70):
A B C if j<=i:
A B C D print(chr(j),end=' ')
A B C D E print()
1 2 3 4 5 for i in range(1,6):
2 3 4 5 for j in range(1,6):
3 4 5 if j>=i:
4 5 print(j,end=' ')
5 else:
print(' ',end=' ')
print()
5 for i in range(5,0,-1):
4 5 for j in range(1,6):
3 4 5 if j<=i:
2 3 4 5 print(j,end=' ')
1 2 3 4 5 print()
1 for i in range(1,6):
2 1
3 2 1 for j in range(5,0,-1):
4 3 2 1
5 4 3 2 1 if j<=i:

print(j, end = ' ')

else:
print(' ',end = ' ')

print()

break and continue statements

break and continue are called passes control statements are


branching statements.

Break statement is used inside the loop for terminating. In order to


terminate loop unconditionally we can use break statement.
Unconditionally means in between.

# write a program to print sum of 10 even numbers between 1 to n


n=int(input("enter the value n"))
s=0
c=0
for num in range(1,n+1):
if num%2==0:
s=s+num
c=c+1
if c==10:
break
print("sum of 10 even number between 1 to ",n,"is",s)

continue move the execution control to the beginning of the loop.


Continue statement also used inside loop only.
After continue rests of the statements are not executed.

for i in range(1,10):
if i<=5:
continue
print(i)

# for with else

for i in range(1,6):
print("inside for block")
else:
print("inside else block")

# while with else


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

Note: else block is not executed when loop is terminated with break

for i in range(1,10):
if i>5:
break
print(i)
else:
print("inside else block")
pass
pass is a keyword in python.
pass is a null operation — when it is executed, nothing happens. It is
useful as a placeholder when a statement is required syntactically,
but no code needs to be executed.

Eg:

If True:
print(“Hello”)
Explanation: The above code generate syntax error, because if
required at least one statement. Any block in python required one
statement. If you want write block without performing any operation
then include pass statement.

Eg:
If true:
pass
Explanation: The above code does not generate any error.
while False:
pass
Explanation: The above code does not generate any error
Example
if True:
pass # it is not for terminate, it just perform null operation
print("inside if")
print("Hello")
Strings

Q: What is string in python?


String is a collection of characters.
String is sequence data type or collection data type.
String is immutable sequence, once string is created cannot do any
changes.
String object is represented using “str” class (OR) str is class or data
type which is used to represent string object.

Python allows representing or creating string in different ways.


1. String is represented within single quotes
2. String is represented within double quotes
3. String is represented within three single or double quotes
4. String is represented using str() type.
• Within single quotes we can represent single line string and it
allows embedding double quotes.
• Within double quotes we can represent single line string and it
allows embedding single quotes.
• Within three single quotes we can represent multiline string and
it allows embedding double quotes.
• Within three double quotes we can represent multiline string
and it allows embedding single quotes.
• Using str() type we can convert other types in string eg:
int,float,complex,..
Example:
str1='Python Language'
str2="Python Langauge"
str3='''Python Langauge'''
str4="""Python Language"""
str5=str("Python Langauge")
print(str1,str2,str3,str4,str5,sep='\n')
str1='"Python Language"'
str2="'Python Language'"
str3='''"Python
Language"'''
str4="""'Python
Language'"""
str5=str(100)
str6=str(1.5)
str7=str(1+2j)
str8=str("Python")
print(str1,str2,str3,str4,str5,str6,str7,str8,sep='\n')
Example
# can we represent multiline string within single quotes
str1='Python\nLanguage'
str2="Python\nLanguage"
print(str1)
print(str2)
Example
str1='\'Python Language\''
str2="\"Python Language\""
print(str1)
print(str2)

String is index based collection (OR) all sequence datatypes are


index based. Where it allows to read using its positions(index). Index is
an integer value which is used to indentify each location in
sequence.
+ve index is used to read characters from left to right.
-ve index is used to read characters from right to left.

Index allows to read in sequentially and randomly.


str1="PYTHON"
str1[0]="X"

# write a program to find length of string


# python provide a predefined function called len()
s=input("Enter any string")
l=len(s)
print(l)

Example

# write a program to read string and count number of


alphabets,digits and

# special characters

str1=input("Enter any string") # python3.9


ca=0
cd=0
cs=0
for i in range(len(str1)): # 0 1 2 3 4 5 6 7 8
if (str1[i]>='A' and str1[i]<='Z') or (str1[i]>='a' and str1[i]<='z'):
ca=ca+1
elif str1[i]>='0' and str1[i]<='9':
cd=cd+1
else:
cs=cs+1

print("Count of alphabets ",ca)


print("Count of digits ",cd)
print("Count of special characters ",cs)
Reading String using for loop:

For loop is used to read the content of iterable, string is also iterable.
For loop each time read one character and perform operation.

# write a program to find length of string without using len function


str1=input("enter any string") # NIT
c=0
for ch in str1: # NIT
c=c+1
print("length of string ",c)

# Write a program to convert lowercase string to uppercase


str1=input("enter any string")
str2=""
for ch in str1:
if ch>='a' and ch<='z':
ch=chr(ord(ch)-32)
str2=str2+ch
else:
str2=str2+ch
print(str1)
print(str2)

# write a program to conver uppercase string to lowercase string


str1=input("enter any string")
str2=""
for ch in str1:
if ch>='A' and ch<='Z':
ch=chr(ord(ch)+32)
str2=str2+ch
else:
str2=str2+ch
print(str1)
print(str2)

# write a program to convert string to capitalize


# first letter of the string is capital and rest of letters are in lowercase
str1=input("enter any string") # nit
str2=""
for i in range(len(str1)): # 0 1 2
if i==0 and str1[i]>='a' and str1[i]<='z':
str2=str2+chr(ord(str1[i])-32)
elif i==0:
str2=str2+str1[i]
elif str1[i]>='A' and str1[i]<='Z':
str2=str2+chr(ord(str1[i])+32)
else:
str2=str2+str1[i]
print(str1)
print(str2)

# write a program to convert string to title case


# each word first letter in capital
str1=input("enter any string")
str2=""
i=0
while i<len(str1):
if i==0 and str1[i]>='a' and str1[i]<='z':
str2=str2+chr(ord(str1[i])-32)
elif i==0:
str2=str2+str1[i]
elif str1[i]==' ' and str1[i+1]>='a' and str1[i+1]<='z':
str2=str2+str1[i]
str2=str2+chr(ord(str1[i+1])-32)
i=i+1
elif str1[i]==' ' and str1[i+1]>='A' and str1[i+1]<='Z':
str2=str2+str1[i]
str2=str2+str1[i+1]
i=i+1
elif str1[i]>='A' and str1[i]<='Z':
str2=str2+chr(ord(str1[i])+32)
else:
str2=str2+str1[i]
i=i+1
print(str1)
print(str2)

# write a program for swapcase


# naresh ==> NARESH
# NARESH ==> naresh
# Naresh ==> nARESH
# aBc ==> AbC

str1=input("enter any string")


str2=""
for ch in str1:
if ch>='A' and ch<='Z':
str2=str2+chr(ord(ch)+32)
elif ch>='a' and ch<='z':
str2=str2+chr(ord(ch)-32)
else:
str2=str2+ch
print(str1)
print(str2)
Slicing

Using index we can read only one character from string. With the
slicing we can read more than one character. Slice is reading part of
a sequence.

This slicing is done in two ways.


1. Slice operator
2. Slice object
Slice operator: Slice operator required three values.
1. Start index
2. Stop index
3. Step
Startindex,stop index, step operational. The default startindex is
0,stop index is length of string, step is +1
Slice operator internally uses range for generating indexes.
Syntax1: string-name[startindex:stopindex:step]
Syntax2: string-name[startindex:stopindex]
Syntax3:string-name[startindex:]
Syntax4:string-name[::]
Syntax5:string-name[:stopindex]
Syntax6:string-name[::step]
If step is +ve the default startindex is 0 and endindex len(string)
If step is –ve the default startindex is -1 and endindex –len(string)

>>> str1="PYTHON"
>>> str2=str1[0:4:1]
>>> str1
'PYTHON'
>>> str2
'PYTH'
>>> str3=str1[1:5]
>>> str3
'YTHO'
>>> str4=str1[::]
>>> str4
'PYTHON'
>>> str5=str1[:]
>>> str5
'PYTHON'
>>> str6=str1[:3]
>>> str6
'PYT'
>>>
>>> str7=str1[::1]
>>> str8=str1[::-1]
>>> str7
'PYTHON'
>>> str8
'NOHTYP'

Example:

str1="PROGRAMMING"
str2=str1[::]
str3=str1[:]
str4=str1[::1]
str5=str1[::-1]
str6=str1[::2]
str7=str1[::-2]
str8=str1[2:5]
str9=str1[5:2:-1]
str10=str1[-3:-6:-1]
str11=str1[-6:-3:1]
print(str1)
print(str2)
print(str3)
print(str4)
print(str5)
print(str6)
print(str7)
print(str8)
print(str9)
print(str10)

# write a program to find input string is pal or not


str1=input("enter any string")
if str1==str1[::-1]:
print("String is pal")
else:
print("String is not pal")

slice() object
slice object is reusable
Syntax-1:slice(stop) ➔ default start 0 and step +1
Syntax-2:slice(start,stop,[step]) ➔ default step is +1
Example
s=slice(4)
str1="PROGRAMMING"
str2="LANGUAGE"
str3=str1[s]
str4=str2[s]
print(str1)
print(str2)
print(str3)
print(str4)
Example
s1=slice(0,5)
str1="PROGRAMMING"
str2="LANGUAGE"
str3=str1[s1]
str4=str1[s1]
s2=slice(-1,-5,-1)
str5=str1[s2]
str6=str2[s2]
print(str1)
print(str2)
print(str3)
print(str4)
print(str5)
print(str6)

String methods

Conversion Methods
• str.capitalize()
o Return a copy of the string with its first character
capitalized and the rest lowercased.
• str.swapcase()
o Return a copy of the string with uppercase characters
converted to lowercase and vice versa. Note that it is not
necessarily true that s.swapcase().swapcase() == s.
• str.title()
o Return a titlecased version of the string where words start
with an uppercase character and the remaining
• str.upper()
o Return a copy of the string with all the cased characters
converted to uppercase.
• str.lower()
o Return a copy of the string with all the cased characters
converted to lowercase

Example
str1="python"
str2=str1.upper()
print(str1,str2)
str3="JAVA"
str4=str3.lower()
print(str3,str4)
str5="datascience"
str6=str5.capitalize()
print(str5,str6)
str7="gudio van rossum"
str8=str7.title()
print(str7,str8)
str9="aBcDeF"
str10=str9.swapcase()
print(str9,str10)

String examine methods


String examine methods
str.isalnum()
Return True if all characters in the string are alphanumeric and there
is at least one character, False otherwise
Example
str1="abc"
str2="123"
str3="abc123"
str4="abc123%"
b1=str1.isalnum()
b2=str2.isalnum()
b3=str3.isalnum()
b4=str4.isalnum()
print(str1,str2,str3,str4)
print(b1,b2,b3,b4)
str.isalpha()
Return True if all characters in the string are alphabetic and there is
at least one character, False otherwise.
Example
print("User Registration")
name=input("Name :")
user=input("UserName ")
if name.isalpha() and user.isalnum():
print("valid name and user name")
else:
print("name must be alphabets and user name must be alphabets
and digits")

str.isdecimal()
Return True if all characters in the string are decimal characters and
there is at least one character, False otherwise

Example
str1="123"
b1=str1.isdecimal()
print(b1)
str2="0b1010"
b2=str2.isdecimal()
print(b2)
str3="0o45"
b3=str3.isdecimal()
print(b3)
str4="0xab"
b4=str4.isdecimal()
print(b4)
if str1.isdecimal():
n=int(str1)
print(n)

str.isdigit()
Return True if all characters in the string are digits and there is at least
one character, False otherwise

str1="123"
b1=str1.isdigit()
print(b1)
str2="abc"
b3=str2.isdigit()
print(b3)
# write a program to input string and count number of
alphabets,digits and special characters
str1=input("Enter any string")
ac=0
dc=0
sc=0
for ch in str1:
if ch.isalpha():
ac=ac+1
elif ch.isdigit():
dc=dc+1
else:
sc=sc+1
print("Alphabet count ",ac)
print("Digit count ",dc)
print("Special character count",sc)

str.islower()

Return True if all cased characters in the string are lowercase


and there is at least one cased character, False otherwise

str.isspace()

Return True if there are only whitespace characters in the string


and there is at least one character, False otherwise

str.istitle()

Return True if the string is a titlecased string and there is at least


one character, for example uppercase characters may only
follow uncased characters and lowercase characters only
cased ones. Return False otherwise.

str.isupper()

Return True if all cased characters in the string are uppercase


and there is at least one cased character, False otherwise.

# write a program count uppercase alphabets and lowercase


alphabets inside string

str1=input("Enter string")
uc=0
lc=0
sc=0
for ch in str1:
if ch.isupper():
uc=uc+1
elif ch.islower():
lc=lc+1
elif ch.isspace():
sc=sc+1
print("uppercase characters ",uc)
print("lowercase characters ",lc)
print("space count ",sc)

Searching Methods of str class

str.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found
within the slice s[start:end]. Optional arguments start and end
are interpreted as in slice notation. Return -1 if sub is not found.

str.rfind(sub[, start[, end]])

Return the highest index in the string where substring sub is


found, such that sub is contained within s[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False.
prefix can also be a tuple of prefixes to look for. With optional
start, test string beginning at that position. With optional end,
stop comparing string at that position.

str.endswith(suffix[, start[, end]])

Return True if the string ends with the specified suffix, otherwise
return False. suffix can also be a tuple of suffixes to look for. With
optional start, test beginning at that position. With optional end,
stop comparing at that position.
Example
str1="python is a programming langauge"
i=str1.find("is")
print(i)
i=str1.rfind("is")
print(i)
str2="python is a programming and is a scripting langauge"
i1=str2.find("is")
i2=str2.rfind("is")
print(i1)
print(i2)
Example
str1="python is a programming and is a scripting langauge"
i1=str1.find("a",12)
print(i1)
i2=str1.find("a")
print(i2)

Example
str1="naresh"
b1=str1.startswith("n")
print(b1)
b2=str1.startswith(('a','b','c'))
print(b2)
b3=str1.endswith("h")
print(b3)
b4=str1.endswith(('h','H','a','e'))
print(b4)
Collections or Data Structures

Collection itself is one object which contains more than one object.
Grouping individual objects and representing it is one object.
Every collection follows some set of rules and regulation for
organization of objects/data structures.
As a part of python or python support the following data structures.
1. List ➔ Sequence type
2. Tuple ➔ Sequence type
3. Set ➔ non sequence type
4. Frozenset ➔ non sequence type
5. Dict ➔ non sequence
Sequence types are index based and organize objects in sequential
order.
Non sequence types are non index based organizing objects are not
done using index.
Every collection is called one container.
Containers are used to store and perform aggregate operations or
group operations. These are also used to send data from one place
to another.
Collections are used to store more than one value/object.

List
Lists are mutable sequences, typically used to store collections of
homogeneous items or similar type of items. But it also support to
store heterogeneous items or different types.
After creating list we can modify (add,update or delete) items.
List is a index based collection, where reading and writing is done
using index. Index allows to read and write in sequentially or
randomly.
List allows duplicates.
List is ordered collection, where insertion is preserved (order of
insertion does not changes from one insertion to another).
List is sequence data type or data type.

How create list?

• Using a pair of square brackets to denote the empty list: []


• Using square brackets, separating items with commas: [a],
[a, b, c]
• Using a list comprehension: [x for x in iterable]
• Using the type constructor: list() or list(iterable)

>>> 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(type(list3))
<class 'list'>
>>> print(list3)
[10, 20, 30, 40, 50]
>>>
>>> print(type(list3))
<class 'list'>
>>> print(list3)
[10, 20, 30, 40, 50]
>>> list4=[10,1.5,"naresh",1+2j]
>>> list4
[10, 1.5, 'naresh', (1+2j)]
>>> print(type(list4))
<class 'list'>
>>>
>>> student_record=[101,'naresh','python',5000.0]
>>> print(student_record)
[101, 'naresh', 'python', 5000.0]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list("PYTHON")
>>> print(list2)
['P', 'Y', 'T', 'H', 'O', 'N']
>>> list3=list(list1)
>>> print(list3)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>>
List is an iterable, which allows to each time one object. We can
create list using existing iterables or collections using list() type.

How to read elements/objects from list?


1. Using index
2. Slicing
3. For loop
4. Iterator
5. Enumeration
Index: index is an integer value which is used to identity each
element or object within list. This index can be +ve or –ve. +ve index
starts with 0 and –ve index start with -1. Using +ve index we can read
objects from left to right and using –ve index we can read
value/objects from right to left.
# reading elements from list using index
list1=[10,20,30,40,50]
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
print(list1[4])
print(list1[-1])
print(list1[-2])
print(list1[-3])
print(list1[-4])
print(list1[-5])
l=len(list1)
print(l)
for i in range(0,len(list1)): # 0 1 2 3 4
print(list1[i])
for i in range(-1,-(len(list1)+1),-1): # -1 -2 -3 -4 -5
print(list1[i])

# count of even and odd numbers


list1=list(range(1,51))
ecount=0
ocount=0
for i in range(0,len(list1)):
if list1[i]%2==0:
ecount+=1
elif list1[i]%2!=0:
ocount+=1

print(list1)
print("Even Numbers Count ",ecount)
print("Odd Numbers Count ",ocount)
Example
# list the names whose name ends with h
list1=['naresh','suresh','rajesh','kishore','raman']
for i in range(0,len(list1)): # 0 1 2 3 4
if list1[i].endswith('h'):
print(list1[i])
# list names whose name starts with r
for i in range(0,len(list1)):
if list1[i].startswith('r'):
print(list1[i])
# list names whose name starts with r or s
for i in range(0,len(list1)):
if list1[i].startswith(('r','s')):
print(list1[i])
Reading elements from list using slicing.

Slicing allows to read more than one value. This slicing is done using
two ways.

1. Slice operator
2. Slice object

It is similar to slicing of string(sequence). All sequences allows


indexing and slicing.

Example

list1=list(range(10,110,10))
print(list1)
list2=list1[::]
list3=list1[::-1]
list4=list1[2:]
list5=list1[-2::-1]
print(list2,list3,list4,list5,sep="\n")
list6=list1[3:7]
print(list6)
list7=list1[7:3:-1]
list8=list1[-6:-2]
print(list7,list8,sep='\n')

Example
names_list=['naresh','suresh','rajesh','kishore','rakesh','ramesh']
s1=slice(5)
names_list1=names_list[s1]
s2=slice(5,2,-1)
names_list2=names_list[s2]
print(names_list1,names_list2,sep="\n")
iterator
The content list or sequence can be read using iterator. Iterator
allows to read each time one object.

list1=[10,20,30,40,50]
i=iter(list1)
e1=next(i)
e2=next(i)
e3=next(i)
print(list1)
print(e1,e2,e3)
for e in i:
print(e,sep='\n')

enumeration
The content of list or sequence can be read using enumeration, this
return count and element. This is useful to convert list map collection.

list1=[10,20,30,40,50]
e=enumerate(list1)
print(next(e))
print(next(e))

for loop
for loop each time it read one value from list or collection and
execute block of statements.
list1=list(range(10,110,10))
for value in list1:
print(value)
s=0
for value in list1:
s=s+value
print(s)

Mutable methods of list


These methods are used to modify the list after creation.
List is mutable collection, after creating list we can add, update and
delete items. For doing list provide mutable methods.

1. append():appends x to the end of the sequence (same as


s[len(s):len(s)] = [x])

Example1:
list1=[]
print(list1)
list1.append(10)
list1.append(20)
list1.append(30)
print(list1)

Example2:
# write a program to read the scores n players and display

scores=[]
n=int(input("Enter how many players"))
for i in range(n):
score=int(input("Enter score"))
scores.append(score)

for score in scores:


print(score)
# write a program to read the sales of n sales persons and find min
and max sales\

sales=[]
n=int(input("enter how may sales persons"))
for i in range(n):
sale=float(input("enter sale amount"))
sales.append(sale)

print(sales)
min_sale=min(sales)
max_sale=max(sales)
print(min_sale)
print(max_sale)

# using slicing operator append values to the list


list1=[10,20,30,40,50]
list1[5:5]=[60]
print(list1)
list1[6:6]=[70,80,90]
print(list1)

using append method we can append only one value.


Using slicing operator we can append one or more than one value.

s[i] = x item i of s is replaced by x


s[i:j] = slice of s from i to j is replaced by the contents of the
t iterable t

Example
list1=list(range(10,110,10))
print(list1)
list1[0]=99 # using index we can replace only one value
print(list1)
list1[0:4]=[11,22,33,44] # using slicing we can replace more than one
value
print(list1)
Deleting elements from list

del s[i:j] same as s[i:j] = []


del s[i:j:k] removes the elements of s[i:j:k] from the list
s.clear() removes all items from s (same as del s[:])
s.remove(x) remove the first item from s where s[i] is equal to x

Example
# deleting using index, it allows to delete only one
list1=[10,20,30,40,50]
print(list1)
del list1[0]
print(list1)
Example

# slicing allows to delete more than one element


list1=[10,20,30,40,50,60]
print(list1)
del list1[0:2]
print(list1)
Example

list1=list(range(1,50))
print(list1)
del list1[1::2]
print(list1)
Example
list1=list(range(10))
print(list1)
list1.clear()
print(list1)
Example
list1=list(range(1,50))
print(list1)
del list1[:]
print(list1)

Example
list1=list(range(10,110,10))
print(list1)
list1.remove(20)
print(list1)

s.extend(t) or s extends s with the contents of t (for the most part


+= t the same as s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times
inserts x into s at the index given by i (same as s[i:i] =
s.insert(i, x)
[x])
# example of extend
list1=[10,20,30,40,50]
list2=[60,70,80,90,100]
list1.extend(list2)
print(list1)
l1=[10,20,30]
l2=[40,50,60]
l1[len(l1):len(l1)]=l2
print(l1)

# example of insert
list1=[10,20,30,40,50]
print(list1)
list1.insert(0,99)
print(list1)
list2=[100,200,300,400,500]
print(list2)
list2[2:2]=[600,700]
print(list2)

# example of repeating sequence


list1=[10,20,30,40,50]
list1*=2
print(list1)

s.copy() creates a shallow copy of s (same as s[:])


Python support two types of copies.
1. Shallow copy
2. Deep copy
Q: What is shallow copy?
Shallow copy is reference copy, it copy the address of objects from
one sequence(list) to another.
Copy method of list perform shallow copy.
Example
list1=[10,20,30,40,50]
list2=list1.copy()
print(list1)
print(list2)
list1=[10,[20,30]]
list2=list1.copy()
print(list1)
print(list2)
list1[1].append(40)
print(list1)
print(list2)
list1[1].remove(20)
print(list1)
print(list2)
list2[1].append(100)
print(list1)
print(list2)

In shallows copy if changes done using one list that changes reflect
to another list.
Q:What is deep copy?
Deep copy is object copy, it will not copy addresses but create
copy of object and copy into another sequence/list.
For performing deep copy, python provide copy module. This
module is having a function deepcopy()
In this copy if any changes done in one list, that changes not reflect
another list.

copy.deepcopy(x[, memo])
Return a deep copy of x.

import copy
list1=[10,[20,30]]
list2=copy.deepcopy(list1)
print(list1)
print(list2)
list1[1].append(40)
print(list1)
print(list2)
list2[1].append(100)
print(list2)
print(list1)

Using list as a stack


Stack is a data structure which follows LIFO (Last In First Out), the
element inserted last is removed first.
Stack performs the following operations.
1.push ➔ adding element into stack
2.pop➔ removing element from stack

# stack operations
stack=[]
while True:
print("****Stack Operations****")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
opt=int(input("enter option"))
if opt==1:
ele=int(input("enter element to push"))
stack.append(ele)
print("element pushed inside stack")
if opt==2:
if len(stack)==0:
print("Stack Empty")
else:
print("Elemeted poped",stack.pop())
if opt==3:
print(stack)
if opt==4:
break

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


Example
list1=[10,20,30,40,50]
print(list1)
list1.reverse()
print(list1)

sort(*, key=None, reverse=False)

This method sorts the list in place, using only < comparisons between
items. Exceptions are not suppressed - if any comparison operations
fail, the entire sort operation will fail (and the list will likely be left in a
partially modified state.
Example
list1=[10,40,20,50,30]
print(list1)
list1.sort()
print(list1)
list1.sort(reverse=True)
print(list1)

stringlist=['aaa','AAA','bbb','BBB','ccc','CCC']
print(stringlist)
stringlist.sort()
print(stringlist)
stringlist.sort(key=str.upper)
print(stringlist)
stringlist.sort(key=str.lower,reverse=True)
print(stringlist)

len(s) length of s
min(s) smallest item of s
max(s) largest item of s
s.count(x) total number of occurrences of x in s
Example
list1=[10,20,30,40,50]
print(len(list1))
print(max(list1))
print(min(list1))
print(list1.count(10))
Nested List

List within list is called nested list. Nested list can be used as matrix.
Nested list allows organizing data in rows and columns.

List is index based collection where we can read and write using
index.
Example
list1=[[1,2],[3,4],[5,6]]
print(list1[0][0],list1[0][1])
print(list1[1][0],list1[1][1])
print(list1[2][0],list1[2][1])
print(list1[0])
print(list1[1])
print(list1[2])

list2=[10,20,[30,40]]
print(list2[0])
print(list2[1])
print(list2[2])
print(list2[2][0],list2[2][1])

Example
list1=[]
list1.append([])
list1.append([])
print(list1)
list1[0].append(10)
list1[0].append(20)
list1[1].append(30)
list1[1].append(40)
print(list1)
print(list1[0][0])
print(list1[0][1])
print(list1[1][0])
print(list1[1][1])

print(list1[0])
print(list1[1])
Example
# write a program to read 2x2 matrix and display
matrix=[]
for i in range(2): # 0 1
matrix.append([])
for j in range(2):
ele=int(input("enter element"))
matrix[i].append(ele)
print(matrix)
for i in range(2):
for j in range(2):
print(matrix[i][j],end=' ')
print()
# write a program to read MxN matrix and display
m=int(input("enter number of rows"))
n=int(input("enter number of columns"))
matrix=[]
for i in range(m):
matrix.append([])
for j in range(n):
ele=int(input("enter element"))
matrix[i].append(ele)

for i in range(m):
for j in range(n):
print(matrix[i][j],end=' ')
print()
print(matrix)

# write a program to read M students and each student is having


rno,name,course
m=int(input("enter how many students?"))
students=[]
for i in range(m):
students.append([])
rno=int(input("enter rollno"))
name=input("enter name")
course=input("enter course")
students[i].append(rno)
students[i].append(name)
students[i].append(course)
print(students)
for i in range(m):
for j in range(3):
print(students[i][j],end=' ')
print()

# write a program to add two 3x3 matrices


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

print("enter elements of first matrix")


for i in range(3):
matrix1.append([])
for j in range(3):
ele=int(input("enter element"))
matrix1[i].append(ele)

print("enter elements of second matrix")


for i in range(3):
matrix2.append([])
for j in range(3):
ele=int(input("enter element"))
matrix2[i].append(ele)
for i in range(3):
matrix3.append([])
for j in range(3):
matrix3[i].append(matrix1[i][j]+matrix2[i][j])

print(matrix1)
print(matrix2)
print(matrix3)
Comprehension
For constructing a list, a set or a dictionary Python provides special
syntax called “displays”, each of them in two flavors:

• either the container contents are listed explicitly, or


• they are computed via a set of looping and filtering
instructions, called a comprehension.

Ex:

• either the container contents are listed explicitly.

List1=[10,20,30,40,50]
List2=[1+2,2+2,3+4,5+5]

Comprehension is an elegant way of creating list, set or dictionary by


applying expression.

Syntax-1: [expression for variable in iterable]


Syntax-2: [expression for variable in iterable if test]
Syntax-3: [expression for variable in iterable for variable in iterable]
Syntax-4:[expression for variable in iterable for variable in iterable if
test]
Example
even_list=[num for num in range(0,21,2)]
odd_list=[num for num in range(1,21,2)]
alpha_list=[chr(num) for num in range(65,91)]
print(even_list)
print(odd_list)
print(alpha_list)

Example
# create random 10 otp list
import random
otp_list=[str(random.randint(0,9))+str(random.randint(0,9))+str(rando
m.randint(0,9))+str(random.randint(0,9))+str(random.randint(0,9)) for i
in range(10)]
print(otp_list)

Example
# create list with 5 random passwords
import random
password_list=[chr(random.randint(65,91))+
chr(random.randint(97,121))+
chr(random.randint(65,91))+
chr(random.randint(97,121))+
str(random.randint(1,9))
for i in range(5)]
print(password_list)

Example
names_list=['naresh','suresh','ramesh','kishore']
names_list1=[s.upper() for s in names_list]
print(names_list)
print(names_list1)

# without comprehension
names_list2=[]
for name in names_list:
names_list2.append(name.upper())

print(names_list2)
Comprehension with test condition or filter

[expression for variable in iterable if test]


For loop each time read one value from iterable, and test condition
if condition is True, it eval expression.

Example
list1=list(range(1,31))
print(list1)
even_list=[value for value in list1 if value%2==0]
odd_list=[value for value in list1 if value%2!=0]
print(even_list)
print(odd_list)

Example
sales_list=[10000,12000,15000,20000,21000,30000,13000,14000,35000]
sales_list1=[sales for sales in sales_list if sales<15000]
sales_list2=[sales for sales in sales_list if sales>=15000]
print(sales_list)
print(sales_list1)
print(sales_list2)

Example
names_list=['suresh','kishore','naresh','ramesh','rajesh']
names_list1=[name for name in names_list if name.endswith('h')]
names_list2=[name for name in names_list if
name.startswith(('s','k','r'))]
print(names_list)
print(names_list1)
print(names_list2)
List Comprehension using nested for loop

[expression for variable in iterable for variable in iterable]

Example
matrix1=[[1,2],[3,4]]
matrix2=[[5,6],[8,9]]
matrix3=[[matrix1[i][j]+matrix2[i][j] for j in range(2)] for i in range(2)]
print(matrix1)
print(matrix2)
print(matrix3)

Example

list1=[[1,2,3],[4,5,6],[7,8,9]]
list2=[col for row in list1 for col in row]
print(list1)
print(list2)

tuple
tuple is immutable collection. After creating tuple we cannot modify
(add,update or delete) items.
Tuple is useful to represent dictionaries.
Tuple is useful to represent function arguments.
Tuple is read only, we can read but cannot modify.

How to create tuple?


1. Singleton tuple is created using (obj,) the tuple which contain
one object is called singleton tuple
2. Tuple is created using tuple type
Tuple() ➔ create empty tuple
tuple(iterable) This allows to create tuple using existing
iterables.
Tuple is an immutable list.
Example
t1=(10,) # tuple with one object, which is called singleton tuple
t2=(100,200,300,400,500)
t3=tuple(range(10,60,10))
t4=tuple([10,20,30,40,50])
t5=tuple((10,20,30,40,50))
t6=tuple("PYTHON")
print(t1,t2,t3,t4,t5,t6,sep='\n')

Example
t1=(10,20,30,40,50)
print(t1)
t1[0]=99 # error
print(t1)

Example:
t1=(10,20,30,40,50)
print(t1)
del t1[0] # error
print(t1)

Example
# converting list to tuple and tuple to list
t1=(10,20,30,40,50)
l1=list(t1)
l1.append(60)
t1=tuple(l1)
print(t1)
set
set is non index based collection.
Set is unordered collection, where insertion order is not preserved.
In set data is organized using hashing data structure.
Set does not allow duplicates.
Set is mutable collection, after creating set we can add and remove
items.
Set allows only hashable objects. The object which generate
hashcode is called hashable object. This hashcode is used to
organize objects in hash based data structures. If two objects are
equal then it should generate same hashcode.
Hashcode is an integer value, which is used to organize objects in
hash based data structures.

How to find hashcode of object?


hash() is predefined function in python, which is used to get the
hashcode of the object.
Hashcode is generate by only objects which are hashable.

Example:
>>> hash(10)
10
>>> hash(1.5)
1073741825
>>> hash("java")
471029483
>>> x="java"
>>> y="java"
>>> hash(x)
471029483
>>> hash(y)
471029483
>>> a=100
>>> b=100
>>> a==b
True
>>> hash(a)
100
>>> hash(b)
100
>>> f1=1.5
>>> f2=1.5
>>> f1==f2
True
>>> hash(f1)
1073741825
>>> hash(f2)
1073741825
>>> s1="python"
>>> s2="python"
>>> s1==s2
True
>>> hash(s1)
-1745864186
>>> hash(s2)
-1745864186
>>>
Q: What is hashing data structure?
According to hashing there is a hash table. Each location in
hashtable is identified with key. Each location is called bucket, which
one or more than one object.
Where to add the object is defined by hashing alg.

How to create Set?


1. Empty set is created using set() type
2. Set with existing iterable is created using set(iterable)
3. Set can be created curly braces with at least one element
{ele} ➔ set
{ele,ele,ele,ele,..} ➔ set
{} ➔ dictionary
Note: empty set cannot created using curly braces.
Set allows to perform mathematical set operations (union,
intersection, difference, …)
How to create Set?
1. Empty set is created using set() type
2. Set with existing iterable is created using set(iterable)
3. Set can be created curly braces with at least one element
{ele} ➔ set
{ele,ele,ele,ele,..} ➔ set
{} ➔ dictionary
Note: empty set cannot created using curly braces.
Set allows to perform mathematical set operations (union,
intersection, difference, …)
Some of the applications of set.
1. Removing duplicates from sequence
2. Membership testing
3. Performing mathematical set operations
Example
set1={10,20,30,40,50}
set2={10,10,10,10,10}
set3={} # this is not empty set, it is a dictionary
print(set1)
print(set2)
print(set3)
print(type(set1),type(set2),type(set3))

Example
# creating set using existing iterables
set1=set() # creating empty set
set2=set([10,20,30,40,50])
set3=set({10,20,30,40,50})
set4=set(range(10,60,10))
set5=set((10,20,30,40,50))
set6=set("PYTHON")
print(set1,set2,set3,set4,set5,set6,sep='\n')
How to read elements from set?
We can read elements from set using,
1. For loop
2. Iterator
3. Enumerator
Set does not allow indexing and slicing, because set is not index
based collection.
Example
# reading using for loop
set1={10,20,30,40,50}
for value in set1:
print(value)
# reading using iterator
it=iter(set1)
value1=next(it)
value2=next(it)
value3=next(it)
print(value1,value2,value3)
# reading using enumeration
e=enumerate(set1)
value1=next(e)
value2=next(e)
value3=next(e)
print(value1,value2,value3)

# write a program to remove duplicates from list

list1=[10,20,10,20,30,40,50,30,40,50]
set1=set(list1)
print(set1)
list2=list(set1)
print(list2)

# write a program to count each element is repeated how many


times within list
list1=[10,20,10,20,30,40,50,10,20]
set1=set(list1)
for value in set1:
c=list1.count(value)
print(c,"-",value,end=' ')

#output 3-30,3-20,1-30,1-40

# write a program to solve given problem


# string ==> abcabbcad
# output ==> 3a3b2c1d
str1=input("enter any string")
set1=set(str1)
str2=""
for ch in set1:
c=str1.count(ch)
str2=str2+str(c)+ch
print(str1)
print(str2)

set is a mutable collection, where we can add and remove objects


after creating set.

add(ele) : add element to set

set1=set()
print(set1)
set1.add(10)
set1.add(20)
set1.add(30)
set1.add(40)
set1.add(50)
print(set1)

# write a program read n objects into set


set1=set()

n=int(input("enter how many objects?"))


for i in range(n):
e=int(input("enter element"))
set1.add(e)
print(set1)

remove(ele) : this remove element from set. If element not exists in


set it raises KeyError.

set1={10,20,30,40,50}
print(set1)
set1.remove(10)
print(set1)
set1.remove(10)

discard(elem)

Remove element elem from the set if it is present.

set1={10,20,30,40,50}
print(set1)
set1.discard(100)
Set operations provided by set.
union(*others)
set | other | ...

Return a new set with elements from the set and all others.

intersection(*others)
set & other & ...

Return a new set with elements common to the set and all
others.

difference(*others)
set - other - ...

Return a new set with elements in the set that are not in the
others.

symmetric_difference(other)
set ^ other

Return a new set with elements in either the set or other but not
both.

Example:
A={1,2,3,4,5}
B={1,2,3,6,7}
C=A.union(B)
print(A,B,C,sep='\n')
D=A|B
print(A,B,D,sep='\n')
Example
python_students={'suresh','rajesh','kishore'}
java_students={'ramesh','naresh','kiran'}
python_java_students=python_students.union(java_students)
print(python_students)
print(java_students)
print(python_java_students)

Example
A={1,2,3,4,5}
B={1,2,3,5,6}
C={1,2,7,8,9}
D=A|B|C
print(D)
intersection(*others)
set & other & ...

Return a new set with elements common to the set and all others.

A={10,20,30,40,50}
B={10,20,40,50,60}
C=A.intersection(B)
print(A,B,C,sep='\n')

python_students={'suresh','kishore','rajesh','ramesh'}
java_students={'kishore','naresh','ramesh','kiran'}
both_students=python_students.intersection(java_students)
print(python_students)
print(java_students)
print(both_students)

A={1,2,3,4,5}
B={1,2,3,6,7}
C={6,7,8,9,10}
D=A&B&C
print(A)
print(B)
print(C)
print(D)

difference(*others)
set - other - ...

Return a new set with elements in the set that are not in the others.

A={1,2,3,4,5}
B={1,2,3,6,7}
C=A.difference(B)
print(A,B,C,sep='\n')
python_students={'naresh','suresh','kishore','ramesh'}
java_students={'naresh','kiran','rajesh','karan'}
only_python=python_students.difference(java_students)
only_java=java_students.difference(python_students)
print(python_students)
print(java_students)
print(only_python)
print(only_java)

symmetric_difference(other)
set ^ other

Return a new set with elements in either the set or other but not both.

A={1,2,3,4,5}
B={1,2,3,6,7}
C=A.symmetric_difference(B)
print(A,B,C,sep='\n')

update(*others)
set |= other | ...
Update the set, adding elements from all others.
intersection_update(*others)
set &= other & ...
Update the set, keeping only elements found in it and all
others.
difference_update(*others)
set -= other | ...
Update the set, removing elements found in others.
symmetric_difference_update(other)
set ^= other
Update the set, keeping only elements found in either set, but
not in both.
Example
products_list1={'keyboard','mouse','disk'}
products_list2={'monitor','printer'}
products_list1.update(products_list2)
print(products_list1)
Example
A={1,2,3,4,5}
B={1,2,3,6,7}
A.intersection_update(B)
print(A)
Example
python_students={'naresh','suresh','kishore','kiran'}
java_students={'naresh','kiran','ramesh'}
python_students.difference_update(java_students)
print(python_students)
Example
A={1,2,3,4,5}
B={1,2,3,6,7}
A.symmetric_difference_update(B)
print(A)

isdisjoint(other)

Return True if the set has no elements in common with other. Sets are
disjoint if and only if their intersection is the empty set.

A={1,2,3,4,5}
B={6,7,8,9,10}
res=A.isdisjoint(B)
print(A,B,res,sep='\n')

sales_2019={10000,20000,30000,40000,50000}
sales_2020={10000,30000,60000,70000,90000}
b=sales_2019.isdisjoint(sales_2020)
print(b)

issubset(other)
set <= other

Test whether every element in the set is in other.

A={1,2,3,4,5}
B={1,2,3,4,5,6,7,8,9,10}
res=A.issubset(B)
print(A,B,res,sep='\n')

issuperset(other)
set >= other

Test whether every element in other is in the set.

A={1,2,3}
B={1,2}
res=A.issuperset(B)
print(A,B,res,sep='\n')

FrozenSet
Frozenset is immutable collection, after creating frozenset we cannot
modify.
Fronzenset is used to define a set in side set or nested set.
Inorder to define nested set the inner set must be frozenset because
frozenset is hashable.
How to create frozenset?
Frozenset is created using frozenset type or class.
Syntax:
Forzenset() ➔ creating empty frozenset
Forzenset(iterable) ➔ creating frozenset with iterable

>>> set1={{1,2,3}}
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
set1={{1,2,3}}
TypeError: unhashable type: 'set'

Nested sets are not possible directly, in order to create set inside set
we should use frozenset.

>>> f1=frozenset()
>>> f1.add(10)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
f1.add(10)
AttributeError: 'frozenset' object has no attribute 'add'

>>> s=set()
>>> s.add(10)
>>> s
{10}
>>> s1={frozenset(range(1,6)),frozenset(range(6,11))}
>>> s1
{frozenset({1, 2, 3, 4, 5}), frozenset({6, 7, 8, 9, 10})}
>>> for s in s1:
print(s)
frozenset({1, 2, 3, 4, 5})
frozenset({6, 7, 8, 9, 10})
>>> for s in s1:
for value in s:
print(value)

1
2
3
4
5
6
7
8
9
10
>>>

Q: What is difference between list and set?


List Set
List is ordered collection. Set is unordered collection.
List is index based collection Set is non index based collection
List allows indexing and slicing Set does not allows indexing and
slicing.
List allows duplicates Set does not allows duplicates
Insertion is preserved. Insertion order is not preserved
It allows any object It allows only hashable object
List is created using [] set is created using {ele,…}
We cannot do mathematical It allows mathematical set
operations.
Set operations
Dictionary or map collection

A mapping object maps hashable values to arbitrary objects.


Mappings are mutable objects. There is currently only one standard
mapping type, the dictionary
A dictionary’s keys are almost arbitrary values. Values that are not
hashable, that is, values containing lists, dictionaries or other mutable
types (that are compared by value rather than by object identity)
may not be used as keys.

Each key in dictionary is mapped with one or more values.


Duplicate keys are not allowed but duplicate values are allowed.
The key must be hashable type but the value can be of any type.

How to create dictionary?


The dictionary is created using,
1. {} ➔ create empty dictionary
2. {key:value,key:value,key:value,…} ➔ create dictionary with key
and value pair, the key and value is separated with :
3. dict() ➔ create empty dictionary
4. dict(iterable) ➔ create dictionary using existing iterable.
Example
>>> dict1={1:'one',2:'two',3:'three'}
>>> dict1
{1: 'one', 2: 'two', 3: 'three'}
>>> dict2={}
>>> dict2
{}
>>> type(dict1)
<class 'dict'>
>>> type(dict2)
<class 'dict'>
>>>
>>> dict3={1:10,1:20,1:30} # it will update key with last value
>>> dict3
{1: 30}
>>>
1. dict() ➔ create empty dictionary
2. dict(iterable) ➔ create dictionary using existing iterable.
>>> dict1=dict()
>>> print(dict1)
{}
>>> dict1=dict([(1,10),(2,20),(3,30),(4,40),(5,50)])
>>> dict1
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
>>> dict2=dict(zip([1,2,3,4,5],['one','two','three','four','five']))
>>> dict2
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>>

In order to create dictionary using list, the list should consist of a tuple
which is key and value pair.

We can create dictionary using zip(), this function using multiple


iterables. This function return iterable which contain tuple by reading
value of first iterable and value of second iterable.

zip([1,2,3],[‘one’,’two’,’three’])

[(1,’one’),(2,’two’),(3,’three’)]

How to read content of dictionary?

The content of dictionary can be read in different ways.

1. Dictionary is key based, we can read value using key


dictionary-name[key] ➔ if key is exists return value of that key
otherwise raises KeyError

Example

courses_dict={'java':2000,'oracle':1000,'python':4000,'c':1000}
print(courses_dict)
fee1=courses_dict['java']
fee2=courses_dict['python']
fee3=courses_dict['c']
print(fee1,fee2,fee3)
# fee4=courses_dict['django'] it raises KeyError

2. Using for loop, for loop each time iterate/read key from
dictionary.

Example

students_dict={1:['naresh','python'],2:['suresh','java'],3:['kishore','cpp']}
print(students_dict)
for rno in students_dict:
print(rno,students_dict[rno])

Example

players_dict={'rahul':40,'hardhik':90}
for name in players_dict:
print(name,players_dict[name])

3. Dictionary provides the following methods which return


different dictionary views. Each view is one iterable. There are
3 views.
i. Key view
ii. Values view
iii. Items view
keys()
Return a new view of the dictionary’s keys.
values()
Return a new view of the dictionary’s values
items()
Return a new view of the dictionary’s items ((key, value) pairs).

telephone_dir={'naresh':998877665,'suresh':77788777,'kishore':4556677
8}
print(telephone_dir)
names_view=telephone_dir.keys()
print(names_view)
phone_view=telephone_dir.values()
print(phone_view)
for name in names_view:
print(name)
for no in phone_view:
print(no)
d=telephone_dir.items()
print(d)
for t in d:
print(t)

for name,no in d:
print(name,no)

4. Get method of dictionary type. Get method of dictionary type


read value of given key. This method avoid keyError by
returning default value if key is not exists.

get(key,default)

the default value of default is None.

dict1={1:'one',2:'two',3:'three'}
value=dict1[1]
print(value)
value=dict1.get(10,0)
print(value)
value=dict1.get(10)
print(value)

Dictionary is mutable collection, after creating dictionary we can


add, update and detete items.
Adding item inside dictionary
Dict-name[key]=value
If key is not exists, it add key with given value inside dictionary
Example:
dict1={}
print(dict1)
dict1[1]=10
dict1[2]=20
dict1[3]=30
print(dict1)
If key exists it update key with given value.
Example
# write a program to create telephone directory
tele_dict={}
while True:
name=input("Enter name")
no=int(input("Enter phone no"))
if name in tele_dict:
print("contact exists")
else:
tele_dict[name]=no
ans=input("Enter another contact?")
if ans=='no':
break
for name,no in tele_dict.items():
print(name,no)

updating dictionary
the dictionary value can be updated using key. If the key is exists it
update the value, if key is not exists add new item.

Dict-name[key]=value
Update(iterable)

Example
dict1={1:10,2:20,3:30,4:40}
dict2={1:100,3:300,5:500,6:600}
print(dict1)
dict1.update(dict2)
print(dict1)
In order to update or add more than one item using update
method.

Example
dict1={1:100,2:200,3:300,4:400}
print(dict1)
dict1[1]=10
print(dict1)

How to delete item from dictionary


Deleting item from dictionary can be done in different ways.
1. del dict-name[key] : if key is exists it delete item, otherwise
raises KeyError
2. clear()
Remove all items from the dictionary.

Example
dict1={1:10,2:20,3:30,4:40,5:50}
print(dict1)
del dict1[2]
print(dict1)
dict1.clear()
print(dict1)
dict2={1:100,2:200,3:300,4:400}
print(dict2)
i=dict2.popitem()
print(i)
print(dict2)
***Shoping Cart***
1.Adding Porduct
2.Updating Product
3.Deleting Product
4.View Products
5.Exit
Enter your option:

product_dict={}
while True:
print("****Shoping Cart****")
print("1. Add Product")
print("2. Update Product")
print("3. Delete Product")
print("4. View Products")
print("5. Exit")
opt=int(input("Enter your option"))
if opt==1:
pname=input("Enter product name")
qty=int(input("Enter Qty"))
product_dict[pname]=qty
print("Product Added")
elif opt==2:
pname=input("Enter product name")
if pname in product_dict:
qty=int(input("enter qty"))
product_dict[pname]=qty
print("product updated")
else:
print("Product not exists")
elif opt==3:
pname=input("Enter product name to delete")
if pname in product_dict:
del product_dict[pname]
print("product deleted")
else:
print("product not exists")
elif opt==4:
for pname,qty in product_dict.items():
print(pname,qty)
elif opt==5:
break

Dictionary Comprehension
Dictionary comprehension allows to create dictionary using for loop
and test conditions.
Comprehension is elegant way creating dictionary.

{key:value for variable in iterable}


{key:value for variable in iterable if test}

Example
sales_dict1={'naresh':10000,'suresh':20000,'kishore':30000,'rajesh':35000
}
print(sales_dict1)
# without comprehension creating dictionary from existing dictionary
sales_dict2={}
for name,sales in sales_dict1.items():
sales_dict2[name]=sales
print(sales_dict2)
# with comprehension
sales_dict3={name:sales for name,sales in sales_dict1.items()}
print(sales_dict3)
Example
sales_dict1={'naresh':10000,'suresh':20000,'kishore':30000,'rajesh':35000
}
print(sales_dict1)

sales_dict2={name:sales for name,sales in sales_dict1.items() if


sales<=20000}
print(sales_dict2)
sales_dict3={name:sales for name,sales in sales_dict1.items() if
sales>20000}
print(sales_dict3)

Functions
Python is multi paradigm programming language. It allows writing
programs using different programming methods or approaches.
Python support procedural oriented programming.
In procedural oriented programming instructions are organized by
dividing according their operations into small pieces and these small
pieces are called subroutines or functions.

Q: What is function?
A function is building block of procedural oriented programming.
A function is small program within program.
A function is named block, which consists instructions to perform
operation.
Adv of functions
1. Modularity : dividing programming instructions according to
their operations into small pieces, which are called functions.
2. Readability: Easy to understand
3. Reusability: It allows writing the code once and using number of
times.
4. Efficiency: reusability reduces the size of program, which
increase efficiency.

Syntax of writing function


def <function-name>([arguments]):
‘’’doc string’’’
Statement-1
Statement-2
Statement-3
“def” is a keyword which is used to write definition of function or to
define function.
Arguments are receivers or variables, which receive values from
another function.
‘’’doc string’’’ is documentation or comments of function.
A function is block and must have at least one statement. We can
define function without any statement using pass.

Example
def fun1():
print("Hello function1")
fun1() # calling the fun1/executing fun1/executable statement

A function is never called automatically, it has to be called explicitly


as an executable statement.
Example
def f1():
print("inside f1")
def f2():
print("inside f2")
def f3():
print("inside f3")
def main(): # main logic
f1()
f2()
f3()
main()

main is a user defined function, which contain executable


statements or main logic of application/program.
We can define the function with,
1. With arguments
2. Without arguments
Function without an argument, which does not receive value from
calling or another function.

# function without arguments


def fun1(): # called function
print("inside fun1")
def fun2(): # called function
print("inside fun2")
def fun3(): # called function
print("inside fun3")

def main(): # calling function


fun1() # calling fun1
fun2() # calling fun2
fun3() # calling fun3

main() # this is calling main function

# function without arguments


def drawline():
for i in range(1,30):
print("*",end='')
print()

def main():
drawline()
print("PYTHON LANGUAGE")
drawline()
print("PROGRAMMING LANGUAGE")
drawline()
main()

If function does not required input from calling function, it is defined


without arguments.

Local variables

The variables declared inside function are called local variables.


Local variables memory is allocated when ever function is called
and de-allocated after execution of function.

Local variables are used within function but cannot used outside the
function.

Example:
def fun1():
x=100 # local variable

def main():
print(x) # cannot access local variable x of fun1 inside main

main()
Example
def add():
n1=100 # local variable
n2=200 # local variable
n3=n1+n2 # local variable
print(n3)

def main():
add()

main()

Global variables
The variables declared outside the function are called global
variables. Global variables can be anywhere within program or
outside the program.

Example:
x=100
y=200
def fun1():
print(x)
print(y)
def fun2():
print(x)
print(y)
def main():
print(x)
print(y)
fun1()
fun2()
main()

Example:
x=10
y=5
def add():
print(x+y)
def sub():
print(x-y)
def multiply():
print(x*y)
def div():
print(x/y)
def main():
add()
sub()
multiply()
div()
main()

Example
x=100
def fun1():
x=200 # creating local variable with name x inside fun1
print(x) # because in python variable is created by assigning value
def fun2():
print(x)

def main():
fun1()
fun2()
main()
How modify or update global variable within function?

global keyword

global keyword is used to modify or update global variables within


function or it is used to create global variable with in function.

global variable-name,variable-name

if variable name exists with global, it changes the value.


If variable name not exists within global, it create new variable in
global scope.
Example
x=100
def fun1():
global x
x=200
print(x)
def fun2():
print(x)

def main():
fun1()
fun2()

main()
base=0 # global variable
height=0 # global variable
def read():
global base,height
base=float(input("Enter base"))
height=float(input("Enter height"))
def find_area():
area=base*height*0.5
print("Area of triangle",area)

def main():
read()
find_area()
main()

create global variables within function


def fun1():
global x,y # creating global variables within function
x=100
y=200

def fun2():
print(x)
print(y)
def main():
fun1()
fun2()
main()

Function with arguments


Arguments are receivers, which receive values from another
function. Arguments are local variables. Python allows writing a
function with 4 types of arguments.
1. Required arguments
2. Default arguments
3. Variable length arguments
4. Keyword arguments
Required arguments
A function with required arguments must be given values for each
argument at the time of calling the function.
Each argument required value at the time of calling the function.

def <function-name>(arg1,arg2,arg3,…):
statement-1
statement-2
Example:
def fun1(a,b):
print(a,b)

def main():
fun1(100,200)
fun1(a=100,b=300)
fun1(b=100,a=200)
fun1() # error
main()

return keyword

a function not only receive values, it also return value. Called


function return value to calling function using return keyword.
Return terminate the execution of function by returning value.

return <value>/<expression>
Example of function which return value
def add(n1,n2):
n3=n1+n2
return n3 # return value to calling function
def sub(n1,n2):
n3=n1-n2
return n3 # return value to calling function
def multiply(n1,n2):
n3=n1*n2
return n3 # return value to calling function
def div(n1,n2):
n3=n1/n2
return n3 # return value to calling function
def main(): # calling function
res1=add(100,200)
res2=sub(10,5)
res3=multiply(5,2)
res4=div(4,2)
print(res1)
print(res2)
print(res3)
print(res4)
main()

Example
def draw_line(ch,length): # required arguments
for i in range(length):
print(ch,end='')
print()

def main():
draw_line("*",10)
print("Hello")
draw_line("$",5)
print("Python")
draw_line("%",30)
main()

Function with default arguments


Arguments which are assigned values at the time defining function.
If the values are not given to these arguments, it takes default
values.

Syntax:
def <function-name>(arg1,arg2=value,arg3=value):
statement-1
statement-2

arg1➔ is required argument


arg2,arg3 ➔ are default arguments, which are given default values.

Example
def fun1(a,b=10):
print(a,b)
def main():
fun1(100,200)
fun1(200)
main()
Function with default arguments
Arguments which are assigned values at the time defining function.
If the values are not given to these arguments, it takes default
values.

Syntax:
def <function-name>(arg1,arg2=value,arg3=value):
statement-1
statement-2

arg1➔ is required argument


arg2,arg3 ➔ are default arguments, which are given default values.

Example
def fun1(a,b=10):
print(a,b)
def main():
fun1(100,200)
fun1(200)
main()

Example
def draw_line(ch='*',length=30):
for i in range(length):
print(ch,end='')
print()
def main():
draw_line()
draw_line('#')
draw_line('$',20)
draw_line(length=10)
main()
Example
def string_conversion(s,case='upper'):
s1=''
for ch in s:
if case=='upper':
if ch>='a' and ch<='z':
s1=s1+chr(ord(ch)-32)
else:
s1=s1+ch
elif case=='lower':
if ch>='A' and ch<='Z':
s1=s1+chr(ord(ch)+32)
else:
s1=s1+ch
return s1
def main():
str1=string_conversion("python")
str2=string_conversion("PYTHON",case='lower')
print(str1)
print(str2)
main()

Example
def sort_data(data,order='ascending'):
if order=='ascending':
for i in range(len(data)):
for j in range(len(data)-1):
if data[j]>data[j+1]:
data[j],data[j+1]=data[j+1],data[j]
elif order=='descending':
for i in range(len(data)):
for j in range(len(data)-1):
if data[j]<data[j+1]:
data[j],data[j+1]=data[j+1],data[j]

def main():
list1=[10,4,1,8,2,9,6]
sort_data(list1)
print(list1)
sort_data(list1,'descending')
print(list1)
main()

Function with variable length arguments


An argument which receive zero or more values, that function is
defined with variable length argument.
Variable length argument is prefix with *
Variable length argument is of type tuple.

def function-name(arg1,arg2=value,*arg3):
statement-1
statement-2
arg1 ➔ is a required argument
arg2 ➔ is default argument
arg3 ➔ variable length argument
Example:
def fun1(*n):
print(n)
print(type(n))
def main():
fun1()
fun1(10)
fun1(10,20)
fun1(10,20,30)
fun1(10,20,30,40)
main()
Example
def maximum(*n):
m=0
for i in range(len(n)):
if m<n[i]:
m=n[i]
return m
def main():
m1=maximum()
print(m1)
m2=maximum(10,20)
print(m2)
m3=maximum(4,1,2)
print(m3)
main()

Example
def add(*value):
s=0
for i in range(len(value)):
s=s+value[i]
return s

def main():
s1=add(10,20)
s2=add(10,20,30)
s3=add(10,20,30,40)
print(s1,s2,s3)
main()

Keyword arguments
Keyword arguments receive values as key, value pair.
Keyword arguments are of type dictionary.
Dictionary consist of key and value.
Keywords argument is prefix with **
Syntax:
def <function-name>(arg1,arg2=value,*arg3,**arg4):
statement-1
statement-2
statement-3

arg1 ➔ is a required argument


arg2 ➔ is default argument
arg3 ➔ is variable length argument
arg4 ➔ keyword argument

Example
def fun1(**k):
print(k)
print(type(k))
def main():
fun1(a=10,b=20)
fun1(x=100,y=200)
main()

Example
def simple_intrest(**kwargs):
si=kwargs['amt']*kwargs['time']*kwargs['rate']/100
return si

def main():
si1=simple_intrest(amt=5000,time=12,rate=1.5)
print("Simple intrest",si1)
main()
Generators or Generator function
Generator a special function which return generator iterator.
Generators are used to generate range of value. It allows to
develop customized range.

Generator function returns value using yield statement.


“yield” is a keyword, this keyword after returning value, it pause
execution, next iteration, it resume the generator.

Generator function must have yield statement.

Example
def fun1():
yield 10
yield 20
yield 30
yield 40
yield 50

def main():
n=fun1() # creating generator iterator object
print(next(n))
print(next(n))
print(next(n))
print(next(n))
print(next(n))
print(next(n)) # error
main()
Example
def alpha_generator():
for n in range(65,91):
yield chr(n)

def main():
alpha=alpha_generator() # creating generator iterator
print(next(alpha))
for c in alpha:
print(c,end=' ')
main()

Example
def prime_generator(m,n):
for num in range(m,n+1):
c=0
for i in range(1,num+1):
if num%i==0:
c=c+1
if c==2:
yield num
def main():
prime=prime_generator(5,50)
for value in prime:
print(value)
main()
Example
import random
def otp_generator():
while True:
n1=random.randint(0,9)
n2=random.randint(0,9)
n3=random.randint(0,9)
n4=random.randint(0,9)
n5=random.randint(0,9)
yield str(n1)+str(n2)+str(n3)+str(n4)+str(n5)
def main():
otp=otp_generator()
otp1=next(otp)
otp2=next(otp)
otp3=next(otp)
print(otp1,otp2,otp3)
main()

You might also like