Full Stack Python YT
Full Stack Python YT
Topics
======
Introduction to Languages
What is Language?
Types of Programming Languages
Translators
o Interpreter
o Compiler
Scripting Language
Difference between Programming Language and Scripting Language
Programming Paradigms
o Procedural Oriented Programming
o Object Oriented Programming
What is language?
A language is software, which provides set of instructions for developing
software’s.
Language acts as mediator between user and computer.
1. Machine Language
2. Assembly Language
Machine Language
Machine language instructions are represented in 0’s and 1’s.
Computer understands only one language called machine language.
Machine language instructions are machine dependent (OR) hardware
dependent.
Machine language instructions are not easy to understand.
Machine Language does not require any translator.
Assembly Language
Assembly language is low level language, but instructions are not given in
0’s and 1’s but instructions are represented in mnemonics (verbs).
ML AL
1010 1111 MOVE
What is assembler?
Assembler is a translator used by assembly language for converting
assembly language instructions into machine language.
Example: C,C++,COBOL,PASCAL,Java,Python,.Net,JavaScript
What is translator?
Translator is software, which convert instructions of one language to
another language.
1. Interpreter
2. Compiler
What is translator?
Translator is software, which converts instructions of one language to
another language.
1. Interpreter
2. Compiler
What is program?
A program is set of instructions.
What is interpreter?
Interpreter is a translator, which translates and executes instructions line
by line.
Interpreter stops translating and executing, if there is an error in one
line. Interpreted code executed by machine directly. Interpreter displays
one error at a time. Debugging program is complex.
Scripting languages uses interpreter as a translator.
What is compiler?
Compiler is a translator, which translates whole program and execute.
Compiler display all error exist within program. If there is error within
program, compiler not generates executable code/file.
What is scripting language?
A scripting language is one type of programming language which is used
for writing scripts.
What is a script?
A script is a small program executed within another program.
Scripts are embedded within another program.
Scripts are used for automation.
Programming paradigm
A programming paradigm defines a set of rules and regulations for writing
programs.
1. Procedural Oriented Programming (POP)
2. Modular Oriented Programming (MOP)
3. Object Oriented Programming (OOP)
4. Functional Oriented Programming (FOP)
What is Python?
Python is a programming language.
Python is a general purpose programming language. This language is used
for developing any type of software or application.
Python is high level programming language. All high level languages are in
simple English. High level languages are portable. Portability allows
developing and running applications on different hardware architecture.
Python is multi paradigm programming language. A programming
paradigm defines set of rules and regulations for writing program. Python
is object oriented programming language and also supports other
programming paradigms (POP, MOP, FOP, SOP).
Applications of Python
In real time or software companies uses python for developing which type
of software’s or applications or projects.
What is library?
A library is set of predefined programs with pre-written functionality.
Python provides huge set of libraries.
A language uses libraries for developing different types of applications.
What is Framework?
Framework is software which provides libraries.
Framework provides development environment and execution
environment.
Python History
Python History
Python was conceived in the late 1980s by Guido van Rossum at Centrum
Wiskunde & Informatica (CWI) in the Netherlands as a successor to the
ABC programming language, which was inspired by SETL, capable of
exception handling and interfacing with the Amoeba operating system. Its
implementation began in December 1989.
First Version of python is released in the year 1991.
Python is product of or Python language is managed by non-profit
organization called PSF (Python Software Foundation).
Python language is implemented or developed in C language.
Python language is developed by taking features from various
programming languages.
1. C (Procedural Oriented Programming)
2. C++ (Object Oriented Programming)
3. Perl (Scripting Language)
4. Modula7 (Modular Programming)
Python name is taken from a comedy series called “Monty Python’s Flying
Circus”
Python Versions
Versions are nothing but changes within python language or software.
Python comes in 3 Versions.
1. Python 1
2. Python 2
3. Python 3
What is PEP?
PEP stands for Python Enhancement Proposal. It is a technical document
which consists of changes done within python language.
Python Features
Python features are nothing but facilities provided by python language to
software developers.
1. Easy or Simple
2. Free and Open Source
3. Large Standard Libraries
4. Platform Independent
5. Dynamic
6. Portable
7. High Level
8. Object Oriented
9. Extensible
10. Embeddable
11. Robust
Easy or Simple
Python Features
Python features are nothing but facilities provided by python language to
software developers.
1. Easy or Simple
2. Free and Open Source
3. Large Standard Libraries
4. Platform Independent
5. Dynamic
6. Portable
7. High Level
8. Object Oriented
9. Extensible
10. Embeddable
11. Robust
Easy or Simple
Python is easy or simple because it provides the following features which
makes python is easy or simple.
1. Python Syntax is Simple
2. Python is user/programmers friendly programming language, It
allows you to write programs using multiple programming
paradigms.
3. Less Coding, python provides large standard libraries, which
provides predefine code.
4. Automatic memory management. In application development
memory managed consist of two things
a. Allocation of memory
b. De-Allocation of memory
In python memory management is automatic; python provides a
service called garbage collection.
www.pypi.org
1. Modules
2. Packages
Platform Independent
Programming languages are two types
1. Platform dependent languages
2. Platform independent languages
What is platform?
Platform is software, which provides development environment and
execution environment. Operating System is called platform. Operating
system acts as an interface between software and hardware.
What is platform?
Platform is software, which provides development environment and
execution environment. Operating System is called platform. Operating
system acts as an interface between software and hardware.
Dynamic
Programming languages are two types
1. Statically typed programming languages
2. Dynamically typed programming languages
High Level
Portable
Embeddable
Extensible
Robust
High Level
Python is high level programming language and all high level programming
language is in simple English.
Portable
Portability allows developing and running python program on any device
or hardware architecture.
Robust
Robust means strong
Python is very strong in error checking.
Python provides an exception handling, using which a program can handle
runtime error to avoid abnormal termination program.
Python Software
Python software is free to download.
www.python.org
How to verify python software is installed or not?
2.
IDE’s
1. Pycharm
2. Spyder
3. VSCode
4. Google Collab
5. Jupiter Notebook
Python Distributions
Python distribution is python software bundle which consists of,
1. Python software
2. Application Specific Libraries
3. Editors or IDE
Python Implementations
IronPython (Python running on .NET)
Jython (Python running on the Java Virtual Machine)
PyPy (A fast python implementation with a JIT compiler)
Stackless Python (Branch of CPython supporting microthreads)
MicroPython (Python running on micro controllers)
Interactive mode
Python working modes
Python working modes are two,
1. Interactive mode
2. Scripting mode/programming mode
Interactive mode
In interactive mode python developer or programmer works with python
shell.
Python shell is command line interface or python shell is REPL tool
REPL stands for Read-Evaluate-Print-Loop.
Python shell is single line command line interface.
In interactive mode programmer cannot develop or write programs.
2.
3.
Working with interactive mode using IDE or Editor
Every editor allows working in two modes.
1. Interactive mode
2. Scripting mode or Programming mode
Open IDLE
Search à IDLE
Programming Mode or Scripting Mode
In programming mode, python developer creates a program or file by
storing all the instructions. This file or program can be executed one or
more than one time. Every python program is saved with extension .py
(source file or source program).
Every python program is called module.
Open Notepad
Type program and save with extension .py
Open IDLE
Select File à New File
Type Python Program
UNICODE super set of ASCII, It support characters of ASCII and also having
more number of characters support from other languages.
Python and all modern languages support ascii and Unicode character
set.
Uppercase Letters A – 65
B -66
…
Z – 90
Lowercase Letters a -97
b-98
…
z-122
Tokens
A token is smallest individual unit within program.
Without tokens a statement cannot created.
1. Keywords
2. Identifiers
3. Literals
4. Data types
5. Operators
Keywords
Keywords are language related words. The meaning of keyword is
reserved by python translator.
Each keyword is used to perform specific operation.
Soft Keywords
Soft keywords can be used as user defined word or identifiers.
>>> keyword.softkwlist
['_', 'case', 'match', 'type']
Identifiers
Identifier is programmer defined words or user defined words. Identifier
is used to identify programming elements.
1. Variable names
2. Function names
3. Data type names
4. Program name / Module name
5. Package name
Identifier is a single word, this word is created using alphabets (a-z, A-Z),
digits (0-9) and one special character (_)
Identifiers
Identifier is programmer defined words or user defined words. Identifier
is used to identify programming elements.
1. Variable names
2. Function names
3. Data type names
4. Program name / Module name
5. Package name
Identifier is a single word, this word is created using alphabets (a-z, A-Z),
digits (0-9) and one special character (_)
>>> a=10
>>> a
10
>>> rollno=1
>>> rollno
1
>>> pass=100
SyntaxError: invalid syntax
>>> break=1
SyntaxError: invalid syntax
>>> class=5
SyntaxError: invalid syntax
>>> Pass=1
>>> Pass
1
>>> A=10
>>> a=20
>>> A
10
>>> a
20
amt$=10
SyntaxError: invalid syntax
$amt=1
SyntaxError: invalid syntax
>>> a*mt=1
SyntaxError: cannot assign to expression here. Maybe you meant '=='
instead of '='?
>>> stud_rollno=1
>>> stud_rollno
1
>>> _=1
>>> _
1
>>> __x__=10
>>> __x__
10
5. Identifier should start with alphabet or _ but should not start with
digit
>>> number1=100
number2=200
>>> number1
100
>>> number2
200
>>> 3number=300
SyntaxError: invalid decimal literal
>>> _number=400
>>> _number
400
>>> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=10
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
10
>>> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb=100
>>> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
100
>>> a=10
>>> b=20
>>> a+b
30
Naming Conventions
Naming Conventions are nothing but naming rules, this naming convention
makes application easy to understand.
1. pascal case
2. snake case
3. camelcase
Data types
Scalar data types are used to allocate memory for one value or single
value.
1. int
2. float
3. complex
4. bool
5. NoneType
Collection data types are used to allocate memory for more than one
value. Collection data types are classified into 3 categories
1. Sequences
a. List
b. Tuple
c. Range
d. Str
e. Bytes
f. Bytearray
2. Sets
a. Set
b. Frozenset
3. Mapping
a. Dict
These 14 data types are called python standard data types
Literals
Literals are values which never changed.
Python literals are classified into two categories
1. Numeric
2. Non-Numeric
Numeric : integer, float, complex
Non Numeric: str, None, bool
What is class?
A class represents data type.
Class is used to allocate memory for data or object.
Class defines structure of object.
Class is a blue print of object
Class defines properties and behavior of object.
Properties defines the values hold by object
Behavior defines the functionality of object
What is object?
An object is instance of a class
Allocating memory for members/properties of the class is process of
creating object.
Object is an implementation of a class.
Python is a dynamically typed programming language, variables are not
bind with specific data type or variables are not declared with any data
type.
int a; a=10
a=10; type(a) 🡪 int
a=1.5; Error a=1.5
type(a) 🡪 float
What is variable?
Variable is an identifier, which is used to identify value/object.
Variable is named memory location.
>>> a=123
>>> type(a)
<class 'int'>
>>> a
123
>>> b=560
>>> type(b)
<class 'int'>
>>> b
560
In python integer values are represented in 4 formats
1. Decimal
2. Octal
3. Hexadecimal
4. Binary
Size of int data type is dynamic. The memory is allocated based value
size. Int data type size is unlimited.
>>>
x=9999999999999999999999999999999999999999999999999999999999999
999
>>> x
999999999999999999999999999999999999999999999999999999999999999
9
>>> import sys
>>> sys.getsizeof(x)
56
>>> y=100
>>> sys.getsizeof(y)
28
>>> z=8999999999999999999
>>> sys.getsizeof(z)
36
Decimal Integer
An integer value with base 10 is called decimal integer.
This integer is created using all the digits from 0-9.
This integer is not prefix with 0
This integer is prefix with + or –
Default representation of integer values are in decimal format.
>>> a=0123
SyntaxError: leading zeros in decimal integer literals are not permitted;
use an 0o prefix for octal integers
Decimal Integer
An integer value with base 10 is called decimal integer.
This integer is created using all the digits from 0-9.
This integer is not prefix with 0
This integer is prefix with + or –
Default representation of integer values are in decimal format.
>>> a=0123
SyntaxError: leading zeros in decimal integer literals are not permitted;
use an 0o prefix for octal integers
>>> amt1=500
>>> amt1
500
>>> type(amt1)
<class 'int'>
>>> amt2=1_500
>>> amt2
1500
>>> amt3=1_50_000
>>> amt3
150000
>>> a=10_
SyntaxError: invalid decimal literal
>>> b=_10
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
b=_10
NameError: name '_10' is not defined
Octal Integer
An integer value with base 8 is called octal integer.
Octal integer is created using digits range from 0-7.
This integer is prefix with 0o or 0O
Example:
>>> a=0o45
>>> type(a)
<class 'int'>
>>> b=0o89
SyntaxError: invalid digit '8' in octal literal
>>> c=0o278
SyntaxError: invalid digit '8' in octal literal
>>> b=0o35
>>> b
29
>>> c=0o125
>>> c
85
Hexadecimal Integer
An integer value with base 16 is called hexadecimal integer.
This integer is created using 16 digits 0-9,a-f/A-F
This integer is prefix with 0x or 0X.
Larger integer values are represented in hexadecimal format.
>>> n1=0xa
>>> n1
10
>>> n2=0xb
>>> n2
11
>>> n3=0xf
>>> n3
15
>>> n4=0xg
SyntaxError: invalid hexadecimal literal
>>> n5=0xabc
>>> n5
2748
>>> n6=0xff
>>> n6
255
>>> n6=0xbad
>>> n6
2989
Binary Integer
An integer value with base 2 is called binary integer.
Binary integer is created using two digits 0 and 1
Binary integer is prefix with 0b or 0B
>>> n1=0b10
>>> n1
2
>>> n2=0b1010
>>> n2
10
>>> n3=0b1012
SyntaxError: invalid digit '2' in binary literal
Binary Integer
An integer value with base 2 is called binary integer.
Binary integer is created using two digits 0 and 1
Binary integer is prefix with 0b or 0B
>>> n1=0b10
>>> n1
2
>>> n2=0b1010
>>> n2
10
>>> n3=0b1012
SyntaxError: invalid digit '2' in binary literal
>>> rollno=125
>>> rollno
125
>>> accountNo=123456999
>>> accountNo
123456999
>>> color=0xff0000
>>> color
16711680
>>> color=0xff
>>> color
255
Example:
>>> a=60
>>> a
60
>>> id(a)
140716079894808
>>> b=90
>>> id(b)
140716079895768
>>> a=80
>>> a
80
>>> id(a)
140716079895448
Example:
>>> x=10
>>> y=10
>>> z=10
>>> x
10
>>> y
10
>>> z
10
>>> id(x)
140716079893208
>>> id(y)
140716079893208
>>> id(z)
140716079893208
>>> p=5+5
>>> p
10
>>> id(p)
140716079893208
Example:
>>> a=12
>>> a
12
>>> bin(a)
'0b1100'
>>> hex(a)
'0xc'
>>> oct(a)
'0o14'
>>> b=0xc
>>> b
12
>>> bin(b)
'0b1100'
>>> oct(b)
'0o14'
>>> bin(4000)
'0b111110100000'
c=0o12
>>> c
10
>>> oct(c)
'0o12'
>>> hex(c)
'0xa'
>>> bin(c)
'0b1010'
>>> f1=12.456
>>> f1
12.456
>>> f2=12456e-3
>>> f2
12.456
>>> f3=1.234e2
>>> f3
123.4
In scientific notation one special character used in float value called “e”,
the value of “e” is 10.
>>> a=1.7976931348623157e+308
>>> a
1.7976931348623157e+308
>>> b=1.7976931348623157e+309
>>> b
inf
>>> c=0b1010.10
SyntaxError: incomplete input
>>> d=0xab.a
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
d=0xab.a
AttributeError: 'int' object has no attribute 'a'
>>> c1=1+2j
>>> c1
(1+2j)
>>> type(c1)
<class 'complex'>
>>> c1.real
1.0
>>> c1.imag
2.0
>>> c2=2j
>>> c2
2j
>>> type(c2)
<class 'complex'>
>>> c2.real
0.0
>>> c2.imag
2.0
>>> c2.real=1.0
Traceback (most recent call last):
File "<pyshell#78>", line 1, in <module>
c2.real=1.0
AttributeError: readonly attribute
Example:
>>> a=True
>>> a
True
>>> type(a)
<class 'bool'>
>>> b=False
>>> b
False
>>> type(b)
<class 'bool'>
>>> c=1
>>> c
1
>>> type(c)
<class 'int'>
>>> d=10>2
>>> d
True
NoneType
NoneType represent None value.
In python None is represented as missing value or no value.
>>> rollno=1
>>> name=None
>>> fee=4000.0
>>> feePaid=True
>>> rollno
1
>>> name
>>> fee
4000.0
>>> feePaid
True
>>> a=None
>>> a
>>> type(a)
<class 'NoneType'>
string
String
Example:
>>> s1='python'
>>> s1
'python'
>>> s2='python 3.12'
s2
>>> 'python 3.12'
>>> s3='45'
>>> n1=45
>>> n1+10
55
>>> s3+10
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
s3+10
TypeError: can only concatenate str (not "int") to str
>>> s4='python is a
SyntaxError: incomplete input
>>> s4='python is "high" programming language'
>>> print(s4)
python is "high" programming language
>>> s5='python is a 'high level' programming language'
SyntaxError: invalid syntax
>>> str1="python"
>>> print(str1)
python
>>> str2="python 3.12"
>>> print(str2)
python 3.12
>>> str3="45"
>>> print(str3)
45
>>> str4="python is high level
SyntaxError: incomplete input
>>> rollno=101
>>> name="nk"
>>> course="FSP"
>>> description=''' Full Stack Python consists of 5 Modules
Module1: Python
Module2: Database
Module3: UI
Module4: Backend
Module5: Tools'''
>>> print(rollno)
101
>>> print(name)
nk
>>> print(course)
FSP
>>> print(description)
Full Stack Python consists of 5 Modules
Module1: Python
Module2: Database
Module3: UI
Module4: Backend
Module5: Tools
>>> str1=""" Python is
... high level, multiparadigm
... programming language"""
>>> print(str1)
Python is
high level, multiparadigm
programming language
Comments in Python
test1.py
# This is my first program in python
Output:
Hello
test2.py
a=''' This is my first python program '''
print("Hello")
print(a)
Output:
Hello
This is my first python program
What is indent?
Space given at the beginning of the statement is called indent.
Indent is used to create block.
print()
print() is a predefined function in python.
print() is a standard output function, this function is used to print data or
information on console/monitor.
Example:
print()
print()
print()
print()
Output:
4 blank lines
Example:
print(10)
print()
print(20)
print()
print(1.5)
print()
print("Hello")
Output:
10
20
1.5
Hello
Example:
print(10,20,30,40,50)
print(1,"nk","python",4000.0)
print(10,20,30,40,50,sep="$")
print(10,20,30,40,50,sep=",")
print(10,20,30,40,50)
print(1,2,3,4,5,sep="nit")
Output:
10 20 30 40 50
1 nk python 4000.0
10$20$30$40$50
10,20,30,40,50
10 20 30 40 50
1nit2nit3nit4nit5
Example:
rollno=101
name="Nk"
course="Python"
fee=5000.0
print("rollno",rollno)
print("name",name)
print("course",course)
print("fee",fee)
Output:
rollno 101
name Nk
course Python
fee 5000.0
Example:
a=10
b=20
c=30
print(a,b,c)
print("a","b","c")
Output:
10 20 30
abc
Example:
print(10,20,30,end=';')
print(40,50,60)
print(70,80)
Output:
10 20 30;40 50 60
70 80
Escape Sequences
Escape sequences are special string
These are called backslash character literals
\n New line
\t Horizontal tab space
\v Vertical tab space
\\ \
\” “
\’ ‘
\b backspace
Example:
print('\\')
print("\"")
print('\'')
print("\n")
print("\t")
Output:
\
"
'
Example:
a=10
b=20
c=30
print(a,b,c,sep="\n")
x=100
y=200
z=300
print(x,y,z,sep="\t")
Output:
10
20
30
100 200 300
Example:
a=10
b=20
print("sum of ",a,b,"is",a+b)
Output:
sum of 10 20 is 30
format string
A string prefix with f or F is called format string.
This string contains replacement fields, which are replaced with values
(OR) format string allows to insert values within string.
Format string is used to format output.
Inside format string replacement fields are represented using curly braces
{}.
Example:
a=10
b=20
print(f'sum of {a} and {b} is {a+b}')
Output:
sum of 10 and 20 is 30
Example:
a=10
print(f'{a:d},{a:o},{a:x},{a:b}')
b=1.5
print(f'{b}')
print(f'{b:f}')
print(f'{b:.2f}')
print(f'{b:.30f}')
c=1.5e-2
print(f'{c:e}')
print(f'{c:.2e}')
Output:
10,12,a,1010
1.5
1.500000
1.50
1.500000000000000000000000000000
1.500000e-02
1.50e-02
format function of string data type
before 3.8 formatting of output is done using format function of string
data type.
Example:
a=10
b=20
print("sum of {} and {} is {}".format(a,b,a+b))
print("{:d},{:o},{:x},{:b}".format(a,a,a,a))
base=1.5
height=2.5
print("Area of triangle with base={} and height={} is
{}".format(base,height,0.5*base*height))
print("Area of triangle with base={:.2f} and height={:.2f} is
{:.2f}".format(base,height,0.5*base*height))
Output:
sum of 10 and 20 is 30
10,12,a,1010
Area of triangle with base=1.5 and height=2.5 is 1.875
Area of triangle with base=1.50 and height=2.50 is 1.88
Input() function
input() is standard input function, this function is used to input/read data
from keyboard.
Input() is function is used to input/read string value.
Input() function allows to input/read one value.
Syntax:
variable=input([prompt])
Example:
a=input("Enter First Value ")
b=input("Enter Second Value ")
c=input("Enter value of c ")
print(a,b,c)
print(type(a),type(b),type(c))
Output:
Enter First Value 100
Enter Second Value 200
Enter value of c 300
100 200 300
<class 'str'> <class 'str'> <class 'str'>
Example:
# Write a program to print sum of integers
# input two integers from keyboard
Output:
Enter First Value 10
Enter Second Value 20
sum of 10 and 20 is 1020
1. Int()
2. Float()
3. Complex()
4. Bool()
5. Str()
All these are in-built functions and available in default module imported
by any python program called __builtins__
int() function
This function is used to create integer object (OR) this function performs
the following conversions.
1. Int to int
2. Float to int
3. String to int
4. Bool to int
Syntax1: int(value)
Syntax2: int(value,base=10)
Output:
Enter First Value 100
Enter Second Value 200
sum of 100 and 200 is 300
Example:
>>> int(10)
10
>>> int(1.5)
1
>>> int(True)
1
>>> int(False)
0
>>> int(1+2j)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
int(1+2j)
TypeError: int() argument must be a string, a bytes-like object or a real
number, not 'complex'
>>> int("65")
65
>>> int("1.25")
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
int("1.25")
ValueError: invalid literal for int() with base 10: '1.25'
>>> int("a")
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
int("a")
ValueError: invalid literal for int() with base 10: 'a'
>>> int("a",base=16)
10
>>> int("ff",base=16)
255
>>> int("ffff",base=16)
65535
>>> int("1010",base=2)
10
>>> int("1010")
1010
float() function
This function is used to create float object or to perform the following
conversions
1. float to float
2. int to float
3. string to float
4. bool to float
Syntax: float(value)
Example
>>> float(1.5)
1.5
>>> float(1)
1.0
>>> float(True)
1.0
>>> float(False)
0.0
>>> float("1.5")
1.5
>>> float("15e-1")
1.5
>>> float("15")
15.0
>>> float("abc")
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
float("abc")
ValueError: could not convert string to float: 'abc'
Example:
# Write a program to swap/interchange two float values input from stdin
Output:
Enter value of a 1.5
Enter value of b 2.5
before swaping a=1.5 and b=2.5
after swaping a=2.5 and b=1.5
after swaping a=1.5 and b=2.5
after swaping a=2.5 and b=1.5
complex()
This function is used to create complex number (OR) perform the
following conversions
1. complex to complex
2. int to complex
3. float to complex
4. string to complex
5. bool to complex
complex()
This function is used to create complex number (OR) perform the
following conversions
1. complex to complex
2. int to complex
3. float to complex
4. string to complex
5. bool to complex
Example:
>>> comp1=complex(1+2j)
>>> print(comp1)
(1+2j)
>>> print(type(comp1))
<class 'complex'>
>>> comp2=complex("1+2j")
>>> print(comp2)
(1+2j)
>>> print(type(comp2))
<class 'complex'>
>>> comp3=complex("2j")
print(comp3)
2j
>>> print(type(comp3))
<class 'complex'>
>>> comp4=complex("4")
>>> print(comp4)
(4+0j)
>>> comp5=complex(1)
>>> print(comp5)
(1+0j)
>>> comp6=complex(2j)
>>> print(comp6)
2j
>>> print(comp6.real,comp6.imag)
0.0 2.0
>>> comp7=complex(True)
>>> print(comp7,type(comp7))
(1+0j) <class 'complex'>
>>> comp8=complex(False)
>>> print(comp8,type(comp8))
0j <class 'complex'>
>>> print(comp8.real,comp8.imag)
0.0 0.0
Example:
# Write a program for adding two complex numbers
Output:
input complex number1 1+2j
input complex number2 1+3j
sum of (1+2j) and (1+3j) is (2+5j)
bool() function
This function returns Boolean value (OR) this function performs the
following conversions.
1. Bool to bool
2. Int to bool
3. Float to bool
4. Complex to bool
5. String to bool
Example:
>>> b1=bool(True)
>>> print(b1)
True
>>> b2=bool(False)
>>> print(b2)
False
>>> b3=bool(0)
print(b3)
>>> False
>>> b4=bool(1)
>>> print(b4)
True
>>> b5=bool(100)
>>> print(b5)
True
>>> b6=bool(-5)
>>> print(b6)
True
>>> b7=bool(0.0)
>>> print(b7)
False
>>> b8=bool(0.5)
>>> print(b8)
True
>>> b9=bool(0+0j)
>>> print(b9)
False
>>> b10=bool(1+0j)
>>> print(b10)
True
>>> b11=bool("A")
>>> print(b11)
True
>>> b12=bool("NARESH")
>>> print(b12)
True
>>> b13=bool("False")
>>> print(b13)
True
>>> b14=bool("True")
>>> print(b14)
True
ord(),char()
Example:
# Write a program to convert given character from uppercase to
lowercase
char='B'
print(char)
value=ord(char) # 66
value=value+32
char1=chr(value)
print(char1)
value=ord(char1)
value=value-32
char2=chr(value)
print(char2)
Output:
B
b
B
B
str() function
This function returns string object (OR) this function is used to convert
other types into string type.
Syntax: str(value)
>>> s1=str()
print(s1)
>>> s2=str(25)
>>> print(s2)
25
>>> s3=str(1.5)
>>> print(s3)
1.5
>>> s2+s3
'251.5'
>>> print(type(s2),type(s3))
<class 'str'> <class 'str'>
>>> s4=str(1+2j)
>>> print(s4)
(1+2j)
>>> print(type(s4))
<class 'str'>
>>> s5=str(True)
>>> print(s5)
True
>>> s6=str(False)
>>> print(s6)
False
>>> print(type(s5),type(s6))
<class 'str'> <class 'str'>
Operators
What is operator?
Operator is a special symbol, which is used to perform operations.
Based on the numbers of operand used to perform operation, the
operators are classified into 3 categories
1. Unary Operator
2. Binary Operator
3. Ternary Operator
Types of operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Membership Operator
6. Identity Operator
7. Conditional Operator
8. Bitwise Operators
9. Walrus Operator (Python 3.8)
Arithmetic Operators
Operator Description
+ Adding or Concatenation
- Subtraction
* Multiplication or Repeat
/ Float Division
// Floor Division
% Modulo
** Exponent or Power
Example:
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)
10 20 30
>>> x=1.5
>>> y=1.2
>>> z=x+y
>>> print(x,y,z)
1.5 1.2 2.7
>>> b1=True
>>> b2=False
>>> b3=b1+b2
>>> print(b1,b2,b3)
True False 1
>>> b4=True+15
>>> print(b4)
16
>>> c1=1+2j
>>> c2=1+1j
>>> c3=c1+c2
>>> print(c1,c2,c3)
(1+2j) (1+1j) (2+3j)
>>> s1="Python"
>>> s2="3.12"
>>> s3=s1+s2
>>> print(s1,s2,s3)
Python 3.12 Python3.12
>>> s4="10"
>>> s5="15"
>>> s6=s4+s5
>>> print(s4,s5,s6)
10 15 1015
>>> s7="python"
>>> s8=3.12
>>> print(s7+s8)
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
print(s7+s8)
TypeError: can only concatenate str (not "float") to str
eval() function
it is a predefined function of python. This function evaluate string
representation of expression and return value.
eval(expression)
>>> a=eval("1.5")
>>> print(a,type(a))
1.5 <class 'float'>
>>> b=eval("25")
>>> print(b,type(b))
25 <class 'int'>
>>> c=eval("1+2j")
>>> print(c,type(c))
(1+2j) <class 'complex'>
>>> d=eval("10+20+30")
>>> print(d)
60
Example:
# write a program to add two numbers
Output
Enter first number 10
Enter second number 20
sum of 10 and 20 is 30
>>> a=10
>>> b=1.5
>>> c=a-b
>>> print(a,b,c)
10 1.5 8.5
>>> c1=1+2j
>>> c2=1j
>>> c3=c1-c2
>>> print(c1,c2,c3)
(1+2j) 1j (1+1j)
>>> c3=c1-2
>>> print(c3)
(-1+2j)
complex()
This function is used to create complex number (OR) perform the
following conversions
1. complex to complex
2. int to complex
3. float to complex
4. string to complex
5. bool to complex
Example:
>>> comp1=complex(1+2j)
>>> print(comp1)
(1+2j)
>>> print(type(comp1))
<class 'complex'>
>>> comp2=complex("1+2j")
>>> print(comp2)
(1+2j)
>>> print(type(comp2))
<class 'complex'>
>>> comp3=complex("2j")
print(comp3)
2j
>>> print(type(comp3))
<class 'complex'>
>>> comp4=complex("4")
>>> print(comp4)
(4+0j)
>>> comp5=complex(1)
>>> print(comp5)
(1+0j)
>>> comp6=complex(2j)
>>> print(comp6)
2j
>>> print(comp6.real,comp6.imag)
0.0 2.0
>>> comp7=complex(True)
>>> print(comp7,type(comp7))
(1+0j) <class 'complex'>
>>> comp8=complex(False)
>>> print(comp8,type(comp8))
0j <class 'complex'>
>>> print(comp8.real,comp8.imag)
0.0 0.0
Example:
# Write a program for adding two complex numbers
Output:
input complex number1 1+2j
input complex number2 1+3j
sum of (1+2j) and (1+3j) is (2+5j)
bool() function
This function returns Boolean value (OR) this function performs the
following conversions.
1. Bool to bool
2. Int to bool
3. Float to bool
4. Complex to bool
5. String to bool
Example:
>>> b1=bool(True)
>>> print(b1)
True
>>> b2=bool(False)
>>> print(b2)
False
>>> b3=bool(0)
print(b3)
>>> False
>>> b4=bool(1)
>>> print(b4)
True
>>> b5=bool(100)
>>> print(b5)
True
>>> b6=bool(-5)
>>> print(b6)
True
>>> b7=bool(0.0)
>>> print(b7)
False
>>> b8=bool(0.5)
>>> print(b8)
True
>>> b9=bool(0+0j)
>>> print(b9)
False
>>> b10=bool(1+0j)
>>> print(b10)
True
>>> b11=bool("A")
>>> print(b11)
True
>>> b12=bool("NK")
>>> print(b12)
True
>>> b13=bool("False")
>>> print(b13)
True
>>> b14=bool("True")
>>> print(b14)
True
ord(),char()
Example:
# Write a program to convert given character from uppercase to
lowercase
char='B'
print(char)
value=ord(char) # 66
value=value+32
char1=chr(value)
print(char1)
value=ord(char1)
value=value-32
char2=chr(value)
print(char2)
Output:
B
b
B
B
str() function
This function returns string object (OR) this function is used to convert
other types into string type.
Syntax: str(value)
>>> s1=str()
print(s1)
>>> s2=str(25)
>>> print(s2)
25
>>> s3=str(1.5)
>>> print(s3)
1.5
>>> s2+s3
'251.5'
>>> print(type(s2),type(s3))
<class 'str'> <class 'str'>
>>> s4=str(1+2j)
>>> print(s4)
(1+2j)
>>> print(type(s4))
<class 'str'>
>>> s5=str(True)
>>> print(s5)
True
>>> s6=str(False)
>>> print(s6)
False
>>> print(type(s5),type(s6))
<class 'str'> <class 'str'>
Operators
What is operator?
Operator is a special symbol, which is used to perform operations.
Based on the numbers of operand used to perform operation, the
operators are classified into 3 categories
1. Unary Operator
2. Binary Operator
3. Ternary Operator
Types of operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Membership Operator
6. Identity Operator
7. Conditional Operator
8. Bitwise Operators
9. Walrus Operator (Python 3.8)
Arithmetic Operators
Operator Description
+ Adding or Concatenation
- Subtraction
* Multiplication or Repeat
/ Float Division
// Floor Division
% Modulo
** Exponent or Power
Example:
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)
10 20 30
>>> x=1.5
>>> y=1.2
>>> z=x+y
>>> print(x,y,z)
1.5 1.2 2.7
>>> b1=True
>>> b2=False
>>> b3=b1+b2
>>> print(b1,b2,b3)
True False 1
>>> b4=True+15
>>> print(b4)
16
>>> c1=1+2j
>>> c2=1+1j
>>> c3=c1+c2
>>> print(c1,c2,c3)
(1+2j) (1+1j) (2+3j)
>>> s1="Python"
>>> s2="3.12"
>>> s3=s1+s2
>>> print(s1,s2,s3)
Python 3.12 Python3.12
>>> s4="10"
>>> s5="15"
>>> s6=s4+s5
>>> print(s4,s5,s6)
10 15 1015
>>> s7="python"
>>> s8=3.12
>>> print(s7+s8)
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
print(s7+s8)
TypeError: can only concatenate str (not "float") to str
eval() function
it is a predefined function of python. This function evaluate string
representation of expression and return value.
eval(expression)
>>> a=eval("1.5")
>>> print(a,type(a))
1.5 <class 'float'>
>>> b=eval("25")
>>> print(b,type(b))
25 <class 'int'>
>>> c=eval("1+2j")
>>> print(c,type(c))
(1+2j) <class 'complex'>
>>> d=eval("10+20+30")
>>> print(d)
60
Example:
# write a program to add two numbers
>>> a=10
>>> b=1.5
>>> c=a-b
>>> print(a,b,c)
10 1.5 8.5
>>> c1=1+2j
>>> c2=1j
>>> c3=c1-c2
>>> print(c1,c2,c3)
(1+2j) 1j (1+1j)
>>> c3=c1-2
>>> print(c3)
(-1+2j)
“*” This operator is used to perform two operations
1. Multiplication
2. Repeating Sequence number of times
Example:
>>> n1=5
>>> n2=2
>>> n3=n1*n2
>>> print(n1,n2,n3)
5 2 10
>>> f1=1.5
>>> f2=2.5
>>> f3=f1*f2
>>> print(f1,f2,f3)
1.5 2.5 3.75
>>> r1=5*1.5
>>> print(r1)
7.5
>>> r2=5*True
>>> print(r2)
5
Example:
>>> list1=[0]
>>> list1=list1*10
>>> print(list1)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> s1="abc"
>>> s2=5*s1
>>> print(s2)
abcabcabcabcabc
>>> print("-"*30)
------------------------------
>>> print(30*"*")
******************************
>>> list2=[5]*20
>>> print(list2)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
Example:
# Write a program to find area of rectangle
# area=l*b
Output:
Enter value of l1.2
Enter value of b1.5
area of rectangle with l=1.20 and b=1.50 is 1.80
This operator divide two numbers and return value as float type.
Example:
q1=5/2
print(q1)
2.5
>>> q2=4/2
>>> print(q2)
2.0
>>> q3=4/2.0
>>> print(q3)
2.0
>>> q4=4/0
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
q4=4/0
ZeroDivisionError: division by zero
>>> q5=0/5
>>> print(q5)
0.0
Example:
# Write a program to find simple interest
# si=ptr/100
p=float(input("Amount "))
t=int(input("Time "))
r=float(input("Rate "))
si=p*t*r/100
print(f'''Amount {p}
Time {t}
Rate {r}
Simple Interest {si:.2f}''')
Output:
Amount 5000
Time 12
Rate 1.5
Amount 5000.0
Time 12
Rate 1.5
Simple Interest 900.00
Example:
# Write a program to input rollno,name 3 subject marks
# calculate total and avg marks
rollno=int(input("Rollno "))
name=input("Name ")
sub1=int(input("Subject1 Marks "))
sub2=int(input("Subject2 Marks "))
sub3=int(input("Subject3 Marks "))
total=sub1+sub2+sub3
avg=total/3
print(f'''
Rollno {rollno}\tName {name}
Subject1 {sub1}\tSubject2 {sub2}\tSubject3 {sub3}
Total {total}\tAvg {avg:.2f}''')
Output:
Rollno 1
Name nk
Subject1 Marks 50
Subject2 Marks 70
Subject3 Marks 90
Rollno 1 Name nk
Subject1 50 Subject270 Subject390
Total 210 Avg 70.00
https://www.hackerrank.com/challenges/python-arithmetic-
operators/problem?isFullScreen=true
a=int(input())
b=int(input())
print(a+b)
print(a-b)
print(a*b)
>>> r1=5//2
>>> print(r1)
2
>>> r2=5/2
>>> print(r2)
2.5
>>> r3=5//2.0
>>> print(r3)
2.0
>>> r4=5/2.0
>>> print(r4)
2.5
Example:
# Write a program to delete last digit of number
num=456
print(num)
num=num//10
print(num)
Output:
456
45
% modulo operator
This operator divides two numbers and return remainder
>>> rem1=5%3
>>> print(rem1)
2
>>> rem2=4%2
>>> print(rem2)
0
Example:
# Write a program to read last digit of number
num=456
lastdigit=num%10
print(num)
print(lastdigit)
Output:
456
6
>>> res1=5**2
>>> print(res1)
25
>>> res2=5**0
>>> print(res2)
1
>>> res3=10**-1
>>> print(res3)
0.1
Precedence of operators
Operator Description
(expressions...),
Binding or parenthesized expression, list
[expressions...], {key: value...
display, dictionary display, set display
}, {expressions...}
x[index], x[index:index], x(ar Subscription, slicing, call, attribute
guments...), x.attribute reference
await x Await expression
** Exponentiation 5
+x, -x, ~x Positive, negative, bitwise NOT
Multiplication, matrix multiplication,
*, @, /, //, %
division, floor division, remainder
+, - Addition and subtraction
<<, >> Shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, Comparisons, including membership tests
>=, !=, == and identity tests
not x Boolean NOT
Operator Description
and Boolean AND
or Boolean OR
if – else Conditional expression
lambda Lambda expression
:= Assignment expression
Relational Operators
Relational operators are used for comparing values. An expression
created using relational operators is called Boolean expression. Boolean
expression always returns Boolean value (True/False)
Operators Description
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
== Equal
!= Not equal
Example:
>>> 10>5
True
>>> 20>30
False
>>> 20<30
True
>>>10<5
False
>>>10>=10
True
>>>10>=5
True
>>>10<=10
True
>>> 5<=10
True
>>> 20<=10
False
>>> 10==10
True
>>> 10==20
False
>>> 10!=10
False
>>> 10!=20
True
>>> "A">"B"
False
>>> "B">"A"
True
>>> "a">"A"
True
>>> a=5
>>> 1<=a<=10
True
>>> a=20
>>> 1<=a<=10
False
>>> 5>=1<=10
True
Conditional Operator
Conditional operator is a ternary operator, this operator required 3
operands. Condition operator is used for creating conditional expression.
Conditional operators allow evaluating expression based on
condition/test.
Syntax:
<variable-name>=opr1 if opr2 else opr3
Example:
# Write a program to find a person is elg to vote or not
name=input("Enter Name ")
age=int(input("Enter Age "))
result=f'{name} is elg to vote ' if age>=18 else f'{name} is not elg vote'
print(result)
Output:
Enter Name suresh
Enter Age 30
suresh is elg to vote
Example:
# Write a program to find input number is even or odd
Output:
Enter any number 4
4 is even
Example:
# Write a program to find max of two numbers
Output:
Enter First Number 10
Enter Second Number 5
10 is max
Logical Operators
Logical operators are used to combine two or more conditions or boolean
expressions. In python logical operators are represented using 3
keywords.
and operator
truth table of and operator
Opr1 Opr2 Opr1 and Opr2
True False False
False True False
False False False
True True True
Example:
>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
False
>>> 10>5 and 10>20
False
>>> 10>20 and 10>5
False
Example:
# Write a program to read name and 2 subject marks
# calculate total,avg and result
Output:
Enter Name nk
Enter Subject1 Marks 70
Enter Subject2 Marks 80
Name nk
Subject1 70
Subject2 80
Total 150
Avg 75.00
Result pass
Example:
>>> 100 and 200
200
>>> 0 and 100
0
>>>100 and 200 and 300
300
>>>100 and 0 and 300
0
>>> "java" and "python"
'python'
>>> "A" and "B"
'B'
>>> bool(100)
True
>>> bool(0)
False
Example:
# Login Application
Output:
UserName :nk
Password :nit123
invalid username or password
UserName :nit
Password :nk
invalid username or password
>>>
UserName :nit
Password :nit123
Welcome
or operator
truth table
Opr1 Opr2 Opr1 or Opr2
True True True
True False True
False True True
False False False
True or False
True
>>> False or True
True
>>> False or False
False
>>> 100 or 200
100
>>> 100 or 200 or 300
100
Example:
>>> 100 or 200
100
>>> 100 or 200 or 300
100
>>> 100 or 200 and 300
100
>>> 200 and 300 or 100
300
>>> 0 and 100 or 200
200
t.me/fspy5
Using multiple conditional operator
Multiple conditional operators are used to check more than one
condition.
Example:
# Write a program to find input character is vowel or not
Output:
Enter Single Character i
Vowel
Example:
# Write a program to find input number is +ve,-ve or zero
Output:
Enter any number 5
+ve
Example:
# Write a program to find input character is alphabet,digit or special
character
Output:
Enter any character a
alphabet
not operator
not is a unary operator, this operator required 1 operand
truth table of not operator
Opr1 Not Opr1
True False
False True
Example:
>>> not True
False
>>> not False
True
>>> not 100
False
>>> not 0
True
Membership operator
Membership operator is binary operator
This operator required two operands
Membership operator is represented using “in” keyword
1. In
2. Not in
Example
>>> "a" in "java"
True
>>> "python" in "best programming language to learn is python"
True
>>> 10 in [10,20,30,40]
True
>>> 100 in [10,20,30,40]
False
>>> "nk@nkit.com" in ["suresh@gmail.com","kishore@nkit.com"]
False
>>> 10 not in [10,20,30,40,50]
False
>>> 100 not in [10,20,30,40,50]
True
Example:
# Write a program to find input character is vowel
Output
Enter any character a
vowel
Identity Operator
Identity operator is a binary operator
Identity operator is represented using “is” keyword.
Identity operator is used to compare references or identity of object.
1. is
2. is not
is operator returns True, if two variables pointing to same object inside
memory, else return False
is not operator return True, if two variables are not pointing to same
object inside memory else return False
>>> a=10
>>> b=10
>>> a==b
True
>>> id(a)
140715736550104
>>> id(b)
140715736550104
>>> a is b
True
>>> list1=[10,20,30]
>>> list2=[10,20,30]
>>> list1==list2
True
>>> list1 is list2
False
>>> list3=list1
>>> list1 is list3
True
>>> a=(b=1+5)*(c=5-2)
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
>>> a=(b:=1+5)*(c:=5-2)
>>> print(a)
18
>>> print(b)
6
>>> print(c)
3
>>> x:=10
SyntaxError: invalid syntax
>>> x=10
>>> x
10
Bitwise Operators
Bitwise operators are used to perform operation on binary data.
1. Shift operators
a. Left shift operator
b. Right shift operator
2. Bitwise & (and) operator
3. Bitwise | (or) operator
4. Bitwise ^ (XOR) operator
5. Bitwise ~ (NOT) operator
Shift Operators
Shift operators are used to shift or move bits towards left side or right
side.
These operators are used to increment or decrement value by adding bits
or removing bits.
Applications
Memory Management
Encryption and Decryption
>> right shift operator is used to shift number of bits towards right side.
The shifted bits are deleted.
Syntax: value>>n
>>> a=12
>>> b=a>>2
>>> print(a,b)
12 3
>>> print(bin(a),bin(b))
0b1100 0b11
>>> x=25
>>> y=x>>3
>>> print(bin(x),bin(y))
0b11001 0b11
>>> print(x,y)
25 3
>>> b=a>>5
>>> a=20
>>> b=a>>2
>>> print(a)
20
>>> print(b)
5
Left shift operator is used to shift number of bits towards left side. By
shifting number of bits toward left side the value get incremented.
Syntax: value<<n
Formula: value*2 pow n
>>> a=10
>>> print(bin(a))
0b1010
>>> b=a<<1
>>> print(bin(b))
0b10100
>>> print(b)
20
Logical Gates
A logic gate is a device that acts as a building block for digital circuits.
They perform basic logical functions that are fundamental to digital
circuits. Most electronic devices we use today will have some form of
logic gates in them. For example, logic gates can be used in technologies
such as smartphones, tablets or within memory devices.
.
Note: bitwise operators are applied only one integer data types.
Example:
>>> a=5
>>> b=4
>>> c=a&b
>>> print(a,b,c)
544
>>> print(bin(a),bin(b),bin(c))
0b101 0b100 0b100
>>> x=0b1010
>>> y=0b1110
>>> z=x&y
>>> print(bin(x),bin(y),bin(z))
0b1010 0b1110 0b1010
>>> print(x,y,z)
10 14 10
>>> x=0b101
>>> y=0b110
>>> z=x|y
>>> print(bin(x),bin(y),bin(z))
0b101 0b110 0b111
>>> a=12
>>> b=20
>>> c=a|b
>>> print(bin(a),bin(b),bin(c))
0b1100 0b10100 0b11100
>>> print(a,b,c)
12 20 28
>>> a and b
20
>>> a=0b101
>>> b=0b100
>>> c=a^b
>>> print(bin(a),bin(b),bin(c))
0b101 0b100 0b1
>>> a=5
>>> b=~a
>>> print(a)
5
>>> print(b)
-6
>>> print(bin(a),bin(b))
0b101 -0b110
>>> a=5
>>> a=a+2
>>> print(a)
7
>>> a+=2
>>> print(a)
9
>>> b=10
>>> b-=1
>>> print(b)
9
>>> c=16
>>> c/=4
>>> print(c)
4.0
>>> a=12
>>> a>>=2
>>> print(a)
3
Command line arguments
The values send to python program from command prompt or command
line is called command line arguments.
The values send from command prompt are stored in one variable called
argv. It is a predefined variable/object exists in sys module.
How to execute program with command line arguments in IDLE?
Control Statements
If statement
if is keyword which represent conditional statement.
Types of if syntax
1. simple if
2. if..else
3. if..elif..else (if..else ladder)
4. nested if
simple if
Syntax:
If <condition>:
Statement-1
Statement-2
Statement-3
Example:
if 10>5:
print("Python")
print("Hello")
if 5>10:
print("Java")
print("Bye")
if 2>10:
print(".Net")
print("Good")
Output:
Python
Hello
Bye
Example:
if 10>5:
pass
print("a")
print("b")
Output:
a
b
pass keyword
The pass statement is used as a placeholder for future code. When the
pass statement is executed, nothing happens, but you avoid getting an
error when empty code is not allowed. Empty code is not allowed in
loops, function definitions, class definitions, or in if statements.
Example:
if 10>5:
pass
print("Hello")
Output:
Hello
If..else
Syntax:
If <condition>:
Statement-1
Statement-2
else:
Statement-3
Statement-4
Statement-5
Example:
Output:
Enter any number 14
14 is divisible with 7
Example:
Output:
Enter any Number 20
Hello
If condition1:
Statement-1
elif condition2:
Statement-2
elif condition3:
Statement-3
…
else:
Statement-n
Example:
Output:
Enter any character a
alphabet
https://www.hackerrank.com/challenges/py-if-
else/problem?isFullScreen=true
n=int(input())
if n%2!=0:
print("Weird")
elif n>=2 and n<=5:
print("Not Weird")
elif n>=6 and n<=20:
print("Weird")
elif n>20:
print("Not Weird")
units=int(input("Enter units"))
if units<=100:
amt=0
elif units>100 and units<=200:
amt=(units-100)*5
else:
amt=0+500+(units-200)*10
print(f'Amount {amt}')
p=int(input("Enter Percentage"))
if p>90:
print("A")
elif p>80 and p<=90:
print("B")
elif p>=60 and p<=80:
print("C")
else:
print("D")
cost=int(input("Enter Bike Price :"))
if cost>100000:
tax=cost*15/100
elif cost>50000 and cost<=100000:
tax=cost*10/100
else:
tax=cost*5/100
print(f'Salary {salary}')
print(f'Bonus {bonus}')
Output:
Enter Salary 50000
Enter Service 12
Salary 50000
Bonus 5000.0
Example:
# Write a program to convert input alphabet into uppercase to lower
case,
# lowercase to uppercase
ch=input("Enter any character ")
if ch>='a' and ch<='z':
ch=chr(ord(ch)-32)
print(ch)
elif ch>='A' and ch<='Z':
ch=chr(ord(ch)+32)
print(ch)
else:
print("input character must be alphabet")
Output:
Enter any character $
input character must be alphabet
Nested if
If condition1:
If condition2:
Statement-1
else:
Statement-2
elif condition3:
if condition4:
Statement-3
Else:
Statement-4
else:
Statement-5
Example:
# Login Application
user=input("UserName ")
if user=="nit":
pwd=input("Password ")
if pwd=="nit123":
print("Welcome")
else:
print("invalid password")
else:
print("invalid username")
Output:
UserName abc
invalid username
UserName nit
Password nit123
Welcome
Example:
# Write program to login with OTP
import random
user=input("UserName ")
otp=random.randint(1000,9999)
print(f'{user} please Login with OTP {otp}')
otp1=int(input("OTP :"))
if otp1==otp:
print(f'{user} welcome')
else:
print("invalid OTP")
Output:
UserName nk
nk please Login with OTP 2602
OTP :2602
nk welcome
UserName suresh
suresh please Login with OTP 9425
OTP :9424
invalid OTP
match statement
match statement
match is selection statement.
match statement execute block of statements based selection of value.
match is softkeyword in python.
match statement is introduced in python 3.10 version
Syntax:
match(expression/value):
case <pattern>:
statement-1
case <pattern>:
statement-2
case <pattern>:
statement-3
case _:
statement-x
PVM read value and compare with all the cases, if equals to any case,
PVM execute that block and terminates.
If value is not equal to any case, PVM executes default case which is
defined _
Example:
Output:
Enter any Digit (0-9): 3
Three
Example:
print("****Menu****")
print("1.Area of Circle")
print("2.Area of Triangle")
print("3.Area of Rectangle")
print("4.Exit")
opt=int(input("Enter Your Option [1-4] "))
match(opt):
case 1:
r=float(input("Enter R Value "))
area=3.147*r*r
print(f'Area of Circle is {area:.2f}')
case 2:
base=float(input("Enter Base Value "))
height=float(input("Enter Height Value "))
area=0.5*base*height
print(f'Area of Triangle {area:.2f}')
case 3:
l=float(input("Enter L Value "))
b=float(input("Enter B Value "))
area=l*b
print(f'Area of Rectangle {area:.2f}')
case 4:
print("Thank You...")
case _:
print("Invalid Option Try again...")
Output:
****Menu****
1.Area of Circle
2.Area of Triangle
3.Area of Rectangle
4.Exit
Enter Your Option [1-4] 2
Enter Base Value 1.2
Enter Height Value 1.5
Area of Triangle 0.90
****Menu****
1.Area of Circle
2.Area of Triangle
3.Area of Rectangle
4.Exit
Enter Your Option [1-4] 1
Enter R Value 1.5
Area of Circle is 7.08
Example:
# Write a program to find input character is vowel or not
Output:
Enter any character e
vowel
while loop
while <condition>:
statement-1
statement-2
Example:
# Write a program to input 5 numbers and print sum
i=1
s=0
while i<=5:
value=int(input("Enter Value "))
s=s+value
i=i+1
print(f'Sum is {s}')
Output:
Enter Value 10
Enter Value 40
Enter Value 20
Enter Value 40
Enter Value 50
Sum is 160
Example:
i=0
while i<=5:
print("Hello")
i=i+1
j=1
while j<=5:
print("Bye")
j=j+2
k=1
while k>=5:
print("java")
k=k+1
p=5
while p>=1:
print("Python")
p=p-1
Output:
Hello
Hello
Hello
Hello
Hello
Hello
Bye
Bye
Bye
Python
Python
Python
Python
Python
Full Stack Python (Part-26)
Example:
# Write a program to find length of number or count digits of input
number
Output:
Enter any number 0
Count of digits 1
Example:
Output:
Enter any number 123
Sum of digits 6
Example:
# Write a program to count how many even and odd digits exists within
input number
while num>0:
r=num%10
if r%2==0:
ecount=ecount+1
else:
ocount=ocount+1
num=num//10
Output:
Enter any number 4893
Even count digits 2
Odd count digits 2
Example:
# Write a program to find input number is armstrong or not (3digit
number)
if s==num1:
print(f'{num1} armstrong')
else:
print(f'{num1} is not armstrong')
Output
Enter any number 153
153 armstrong
Enter any number 125
125 is not armstrong
Example:
# Write a program to find an input number is perfect number or not
s=0
i=1
while i<num:
r=num%i
if r==0:
s=s+i
i=i+1
if s==num:
print(f'{num} is perfect number ')
else:
print(f'{num} is not perfect number')
Output:
enter any number 6
6 is perfect number
while num>0:
r=num%10
rev=(rev*10)+r
num=num//10
print(num1)
print(rev)
if rev==num1:
print(f'{num1} is palindrome')
else:
print(f'{num1} is not palindrome')
Output:
Enter any number 123
123
321
123 is not palindrome
HOME WORK
489
for loop
“for” keyword represents for loop.
For loop is used to repeat one or more than one statement number of
times.
For loop is called iterator, which iterate values from iterables (collections
(OR) for loop is used to read values from collections.
Syntax:
for variable-name in iterable:
statement-1
statement-2
for loop each time read one value from iterable and assign to a variable;
After assigning to variable, it execute block of statements.
Statement-1, statement-2 is executed until read all the values from
iterable.
Example:
str1="java"
for ch in str1:
print(ch)
Output:
j
a
v
a
Example:
# Write a program to find length of string
str1=input("Enter any string ")
c=0
for ch in str1:
c=c+1
Output:
Enter any string python
Length of string 6
Example:
# Write a program to count
# alphabets, digits and sepcial character exists within input string
ac=0
dc=0
sc=0
for ch in str1:
if ch>='a' and ch<='z' or ch>='A' and ch<='Z':
ac=ac+1
elif ch>='0' and ch<='9':
dc=dc+1
else:
sc=sc+1
Syntax-1: range(stop)
This syntax is used to generate sequence of +ve integer values.
In this syntax default start=0,step=+1
Example:
r1=range(10) # creating range object start=0,stop=10,step=1 0 1 2 3 4 5 6
789
for a in r1:
print(a,end=' ')
print("\n-----------------------")
for b in range(5): # start=0,stop=5,step=1 --> 0 1 2 3 4
print(b,end=' ')
print("\n-------------------------")
for c in range(-5): # start=0,stop=-5,step=1
print(c,end=' ')
Output:
0123456789
-----------------------
01234
-------------------------
Syntax2: range(start,stop,[step])
This syntax is used to generate sequence of integers in increment or
decrement order.
If step value is not given it default to +1
Example:
for a in range(1,11): # start=1,stop=11,step=1 --> 1 2 3 4 5 6 7 8 9 10
print(a,end=' ')
print()
for b in range(1,11,2): # start=1,stop=11,step=2 --> 1 3 5 7 9
print(b,end=' ')
print()
for c in range(2,20,2): # start=2,stop=20,step=2 --> 2 4 6 8 10 12 14 16 18
print(c,end=' ')
print()
for d in range(10,0,-1): # start=10,stop=0,step=-1 --> 10 9 8 7 6 5 4 3 2 1
print(d,end=' ')
print()
for e in range(-1,-11,-1): # start=-1,stop=-11,step=-1
print(e,end=' ')
print()
for f in range(-10,0,1): # start=-10,stop=0,step=1
print(f,end=' ')
print()
for g in range(-5,6): # start=-5,stop=6,step=1
print(g,end=' ')
print()
for h in range(5,-6,-1): # start=5,stop=-6,step=-1
print(h,end=' ')
print()
Output:
1 2 3 4 5 6 7 8 9 10
13579
2 4 6 8 10 12 14 16 18
10 9 8 7 6 5 4 3 2 1
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
-5 -4 -3 -2 -1 0 1 2 3 4 5
5 4 3 2 1 0 -1 -2 -3 -4 -5
Example:
# Write a program to generate math table of input number
# 5
# 5x1=5
# 5x2=10
# ...
# 5x10=50
for i in range(1,11): # 1 2 3 4 5 6 7 8 9 10
p=num*i
print(f'{num}x{i}={p}')
.
Output:
Enter any number 7
7x1=7
7x2=14
7x3=21
7x4=28
7x5=35
7x6=42
7x7=49
7x8=56
7x9=63
7x10=70
Example:
# Write a program to generate the following series
# 1 4 9 16 25 36 ... n**2
Output:
enter value of n5
1-->1
2-->4
3-->9
4-->16
5-->25
Example:
# write a program to generate even numbers between m,n
Output:
enter value of m5
enter value of n20
6
8
10
12
14
16
18
20
Example:
# Write a program to genreate ascii table for uppercase letter
# A --> 65
# B ---> 66
# C ---> 67
# Z --> 90
Output:
A-->65
B-->66
C-->67
D-->68
E-->69
F-->70
G-->71
Example:
# Write a program to find input number is prime or not
if c==2:
print(f'{num} is prime')
else:
print(f'{num} is not prime')
Output:
Enter any number 4
4 is not prime
Example:
# Write a program to print first 10 even numbers in reverse order
Output:
20
18
16
14
12
10
8
6
4
2
s=0
for i in range(10):
num=int(input("Enter any number "))
s=s+num
avg=s/10
print(f'Avg is {avg:.2f}')
Output:
Enter any number 10
Enter any number 20
Enter any number 30
Enter any number 40
Enter any number 50
Enter any number 60
Enter any number 70
Enter any number 80
Enter any number 90
Enter any number 100
Avg is 55.00
Example:
# Accept 10 numbers from user and find maximum and minimum value
max_value=0
min_value=0
for i in range(10):
num=int(input("Enter any number "))
if i==0:
max_value=num
min_value=num
else:
if num>max_value:
max_value=num
elif num<min_value:
min_value=num
Output:
Enter any number 1
Enter any number 7
Enter any number 3
Enter any number 9
Enter any number 2
Enter any number 5
Enter any number 4
Enter any number 77
Enter any number 1
Enter any number 0
Minimum Value 0
Maximum Value 77
Output:
Example:
# Write a program to display all the numbers which are divisible by 11 but
not by 2 between
# 100 and 500
Output:
121
143
165
187
209
231
253
275
297
319
341
363
385
407
429
451
473
495
Full Stack Python (Part-29)
MCQ Practice
https://cbsepython.in/mcq-on-for-loop-
in-python-class-11/
Nested Looping Statements
1. Nested for
2. Nested while
Syntax:
Example:
# Write a program to generate tables from 1 to 5
Output:
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
1x6=6
1x7=7
1x8=8
1x9=9
1x10=10
2x1=2
2x2=4
2x3=6
2x4=8
2x5=10
2x6=12
2x7=14
2x8=16
2x9=18
2x10=20
3x1=3
3x2=6
3x3=9
3x4=12
3x5=15
3x6=18
3x7=21
3x8=24
3x9=27
3x10=30
4x1=4
4x2=8
4x3=12
4x4=16
4x5=20
4x6=24
4x7=28
4x8=32
4x9=36
4x10=40
5x1=5
5x2=10
5x3=15
5x4=20
5x5=25
5x6=30
5x7=35
5x8=40
5x9=45
5x10=50
Example:
# write a program to generate factorials of all numbers from 1-5
# 1 --> 1
# 2 --> 2
# 3 --> 6
# 4 --> 24
# 5 --> 120
Output:
Factorial of 1-->1
Factorial of 2-->2
Factorial of 3-->6
Factorial of 4-->24
Factorial of 5-->120
Example:
# write a program to print prime numbers from 2 to 20
Output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
Example:
for j in range(1,6):
for i in range(1,6):
print(1,end=' ')
print()
for j in range(1,6):
for i in range(1,6): # 1 2 3 4 5
print(i,end=' ')
print()
Output:
11111
11111
11111
11111
11111
12345
12345
12345
12345
12345
Example:
spaces=4
for r in range(1,6):
for s in range(spaces):
print(" ",end='')
for c in range(1,r+1):
print("* ",end='')
print()
spaces=spaces-1
spaces=0
for r in range(5,0,-1):
for s in range(spaces):
print(" ",end='')
for c in range(1,r+1):
print("* ",end='')
print()
spaces=spaces+1
Output:
Nested while loop
While loop inside while loop is called nested while loop.
Syntax:
while <condition>: 🡪 Outer looping statement
statement-1
statement-2
while <condition>: 🡪 Inner looping statement
statement-3
statement-4
Example:
# using while loop generate numbers from 1 to 10
num=1
while num<=10:
print(num,end=' ')
num=num+1
Output:
1 2 3 4 5 6 7 8 9 10
Example:
# Write a program to generate the following output
#1 2 3 4 5 6 7 8 9 10
#2 4 6 8 10 12 14 16 18 20
# 3 6 9 12 15 18 21 24 27 30
#....
# 10 20 30 40 50 60 70 80 90 100
n=1
while n<=10: # Outer loop
i=1
while i<=10: # inner loop
print(n*i,end=' ')
i=i+1
print()
n=n+1
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Example:
a=int(input("enter starting value "))
b=int(input("enter ending value "))
while a<=b:
i=1
s=0
while i<a:
if a%i==0:
s=s+i
i=i+1
if s==a:
print(a)
a=a+1
Output:
enter starting value 6
enter ending value 500
6
28
496
break
break is branching statement or passes control statement.
break is a keyword.
break statement is used inside looping statements (while, for).
This statement is used to terminate execution of while or for
unconditionally or in between.
Example:
for num in range(1,11):
print("Hello")
break
num=1
while num<=10:
print("Bye")
num=num+1
break
Output:
Hello
Bye
Example:
# write a program to find input number is prime or not
if c==2:
print(f'{num} is prime')
else:
print(f'{num} is not prime')
Output:
Enter any number 6
Hello
Hello
Hello
6 is not prime
Output:
UserName :nit
Password :abc
invalid username or password pls try again...
UserName :abc
Password :nit123
invalid username or password pls try again...
UserName :nit
Password :nit123
Welcome
Example:
# Write a program to generate first 10 prime numbers
num=2
prime_count=0
while True:
c=0
for i in range(1,num+1):
if num%i==0:
c=c+1
if c>2:
break
if c==2:
print(num)
prime_count=prime_count+1
if prime_count==10:
break
num=num+1
Output:
2
3
5
7
11
13
17
19
23
29
continue
Example:
for num in range(1,11): # 1 2 3 4 5 6 7 8 9 10
if num%2==0:
continue
print(num)
Output:
1
3
5
7
9
Full Stack Python (Part-33)
Example:
n=1
while n<=5:
print(n)
n=n+1
else:
print("inside else block")
n=1
while n<=5:
print(n)
break
else:
print("Inside else block")
Output:
1
2
3
4
5
inside else block
1
Example:
for num in range(1,6): # 1 2 3 4 5
print(num)
else:
print("inside else block")
Output:
1
2
3
4
5
inside else block
1
Sequences
Sequences are ordered collections, where objects are organized in
sequential order (OR) insertion order is preserved.
Properties of sequences
1. Index based
2. Allows duplicates
3. Slicing
4. Homogenous or Heterogeneous
Example:
>>> list1=[]
>>> print(list1)
[]
>>> print(type(list1))
<class 'list'>
>>> list2=[10]
>>> print(list2)
[10]
>>> print(type(list2))
<class 'list'>
>>> list3=[10,20,30,40,50]
>>> print(list3)
[10, 20, 30, 40, 50]
>>> print(type(list3))
<class 'list'>
>>> sales=[10000,20000,30000,40000,50000]
>>> stud=[1,"Nk","python",6000.0]
>>> print(sales)
[10000, 20000, 30000, 40000, 50000]
>>> print(stud)
[1, 'Nk', 'python', 6000.0]
Example:
>>> list4=list()
>>> print(list4)
[]
>>> print(type(list4))
<class 'list'>
>>> list5=list(range(1,6))
>>> print(list5)
[1, 2, 3, 4, 5]
>>> list6=list(range(10,110,10))
>>> print(list6)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list7=list("PYTHON")
>>> print(list7)
['P', 'Y', 'T', 'H', 'O', 'N']
>>> list8=list("NIT")
>>> print(list8)
['N', 'I', 'T']
>>> list9=list([10,20,30])
>>> list10=list(list9)
>>> print(list9)
[10, 20, 30]
>>> print(list10)
[10, 20, 30]
index
What is index?
Index is an integer value.
Each element/item in list/sequence identified with index.
Index is element position OR each location in list/sequence is identified
with integer value called index.
Index is used to read elements from sequence in sequentially or
randomly.
+ve index start at 0, which is used to read items left to right (forward
direction)
-ve index start at -1, which is used to read items in right to left
(backward direction)
Syntax: list-name[index]
Example
>>> L=[10,20,30,40,50]
>>> print(L)
[10, 20, 30, 40, 50]
>>> L[0]
10
>>> L[-1]
50
>>> L[2]
30
>>> L[-2]
40
>>> L[5]
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
L[5]
IndexError: list index out of range
>>> L[-5]
10
Full Stack Python (Part-34)
len() : This function returns count elements or length of iterable
Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> print(len(list1))
5
Example:
Displaying +ve and –ve values from list
list1=[1,2,-4,5,-6,6,7,8,9,-10,-12,11,-14,-13]
print(list1)
a=len(list1)
print("Reading -Ve Values from List")
for i in range(a): # start=0,stop=10,step=1 0 1 2 3 4 5 6 7 8 9
if list1[i]<0:
print(list1[i],end=' ')
print()
print("Reading +Ve values from List")
for i in range(a):
if list1[i]>=0:
print(list1[i],end=' ')
Output:
[1, 2, -4, 5, -6, 6, 7, 8, 9, -10, -12, 11, -14, -13]
Reading -Ve Values from List
-4 -6 -10 -12 -14 -13
Reading +Ve values from List
1 2 5 6 7 8 9 11
Example:
# Count of even and odd number of list
list1=[4,8,9,1,2,3,4,12,15,17,19,24,35,76,77,45,54,34,21]
print(list1)
a=len(list1)
ecount,ocount=0,0
for i in range(a): # start=0,stop=15,step=1 0 1 2 3 4 5 6 7 8 9 ... 14
if list1[i]%2==0:
ecount+=1
else:
ocount+=1
Output:
[4, 8, 9, 1, 2, 3, 4, 12, 15, 17, 19, 24, 35, 76, 77, 45, 54, 34, 21]
Even number count 9
Odd number count 10
Example:
list1=[1,2,-4,5,-6,6,7,8,9,-10,-12,11,-14,-13]
a=len(list1)
for i in range(-1,-(a+1),-1): # start=-1,stop=-15,step=-1 -1 -2 -3 -4 -5 ... -
14
print(list1[i],end=' ')
print()
for i in range(a): # start=0,stop=14,step=1
print(list1[i],end='')
Output:
-13 -14 11 -12 -10 9 8 7 6 -6 5 -4 2 1
12-45-66789-10-1211-14-13
Example:
# Write a program to add all the values of list
list1=list(range(10,110,10))
print(list1)
a=len(list1)
total=0
for i in range(a):# start=0,stop=10,step=1 0123456789
total=total+list1[i]
print(f'Total is {total}')
print(f'Avg is {total/a}')
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Total is 550
Avg is 55.0
Example:
# Python program to find smallest number in a list
scores=[50,30,20,10,50,60]
a=len(scores)
print(scores)
print(f'Minimum Score {min_score}')
Output:
[50, 30, 20, 10, 50, 60]
Minimum Score 10
Maximum Score 60
Minimum Score 10
Maximum Score 60
Total Score 220
Sort
sort(*, key=None, reverse=False)
This method sorts the list in place. It is a mutable method of list.
Reverse argument:
Default value of reverse is False, which mean it sort in ascending
order
If reserve value is given True, it sort elements in descending order
Key is a function which is applied to each element.
Example:
>>> list1=[4,5,1,8,3,9,2,7,11,66,12,15,10]
>>> print(list1)
[4, 5, 1, 8, 3, 9, 2, 7, 11, 66, 12, 15, 10]
>>> list1.sort()
>>> print(list1)
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 15, 66]
>>> list1.sort(reverse=True)
>>> print(list1)
[66, 15, 12, 11, 10, 9, 8, 7, 5, 4, 3, 2, 1]
>>> list1=["d","a","B","c","A","D","C","b"]
>>> print(list1)
['d', 'a', 'B', 'c', 'A', 'D', 'C', 'b']
>>> list1.sort()
>>> print(list1)
['A', 'B', 'C', 'D', 'a', 'b', 'c', 'd']
>>> list1.sort(key=str.upper)
>>> print(list1)
['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd']
>>> list1.sort(key=str.upper,reverse=True)
>>> print(list1)
['D', 'd', 'C', 'c', 'B', 'b', 'A', 'a']
count(value)
This method return count of given value inside iterable.
>>> list1=[1,2,3,4,1,2,3,1,2,3,5,6,7]
>>> list1.count(1)
3
>>> list1.count(5)
1
>>> list1.count(3)
3
Example:
# finding second maximum
list1=[4,8,1,9,1,2,3,4,12,15,17,19,24,35,76,77,45,54,34,21,77]
print(list1)
list1.sort()
print(list1)
fmax=list1[-1]
k=list1.count(fmax)
smax=list1[-(k+1)]
print(fmax)
print(smax)
fmin=list1[0]
k=list1.count(fmin)
smin=list1[k]
print(fmin)
print(smin)
Output:
[4, 8, 1, 9, 1, 2, 3, 4, 12, 15, 17, 19, 24, 35, 76, 77, 45, 54, 34, 21, 77]
[1, 1, 2, 3, 4, 4, 8, 9, 12, 15, 17, 19, 21, 24, 34, 35, 45, 54, 76, 77, 77]
77
76
1
2
Slicing
“Slicing” means getting a subset of elements from an iterable/sequence
based on their indices.
Slicing allows reading more than one value from sequences.
Slice operator
Syntax: sequence-name[start:stop:step]
Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list2=list1[::]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list1[:]
>>> print(list3)
[10, 20, 30, 40, 50]
Syntax2: sequence-name[::step]
In this syntax start and stop values are generated based on step value.
If step=+ve, start=0,stop=len(sequence)
If step=-ve, start=-1,stop=-(len(sequence)+1)
Example:
>>> list1=list(range(10,110,10))
print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[::1]
>>> print(list2)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list3=list1[::2]
>>> print(list3)
[10, 30, 50, 70, 90]
>>> list4=list1[::-1]
>>> print(list4)
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
>>> list5=list1[::-2]
>>> print(list5)
[100, 80, 60, 40, 20]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[5:]
>>> print(list2)
[60, 70, 80, 90, 100]
>>> list3=list1[-5:]
>>> print(list3)
[60, 70, 80, 90, 100]
Syntax4: sequence-name[:stop:] or sequence-name[:stop]
This syntax read values from left to right
Default start=0,step=1
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[:5:]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list1[:-5:]
>>> print(list3)
[10, 20, 30, 40, 50]
>>> list4=list1[:-3:]
>>> print(list4)
[10, 20, 30, 40, 50, 60, 70]
>>> list5=list1[:-8:]
>>> print(list5)
[10, 20]
Syntax5: sequence-name[start:stop:]
This syntax read values from left to right
Defaults step is +1
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[0:5]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list1[-5:-3]
>>> print(list3)
[60, 70]
>>> list4=list1[-3:-6]
>>> print(list4)
[]
>>> list5=list1[3:-3]
>>> print(list5)
[40, 50, 60, 70]
Syntax-6: sequence-name[start:stop:step]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[2:8:2]
>>> print(list2)
[30, 50, 70]
>>> list3=list1[-2:-8:-2]
>>> print(list3)
[90, 70, 50]
Syntax:
for variable in iterable:
statement-1
statement2
Example:
>>> list1=[10,20,30,40,50]
>>> for a in list1:
print(a)
10
20
30
40
50
>>> for i in range(len(list1)):
... print(list1[i])
10
20
30
40
50
Full Stack Python (Part-36)
# Find Median
list1=[1,2,3,4,5]
a=len(list1)
if a%2!=0:
mid=len(list1)//2
print(f"Median {list1[mid]}")
else:
mid=len(list1)//2
print(f"Median {(list1[mid]+list1[mid-1])/2}")
# Find Output
list1=[10,20,30,40,50]
for x in list1[::-1]: # [50,40,30,20,10]
print(x,end=' ')
print()
# Find Output
list1=[10,20,30,40,50,60,70,80,90,100]
for x in list1[-5:]: # [60,70,80,90,100]
print(x,end=' ')
print()
for x in list1[:-5]: # [10,20,30,40,50]
print(x,end=' ')
print()
for x in list1[3:-3]: # [40,50,60,70]
print(x,end=' ')
print()
for x in list1[0]: # Error 10
print(x,end=' ')
Output:
Sum of [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] is 550
Maximum value of [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] is 100
Median 3
Length of [1, 2, 3, 4, 5, 6, 7, 8] is 8
50 40 30 20 10
60 70 80 90 100
10 20 30 40 50
40 50 60 70
Traceback (most recent call last):
File "E:/student drive/FSP7PM/test120.py", line 53, in <module>
for x in list1[0]: # Error 10
TypeError: 'int' object is not iterable
Iterator object
iter(iterable) this function receives iterable object and return iterator
object. This iterator object is used to read values from iterables.
__next__() this method read and return next value from iterable.
Example:
names_list=["naresh","ramesh","suresh","kishore"]
a=iter(names_list)
n1=a.__next__()
print(n1)
for n in a:
print(n,end=' ')
Output:
naresh
ramesh suresh kishore
Example:
>>> list1=[10,20,30,40,50]
>>> a=iter(list1)
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list2=list(a)
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list(range(10,110,10))
>>> print(list3)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list4=list("abc")
>>> print(list4)
['a', 'b', 'c']
enumerate object
enumerate(iterable,start=0), this function returns enumerate object.
Enumerate is also iterator object, which iterate value and count.
Example:
sales=[10000,20000,30000,40000,5000]
e=enumerate(sales,1999)
for x in e:
print(x)
names_list=["naresh","suresh","ramesh"]
a=enumerate(names_list,1)
for stud in a:
print(stud)
Output:
(1999, 10000)
(2000, 20000)
(2001, 30000)
(2002, 40000)
(2003, 5000)
(1, 'naresh')
(2, 'suresh')
(3, 'ramesh')
1. append(element/value)
This method add element/value at the end of list
Syntax: list-name.append(value)
Example:
>>> list1=[]
>>> print(list1)
[]
>>> list1.append(10)
>>> list1.append(20)
>>> list1.append(30)
>>> print(list1)
[10, 20, 30]
>>> list1.append(40)
>>> print(list1)
[10, 20, 30, 40]
Example:
# Write a program to append 5 values in list
print(list1)
Output:
Input integer value 10
Input integer value 20
Input integer value 30
Input integer value 40
Input integer value 50
[10, 20, 30, 40, 50]
Example:
# Write a program read scores of n players and display
scores=[]
for i in range(n):
s=int(input("Enter Score "))
scores.append(s)
print(f'Scores {scores}')
print(f'Maximum Score {max(scores)}')
print(f'Minimum Score {min(scores)}')
print(f'Total Score {sum(scores)}')
Output:
How many players?4
Enter Score 10
Enter Score 50
Enter Score 20
Enter Score 40
Scores [10, 50, 20, 40]
Maximum Score 50
Minimum Score 10
Total Score 120
Example:
# Write a program to filter data
num_list=[2,8,1,2,9,5,11,15,17,18,21,89,34,56,87,23,32,37,87,56,45,34,2
3,12]
even_list=[]
odd_list=[]
for value in num_list:
if value%2==0:
even_list.append(value)
else:
odd_list.append(value)
Output:
Number List [2, 8, 1, 2, 9, 5, 11, 15, 17, 18, 21, 89, 34, 56, 87, 23, 32,
37, 87, 56, 45, 34, 23, 12]
Even numbers List [2, 8, 2, 18, 34, 56, 32, 56, 34, 12]
Odd numbers List [1, 9, 5, 11, 15, 17, 21, 89, 87, 23, 37, 87, 45, 23]
Example:
>>> list1=[]
>>> list1.append(10,20)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
list1.append(10,20)
TypeError: list.append() takes exactly one argument (2 given)
Syntax: list-name[len(list):]=iterable
Example:
>>> list1=[10,20,30]
>>> print(list1)
[10, 20, 30]
>> list1[3:]=40,50
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1[5:]=100,200,300
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300]
>>> list1[len(list1):]="NIT"
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300, 'N', 'I', 'T']
>>> list1[len(list1):]=[1,2,3,4,5]
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300, 'N', 'I', 'T', 1, 2, 3, 4, 5]
>>> list1[len(list1):]=range(-1,-6,-1)
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300, 'N', 'I', 'T', 1, 2, 3, 4, 5, -1, -2, -3, -4, -
5]
Syntax1: list-name[index]=value
Syntax2: list-name[startindex:stopindex:step]=iterable
Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1[0]=99
print(list1)
>>> [99, 20, 30, 40, 50]
>>> list1[-1]=88
>>> print(list1)
[99, 20, 30, 40, 88]
>>> list1[2]=44
>>> print(list1)
[99, 20, 44, 40, 88]
>>> list1[5]=66
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
list1[5]=66
IndexError: list assignment index out of range
>>> list1[-5]=10
>>> print(list1)
[10, 20, 44, 40, 88]
>>> list1[-6]=100
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
list1[-6]=100
IndexError: list assignment index out of range
Example:
# Python program to interchange first and last elements in a list
# Input : [12, 35, 9, 56, 24]
# Output : [24, 35, 9, 56, 12]
# 1st approch
x=list1[0]
list1[0]=list1[-1]
list1[-1]=x
# 2nd approch
list1[0],list1[-1]=list1[-1],list1[0]
print(f'After Swaping {list1}')
Output:
After Swaping [24, 35, 9, 56, 12]
After Swaping [12, 35, 9, 56, 24]
Replacing more than one value
Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1[:2]=99,88
>>> print(list1)
[99, 88, 30, 40, 50]
>>> list1[2:]=1,2
>>> print(list1)
[99, 88, 1, 2]
>>> list1[2:]=1,2,3
>>> print(list1)
[99, 88, 1, 2, 3]
>>> list1[2:]=10,20,30,40,50,60,70,80,90,100
>>> print(list1)
[99, 88, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1[3:6]=11,22,33
>>> print(list1)
[99, 88, 10, 11, 22, 33, 50, 60, 70, 80, 90, 100]
>>> list1[-10::-1]=[1,2,3,4,5]
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
list1[-10::-1]=[1,2,3,4,5]
ValueError: attempt to assign sequence of size 5 to extended slice of size
3
>>> list1[-1:-4:-1]=1,2,3
>>> print(list1)
[99, 88, 10, 11, 22, 33, 50, 60, 70, 3, 2, 1]
Example:
# Given a list in Python and provided the positions of the elements, write
a program to swap the two elements in the list.
# Examples:
# Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
# Output : [19, 65, 23, 90]
# Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5
# Output : [1, 5, 3, 4, 2]
list1=[]
n=int(input("How many values ?"))
for i in range(n):
value=int(input("Enter any value "))
list1.append(value)
print(f'Before Swaping {list1}')
pos1=int(input("Enter Pos1 "))
pos2=int(input("Enter Pos2 "))
temp=list1[pos1-1]
list1[pos1-1]=list1[pos2-1]
list1[pos2-1]=temp
Output:
How many values ?5
Enter any value 10
Enter any value 20
Enter any value 30
Enter any value 40
Enter any value 50
Before Swaping [10, 20, 30, 40, 50]
Enter Pos1 1
Enter Pos2 2
After Swaping [20, 10, 30, 40, 50]
Example:
# Reverse list in place
list1=[10,20,30,40,50]
print(list1)
list1[::]=list1[::-1] # [50,40,30,20,10]
print(list1)
list1=[10,20,30,40,50]
print(list1)
list1[:3]=list1[:-4:-1] # [50,40,30]
print(list1)
Output:
[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]
[10, 20, 30, 40, 50]
[50, 40, 30, 40, 50]
Example:
list1=[10,20,30,40,50]
i=0
for list1[i] in list1[::-1]:
i=i+1
print(list1)
list1=[10,20,30,40,50]
list2=[60,70,80,90,100]
list1[:3]=list2[:3]
print(list1)
Output
[50, 40, 30, 20, 10]
[60, 70, 80, 40, 50]
Example:
# Sorting list values using Bubble Sort
for i in range(n):
for j in range(0,n-1): # 0 1 2 3
if list1[j]>list1[j+1]:
temp=list1[j]
list1[j]=list1[j+1]
list1[j+1]=temp
del keyword
“del” keyword is used to delete one or more than one value from list.
Del keyword required,
1. Index for deleting one value/element
2. Slicing for deleting more than one value/element
Syntax1: list-name[index]
Syntax2: list-name[start-index:stop-index:step]
Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> del list1[0]
>>> print(list1)
[20, 30, 40, 50]
>>> del list1[-2]
>>> print(list1)
[20, 30, 50]
>>> del list1[3]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
del list1[3]
IndexError: list assignment index out of range
index (ele,start,stop)
This return index of given element/value.
By defining start and stop value, it will search in slice notation.
>>> list1=[10,20,30,40,50,60,70]
>>> a=list1.index(40)
>>> print(a)
3
>>> a=list1.index(100)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a=list1.index(100)
ValueError: 100 is not in list
>>> list2=[10,20,30,40,50,10,20,30,40,50,10,20,30,40,50]
>>> a=list2.index(10,-10)
>>> print(a)
5
Example:
# Write a program to read n values into list
# remove given value from list
list1=[]
n=int(input("Enter how many values?"))
for i in range(n):
value=int(input("Enter value"))
list1.append(value)
Example:
# Write a program to read n values into list
# remove given value from list
list1=[]
n=int(input("Enter how many values?"))
for i in range(n):
value=int(input("Enter value"))
list1.append(value)
if found==True:
print(f'After deleting values {list1}')
else:
print(f'{value} not exists in list')
Output:
Enter how many values?5
Enter value10
Enter value10
Enter value20
Enter value30
Enter value20
Before deleting values [10, 10, 20, 30, 20]
Enter value to delete 10
After deleting values [20, 30, 20]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list1[0:3]
>>> print(list1)
[40, 50, 60, 70, 80, 90, 100]
>>> del list1[-3:]
>>> print(list1)
[40, 50, 60, 70]
>>> del list1[1:-1]
>>> print(list1)
[40, 70]
>>> list2=list(range(10,110,10))
>>> print(list2)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list2[::2]
>>> print(list2)
[20, 40, 60, 80, 100]
>>> list3=list(range(10,110,10))
>>> print(list3)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list3[::-2]
>>> print(list3)
[10, 30, 50, 70, 90]
Example:
>>> list1=[10,20,30,40,50,60,70,80,90,100]
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1.remove(10)
>>> print(list1)
[20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1.remove(90)
>>> print(list1)
[20, 30, 40, 50, 60, 70, 80, 100]
>>> list1.remove(10)
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
list1.remove(10)
ValueError: list.remove(x): x not in list
>>> list1=[10,10,10,20,20]
>>> list1.remove(10)
>>> print(list1)
[10, 10, 20, 20]
list1=[4,9,2,3,5,1,11,13,17,23,8,12,16,18,20,22]
Output:
Before Deleting values [4, 9, 2, 3, 5, 1, 11, 13, 17, 23, 8, 12, 16, 18, 20,
22]
After Deleting values [9, 3, 5, 1, 11, 13, 17, 23]
clear()
Empty the list or remove all the values or elements from list
Example:
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1.clear()
>>> print(list1)
[]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list1[:]
>>> print(list1)
[]
pop()
pop()
list can be used as a data structure called stack.
Stack is data structure which follows LIFO (Last In First Out). The
element/value added last is removed first.
Stack allows two operations
1. Push
2. Pop
Push is operation of adding/appending element
Pop is operation of removing and returning element
Example:
>>> list1=[]
>>> list1.append(10)
>>> list1.append(20)
>>> list1.append(30)
>>> print(list1)
[10, 20, 30]
>>> list1.pop()
30
>>> print(list1)
[10, 20]
>>> list1.pop()
20
>>> print(list1)
[10]
>>> list1.pop()
10
>>> print(list1)
[]
list1.pop()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
list1.pop()
IndexError: pop from empty list
>>> undo=[]
>>> undo.append("format")
>>> undo.append("inserting image")
>>> undo.append("inserting table")
>>> print(undo)
['format', 'inserting image', 'inserting table']
>>> undo.pop()
'inserting table'
>>> print(undo)
['format', 'inserting image']
>>> undo.pop()
'inserting image'
>>> print(undo)
['format']
>>> undo.pop()
'format'
>>> print(undo)
[]
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1.pop(2)
30
>>> print(list1)
[10, 20, 40, 50]
Output:
1. Adding
2. Removing
3. Display
4. Exit
Enter your option 1
Enter any value10
10 added inside Q
Example:
>>> list1=[]
>>> list1.append(10)
>>> print(list1)
[10]
>>> list1.append(20,30)
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
>>> list1.append(20,30)
TypeError: list.append() takes exactly one argument (2 given)
>>> list1.extend((20,30))
>>> print(list1)
[10, 20, 30]
>>> list1.extend([40,50,60])
>>> print(list1)
[10, 20, 30, 40, 50, 60]
>>> list1.extend("NIT")
>>> print(list1)
[10, 20, 30, 40, 50, 60, 'N', 'I', 'T']
Example:
>>> list1=[10,20,30]
>>> print(list1)
[10, 20, 30]
>>> list1.insert(1,99)
>>> print(list1)
[10, 99, 20, 30]
>>> list1.insert(0,88)
>>> print(list1)
[88, 10, 99, 20, 30]
>>> list1.insert(-1,77)
>>> print(list1)
[88, 10, 99, 20, 77, 30]
>>> list1.insert(9,44)
>>> print(list1)
[88, 10, 99, 20, 77, 30, 44]
>>> list1.insert(-9,33)
>>> print(list1)
[33, 88, 10, 99, 20, 77, 30, 44]
>>> list1.insert(0,100,200)
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
list1.insert(0,100,200)
TypeError: insert expected 2 arguments, got 3
>>> list2=[10,20,30]
>>> print(list2)
[10, 20, 30]
>>> list2[2:2]=[40,50,60]
>>> print(list2)
[10, 20, 40, 50, 60, 30]
>>> list2[1:1]=[11,22,33,44,55]
>>> print(list2)
[10, 11, 22, 33, 44, 55, 20, 40, 50, 60, 30]
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1.reverse()
>>> print(list1)
[50, 40, 30, 20, 10]
>>> list2=[10,20,30,40,50]
>>> list3=list2[::-1]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> print(list3)
[50, 40, 30, 20, 10]
Shallow Copy
s.copy() creates a shallow copy of s (same as s[:])
Shallow copy is called reference copy. In shallow copy a new list created
by copying address/references of objects found in original list.
Example:
>>> list1=[[10,20],30]
>>> list2=list1.copy()
>>> print(list1)
[[10, 20], 30]
>>> print(list2)
[[10, 20], 30]
>>> list1[0].append(40)
>>> print(list1)
[[10, 20, 40], 30]
>>> print(list2)
[[10, 20, 40], 30]
list2[0][0]=99
>>> print(list2)
[[99, 20, 40], 30]
>>> print(list1)
[[99, 20, 40], 30]
>>> list1[1]=88
>>> print(list1)
[[99, 20, 40], 88]
>>> print(list2)
[[99, 20, 40], 30]
copy module
copy.deepcopy(iterable)
>>> list1=[[10,20],30]
>>> print(list1)
[[10, 20], 30]
>>> import copy
>>> list2=copy.deepcopy(list1)
>>> print(list2)
[[10, 20], 30]
>>> list1[0].append(90)
>>> print(list1)
[[10, 20, 90], 30]
>>> print(list2)
[[10, 20], 30]
>>> list2[0][0]=99
>>> print(list2)
[[99, 20], 30]
>>> print(list1)
[[10, 20, 90], 30]
Full Stack Python (Part-40)
Nested List
Defining list as element inside list is called nested list (OR) defining list
inside list is called nested list.
Using nested list data can be organized in rows and columns (OR) nested
list can be used to represent matrix.
Syntax:
<list-name>=[[v1,v2,v3],[v1,v2],[v1,v2,v3,v4]]
Example:
list1=[[10,20,30],[40,50,60],[70,80,90]]
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[0][0],list1[0][1],list1[0][2])
print(list1[1][0],list1[1][1],list1[1][2])
print(list1[2][0],list1[2][1],list1[2][2])
print(list1[-1])
print(list1[-1][-1],list1[-1][-2],list1[-1][-3])
print(list1[-1][0],list1[-1][1],list1[-1][2])
Output:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
10 20 30
40 50 60
70 80 90
[70, 80, 90]
90 80 70
70 80 90
Example:
# Reading elements from nested list using index
list1=[[10,20,30],[40,50,60],[70,80,90]]
for i in range(3): # start=0,stop=3,step=1 --> 0 1 2
print(list1[i])
Output:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
10 20 30
40 50 60
70 80 90
Example:
# Reading elements from nested list without using index
list1=[[1,2,3],[4,5,6],[7,8,9]]
for x in list1:
print(x)
for x in list1:
for y in x:
print(y,end=' ')
print()
Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
123
456
789
Example:
# Creating nested list by input values at runtime (OR) create 2x2 matrix
matrix=[]
matrix.append(row)
print(matrix)
Output:
Enter elements of matrix
Enter value 1
Enter value 2
Enter value 3
Enter value 4
[[1, 2], [3, 4]]
Example:
# write a program to read marks for 3 students and 3 subjects (3x3)
stud=[]
print("enter marks of students")
for i in range(3):
marks=[]
for j in range(3):
m=int(input("Enter Marks "))
marks.append(m)
stud.append(marks)
print(stud)
Output:
enter marks of students
Enter Marks 50
Enter Marks 60
Enter Marks 70
Enter Marks 80
Enter Marks 90
Enter Marks 60
Enter Marks 40
Enter Marks 50
Enter Marks 60
[[50, 60, 70], [80, 90, 60], [40, 50, 60]]
Example:
# Write a program to add two matrices
matrix1=[]
matrix2=[]
matrix3=[]
for i in range(2):
row=[]
for j in range(2):
row.append(matrix1[i][j]+matrix2[i][j])
matrix3.append(row)
print(matrix1)
print(matrix2)
print(matrix3)
Output:
Enter Elements of matrix1
Enter Value 1
Enter Value 2
Enter Value 3
Enter Value 4
Enter Elements of matrix2
Enter Value 5
Enter Value 6
Enter Value 7
Enter Value 8
[[1, 2], [3, 4]]
[[5, 6], [7, 8]]
[[6, 8], [10, 12]]
Comprehension
● List Comprehensions
● Dictionary Comprehensions
● Set Comprehensions
● Generator Comprehensions
List Comprehension
Creating list using comprehension
namesList=["nk","ramesh","suresh","kishore"]
# Create copy of list by converting all the names in upper case
namesList1=[ name.upper() for name in namesList]
print(namesList)
print(namesList1)
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
['nk', 'ramesh', 'suresh', 'kishore']
['NK', 'RAMESH', 'SURESH', 'KISHORE']