Python Material
Python Material
Introduction to Python
Introduction:
✓ Python is a general-purpose, interpreted, interactive, and high-level
programming language.
✓ It is simple to use and easy to learn and provides lots of high-level data
structures and huge library support.
✓ It supports multiple programming paradigms such imperative, procedure
oriented, and object-oriented.
✓ It’ simple syntax and dynamic typing and its interpreted nature make it an ideal
language for scripting and rapid application development.
✓ Python is known as multipurpose programming language as its huge library
support provides multiple domains of software development.
✓ Python is a dynamically typed language, i.e., we can use the variables without
declaring.
✓ Python is recommended as the first programming language for beginners.
✓ Python is Open source and Free, so it has vast community across the world.
History of Python
✓ Python was Developed by Guido van Rossum at National Research Institute for
Mathematics and computer science in Netherlands in 1989 and it was made
available to the public in 1991
✓ The name Python is taken from Monty Python's Flying Circus, it is a British
comedy series created by the comedy group Monty’s Python.
✓ Guido van Rossum has developed Python Programming language by taking
almost all features from different programming languages.
✓ Majority of the Syntax's in python is taken from C Programming and ABC
scripting language.
Python versions:
Year Version
1994 Python 1.0
2000 Python 2.0
2008 Python 3.0
2020 Python 3.9
Note:
✓ Every Major version includes sub version also.
✓ 2.7.14 is the latest version of Python 2
✓ 3.9.6 is the latest version of Python 3 (Released on 28th June,2021)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[1]
Difference between Programming Languages and Scripting languages:
Programming Languages Scripting Languages
1. Run by compiler 1. Run by Interpreter
2. Required explicit compilation 2. Does not require explicit compilation
3. Code is compiled at a time. 3. Code is interpreted line by line.
4. Slow in development, fast in 4. Fast in development, slow in execution
execution
5. Basic, Cobol, C, CPP, JAVA etc. 5. Shell script, Perl, Python, Ruby, Power
Shell etc.
The following are the list of programming languages whose features available in
python:
1. C – Procedure Oriented Programming language.
2. C++, Java – Object Oriented Programming languages.
3. Shell Script, Perl – Scripting Languages.
4. Modula-3 – Modular Programming Language.
Features of Python:
1. Python is Simple, easy, and Powerful programming language.
2. High-level programming language.
3. Python is an expressive language.
4. Python is free, opensource and redistribution language.
5. Python is interpreted language.
6. Python is extensible language.
7. Python is very rich in libraries.
8. Python supports Object oriented Programming language also.
9. Python is portable language.
Limitations:
1. Slow in performance compared to C, CPP or Java.
2. Not suitable for mobile applications.
3. No backward compatibility.
4. Has limitations with Data Access.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[2]
Applications of Python:
There are many real time applications which are built on top of Python in almost all
domains. You can do almost any task with Python.
✓ Desktop applications
o CUI applications
o GUI applications (PyGUI, PyGUI, tKinter)
✓ Web applications
o Django, Flask, Bottle, Pyramid etc.
✓ Mathematical & scientific applications
✓ Games & 3D Graphics
✓ Network programming
✓ Database applications
✓ Business applications – ERP & E-Commerce
✓ Machine learning
✓ Artificial Intelligence
✓ Data Analysis
Here is the List few world class Companies that use python:
✓ Google
✓ YouTube
✓ Facebook
✓ Instagram
✓ Spotify
✓ Quora
✓ Netflix
✓ Dropbox
✓ Reddit
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[3]
Downloading & Installing Python on Windows 10 Operating System
Step 1:
To download python, visit the official website of python.
https://www.python.org/downloads/
Step 2:
Once the download is complete run the.exe file to install python and the installation
starts.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[4]
Step 3:
Installation Begins…
>>>>>
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[5]
>>>>>
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[6]
Writing/Developing applications in python
Python is an interpreted programming language because python programs are
executed by an interpreter. There are two ways to use the interpreter.
1. Interactive mode using IDLE or Command Prompt
2. Script mode using IDLE or Command Prompt
Interactive Mode:
Interactive mode means we use command line shell, type the python statement and
the interpreter print the result.
Python Shell is also known as REPL, which is used to execute a single Python
command and display the result. REPL Means (Read, Evaluate, Print, Loop), where it
reads the command, evaluates the command, prints the result, and loop it back to
read the command again.
>>> 10+20
30
>>> is known as python prompt, what is provided at the prompt is taken by python
interpreter and prints the result.
Interactive mode is not suitable for developing lengthy applications, it is just used to
test the basic functionality of the python.
Script mode:
In script mode we write python programs in a file and use the interpreter to execute
the contents of that file. The extension of python file is .py
We can use Editor’s, IDE’s and Online IDE’s to write python programs.
✓ Editors : Python IDLE, Notepad, Editplus, notepad++,Sublime Text, gedit etc. are
the editors to write python programs.
✓ IDE’s: PyCharm, Eric, Eclipse, NetBeans, PyScripter, Jupyter etc. are different
IDE’s to write python programs.
✓ Online IDE: https://replit.com, https://www.onlinegdb.com,
https://www.online-python.com
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[7]
How to get History in IDLE ie using Previous commands using Up Arrow
✓ IDLE → Options → Configure IDLE → Keys → History-Previous → Get New Key for
Selection → UP Arrow → Apply → OK
Comments in Python
Comments are used to describe the purpose of the code. Commented code is ignored
by Compilers and interpreters.
Comments are of two types
1. Single Line Comment
2. Multi Line Comment
Ex:
# This is a comment.
Multiline Comment:
Use the triple quotes ('''''') for multiline comment.
The triple quotes are also used to string formatting.
''' This is a
Multiline
Comment '''
Modules in python:
A Module is a file in python with .py extension which contains variables, functions, and
classes etc. a module is just like library files of C/C++.
There is more than 200+ Built-In Modules in python and here is the List of the
python standard modules:
https://docs.python.org/3/py-modindex.html
to make use of these modules we must import these modules using import statement
which is like # include statement of C/C++
ex:
import math
import keyword
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[8]
Functions, Modules, Library and Packages:
Function 1
Function 2 Module 1
Function 4
Module 2
Function 5
Example:
#This is my First Comment in Python - single line comment
print("My Name is Atish Jain, I Teach Coding") #print function prints output
print("Square Root of 625 is:",m.sqrt(625))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[9]
What is PIP?
✓ PIP is a Package Installer for Python
✓ PIP is a package management system used to install and manage software
packages (External Libraries) written in Python.
✓ It's a tool that allows you to install and manage additional libraries and
dependencies that are not distributed as part of the standard library.
✓ PIP connects to an online repository of public packages, called the Python
Package Index.
> PIP
Examples:
>pip install numpy
>pip install tenserflow
>pip install pygame
>pip install moviepy
Un installing packages:
>pip uninstall numpy
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[10]
Verifying Package Installations: ( use this command from command prompt)
Syntax:
> pip show package_name
Ex:
> pip show numpy
Note:
In my System the python software is installed at this location, kindly check in your
system also and set the path.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[11]
Ex: Adding of two numbers using python IDLE:
Open python IDLE → File → New → File
a=10
b=20
print(a+b)
Save the file with the name: add.py
F5 – to run the python script.
This python file can be run from the windows command prompt/Power shell also.
Goto the location where the file is saved.
> py add.py
Or
> python add.py
Working with Python IDLE in interactive Mode:
Windows Search → IDLE
>>> 5+5
10
>>> 5-2
3
>>> 5*5
25
>>> 5/2
2.5
>>> 5//2
2
>>> 10+5*2
20
>>> (10+5)*2
30
>>> 2*2*2*2
16
>>> 2**4
16
>>> 10%2
0
>>> 10%3
1
Note:
5//2 – Integer Division or floor Division
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[12]
How to use output of previous operation in python interactive mode:
>>>100+10
110
>>> _+90
200
Note: _ gets the output of the previous operation.
Syntax:
print(Object(s), sep=separator, end=end, file=sys.stdout,flush=false)
a=10
print("The Value is:”, a)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[13]
Working with sep and end:
ex1.py
print("Atish", "Jain")
print("Atish", "Jain", sep="--")
print("Atish")
print("Jain")
ex2.py
a=5
print("a =", a, sep='00000', end='\n\n\n')
print("a =", a, sep='0', end='')
ex3.py
print ("Atish Jain")
print (5 * "\n")
print ("Coding Career Expert")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[14]
Keywords
✓ Keywords are the Reserved words of the language. Keywords have some
predefined functionality, they cannot be used as identifiers, or constants.
✓ Keywords in python are case sensitive.
✓ Python contains 36 keywords in Python 3.9,all the keywords are in lowercase
except 3 keywords.
✓ The 3 Keywords True, False and None are capitalized.
✓ In Python 3.9 there are 36 keywords and in future version of python the
number may increase.
Note:
In Python 2 print is a keyword, from Python 3+ onwards print is removed from
keywords list and included as built-in function.
Help In Python:
Use the command help() to get the list of all available keywords of python.
>>> help("keywords")
Use help("specific keyword") to get help of specific keyword.
>>> help("if")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[15]
Hands-on-Lab
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[16]
2.Variables & Data Types
Variable:
▪ Variable is an entity which holds data.
▪ Variables are nothing but the names of memory locations where values are
stored.
▪ Values of variables may change in the future as per the program requirements.
▪ In python variables are created as soon as they assigned with a value, forward
declaration is not required.
In python variables datatype is assigned after the initialization, based upon type of the
data.
Ex:
>>> x=100
>>> print(x)
100
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[17]
Python Datatypes compared to other languages.
Statically typed language:
The languages which enforce the programmer to declare all variables with their
datatypes before using them are statically typed languages.
Ex: C, Java.
Python is a Dynamically typed language (it doesn’t use explicit type declaration) and
Strongly typed language (because once a variable has a type then it really matters).
Objects Identity:
✓ Every Object that is created is given a number that uniquely identifies it.
✓ It is guaranteed that no two objects will have the same identifier.
✓ The id() function returns identity (unique integer) of a Variable/object.
✓ The type() function returns datatype of a variable
Note:
Identity of the object is unique and remains constant during its lifetime.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[18]
Working with PyCharm IDE
https://www.jetbrains.com/pycharm/download/download-
thanks.html?platform=windows&code=PCC
x=10
y=12.50
z="Python"
print("Datatype of x:",type(x))
print("Identity of x:",id(x))
print("Datatype of y:",type(y))
print("Identity of y:",id(y))
print("Datatype of z:",type(z))
print("Identity of z:",id(z))
Note: Just By Declaraing a Variable in Capital Letters ex: PI, we can just show our
intention that this is constant variable, but still it can be modified.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[19]
Small Integer Caching:
✓ Python Catches Small Integers between -5 and 256, These numbers are used so
frequently that it’s better for performance to already have these objects
available. So, these integers will be assigned at startup. Then, each time you
refer to one, you’ll be referring to an object that already exists.
✓ All the integers in [-5, 256] are known as singletons because they’ve been
already saved in the memory.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[20]
Ex 2: run this code is python script file
a=250
b=250
print(a is b)
x=257
y=257
print(x is y)
Output:
True
True
Note:
✓ Python compiler is very smart and will do many optimizations for us under the
hood. If we run our code as a whole script, the Python compiler can “see” the
whole program at once and do the corresponding optimization’s.
✓ As to our example, since the Python compiler saw the whole program, it knew
there are two variables x and y, and they are equal to the same integer 257.
Therefore, it was reasonable to create one integer object and reference the two
variables into it. This optimization can save time and memory costs.
✓ However, if we run the code line by line in the interactive Python shell, the
compiler can only see one line of code each time.
✓ It means when we input y=257, the compiler just sees this line of code, and
cannot remember the previous code x=257. Because the 257 is not in the
special range, which is [-5, 256], a new integer object is created.
✓ Since we know this character of the Python compiler, we can use a trick to make
the x is y output True on the interactive shell as well:
>>> x=300
>>> y=300
>>> x is y
False
>>> x=300; y=300
>>> x is y
True
As shown above, we can put the two assignments into one line. Since the interactive
Python interpreter can see the two variables at once now, the optimization works
again.
Read This Article for more Information:
https://medium.com/techtofreedom/3-facts-of-the-integer-caching-in-python-
20ce587f09bb
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[21]
Variable types:
In many programming languages, variables are statically typed. That means a variable
is initially declared to have a specific data type, and any value assigned to it during its
lifetime must always have that type.
Variables in Python are not subject to this restriction. In Python, a variable may be
assigned a value of one type and then later re-assigned a value of a different type:
>>> a=10
>>> type(a)
<class 'int'>
>>> a=12.50
>>> type(a)
<class 'float'>
>>> a="atish"
>>> type(a)
<class 'str'>
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[22]
Data Types in python
✓ Datatypes are used to specify what type of data that a variable is going to hold.
✓ Generally, we cannot declare variables without datatypes in most of the
programming languages(c, cpp, java etc.).
✓ Datatypes are the keywords of the programming language.
✓ In python, variables are declared without datatypes and assigned with values,
because python interpreter allocates datatypes dynamically at runtime when
the application is running.
✓ In python datatype of a variable is decided by the interpreter based on the
value that is assigned to the variable.
✓ If the datatype is specified explicitly then interpreter throws error.
✓ In Python Programming everything is an Object, so datatypes are classes and
variables are objects of these classes.
✓ The following are the standard built-in-datatypes.
Data Types
Sequence
Numeric Boolean Dictionary Set
Type
Integer String
Float List
Compex
Tuple
Number
Python supports two types of data types:
1. Fundamental/Basic/Primitive datatypes.
2. Composite datatypes/collection datatypes.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[23]
None:
The None keyword is used to define a null variable or an object. In Python, None
keyword is an object, and it is a data type of the class None Type.
When a variable is not assigned to any value or if we want to remove the object
reference then we can use None, None works like null in other languages.
>>> a=10
>>> a
10
>>> a=None
>>> a
int datatype:
if we assign whole number/non-decimal value to a variable , then the interpreter
assigns int datatype to that variable.
Ex:
>>> a=10
>>> print(a)
10
>>> type(a)
<class 'int'>
float datatype:
if we assign decimal value to a variable , then the interpreter assigns float datatype to
that variable.
Ex:
>>> a=10.50
>>> print(a)
10.5
>>> type(a)
<class 'float'>
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[24]
String datatype:
if we assign a string value to a variable , then the interpreter assigns string datatype to
that variable.
Ex:
>>> s="ahcareer"
>>> print(s)
ahcareer
>>> type(s)
<class 'str'>
bool datatype:
if we assign a True or False to a variable , then the interpreter assigns boolean
datatype to that variable.
Ex 1:
>>> x=True
>>> print(x)
True
>>> type(x)
<class 'bool'>
Ex 2:
>>> a=10
>>> b=20
>>> c=a>b
>>> c
False
>>> print(type(c))
<class 'bool'>
Complex datatype:
if we assign a Complex value to a variable , then the interpreter assigns complex
datatype to that variable.
Note: a Complex Number is just two numbers added together (a Real and an
Imaginary Number)
Ex:
>>> e=3+5j
>>> print(e)
(3+5j)
>>> type(e)
<class 'complex'>
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[25]
Type Conversion
The Process of Converting the Variable of one datatype to another type is called type
conversion.
There are two types of conversions:
1. Implicit conversion
2. Explicit conversion
Ex 1:
>>> a=12.50
>>> b=int(a)
>>> b
12
Ex 2:
>>> a=10
>>> b="20"
>>> c=a+b
>>> c=a+int(b)
>>> c
30
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[26]
There are two type conversion functions.
1. Type casting functions.
2. eval() function.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[27]
2. float():
used to convert any datatype into float type.
Note:
Complex type cannot be converted into float type.
3. complex():
Used to convert string type into complex type.
Ex 1: String to complex
>>> a="10"
>>> x=complex(a)
>>> x
(10+0j)
>>> type(x)
<class 'complex'>
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[28]
4. bool():
Used to convert any other data type into boolean type.
Ex 1: int to boolean Ex2: int to Boolean
>>> a=10 >>> a=0
>>> type(a) >>> type(a)
<class 'int'> <class 'int'>
>>> b=bool(a) >>> b=bool(a)
>>> b >>> b
True False
>>> type(b) >>> type(b)
<class 'bool'> <class 'bool'>
Ex3: float to boolean Ex4: float to Boolean
>>> a=12.50 >>> a=0.0
>>> type(a) >>> type(a)
<class 'float'> <class 'float'>
>>> b=bool(a) >>> b=bool(a)
>>> b >>> b
True False
>>> type(b) >>> type(b)
<class 'bool'> <class 'bool'>
Ex5: string to Boolean Ex6: complex to Boolean
>>> a="hello" >>> a=0+0j
>>> type(a) >>> type(a)
<class 'str'> <class 'complex'>
>>> b=bool(a) >>> b=bool(a)
>>> b >>> b
True False
>>> type(b) >>> type(b)
<class 'bool'> <class 'bool'>
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[29]
Operators in python
✓ An operator is a symbol that tells the interpreter to perform certain
mathematical and logical manipulations.
✓ Operators are used in a program to manipulate data and variables.
✓ Python language supports the following types of operators.
1. Arithmetic operators
2. Assignment operators
3. Unary Operators
4. Comparison (ie Relational) operators
5. Logical operators
6. Membership operators
7. Identity operators
8. Bitwise operators
Arithmetic operators:
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponent
// Floor division
Example:
a=5
b=2
print("a is",a," b is",b)
print("Addition :",a+b)
print("Subtraction :",a-b)
print("Multiplication :",a*b)
print("Division :",a/b)
print("Modulus :",a%b)
print("Exponent :",a**b)
print("Floor Division :",a//b)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[30]
Assignment operators:
Operator Description
= Simple assignment
+= Add and assignment
-= Subtract and assignment
*= Multiply and assignment
/= Divide and assignment
%= Modulus and assignment
//= Floor division and assignment
a+=20
print("a+=20 is:",a)
a-=5;
print("a-=5 is:",a)
a*=2;
print("a*=2 is:",a)
a/=5;
print("a/=5 is:",a)
a//=2; # will give result in decimal becoz a value is in decimal
print("a//=2 is:",a)
a%=3;
print("a%=3 is:",a)
Unary operators:
Operator Description
+ Unary Positive
- Unary Negative
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[31]
Comparison operators:
Comparison operators are used to compare the values of variables.
Operator Description
== Checks for equality
!= Checks for not equality
> Greater than
< Less than
>= Greater than
<= Less than
Example:
# Example on Comparison Operators
a=5
b=2
Logical Operators:
The following are the logical operators supported by python; they are:
Operator Description
AND Logical and
OR Logical or
NOT Logical not
AND: Logical and returns Ture if both values are True, otherwise it returns False.
X Y X and y
True True True
True False False
False True False
False False False
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[32]
# Example on Logical Operator - and
print("5>3 and 5>2 :",5>3 and 5>2)
print("5<3 and 5<2 :",5<3 and 5<2)
print("5>3 and 5<2 :",5>3 and 5<2)
print("5<3 and 5<2 :",5<3 and 5<2)
OR: Logical or returns True if any of the values are True, returns False when both
values are false.
X Y X and y
True True True
True False True
False True True
False False False
a=True
b=False
print(not a)
print(not b)
Membership Operators:
Membership operators are used to test membership in a sequence, such as string, list,
tuple.
Operator Description
in Evaluates to true if the value is found in the sequence otherwise false
not in Evaluates to true if the value is not found in the sequence otherwise false
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[33]
Ex:
lst=[12,34,45,100]
print(45 in lst)
print(99 in lst)
print(100 not in lst)
print(99 not in lst)
Identity operators:
Identity operators compares the memory locations or references of the objects.
Operator Description
Is Returns true if both the objects refer to the same memory location
otherwise false.
is not Returns true if both the objects do not refer to the same memory location
otherwise false.
Ex:
a=10
b=10
x=500
y=800
print(id(a),"-",id(b))
print(a is b)
print(a is not b)
print(id(x),"-",id(y))
print(x is y)
print(x is not y)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[34]
Number System
The Number System is a system to represent numbers.
The various number systems are:
1. Decimal Number System (Base 10) (0-9)
2. Binary Number System (Base 2) (1&0)
3. Octal Number System (Base 8) (0-7)
4. Hexadecimal number System (Base 16) (0-9,a-f)
Bitwise operators:
✓ Bitwise operators take one or two operands and performs bit by bit operations
on them.
✓ Here is the list of bitwise operators of python
o & - Binary AND
o | - Binary OR
o ^ - Binary XOR
o ~ - Binary one’s complement
o << - Binary Left shift
o >> - Binary Right shift.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[35]
Example on bitwise operators:
a=11
b=15
print("a&b",a&b)
print("a|b",a|b)
print("a^b",a^b)
print("~a",~a)
print("~b",~b)
Negative numbers:
Negative numbers are represented by performing two’s complement operation.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[36]
Operators precedence.
The following table lists all operators from highest precedence to lowest.
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators
Not Logical NOT
And Logical AND
Or Logical OR
Example:
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[37]
We can assign single value to single variable, multiple values to multiple variables or
Single value to multiple variables.
Assigning Single value to Single variable:
>>> a=10
>>> a
10
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[38]
Escape sequence characters:
The sequence of character which has a Special meaning when it is used with in a
string.
Code Description
\' Single quote
\" Double quote
\\ Back slash
\n New line
\t Tab space
\r Carriage Return
\b Back space
Examples:
#Example on \n and \t
print("Atish\nJain")
print("Atish\tJain")
Method 1:
Using Double backslash
Method 2:
Using raw string
>>> print(r"In Python also \n prints output in new line")
In Python also \n prints output in new line
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[39]
Reading data from keyboard:
The input() function:
✓ Use the input() function to read data from the keyboard.
✓ input() function returns the inputted value in the form of a string.
✓ To convert the inputted string data into its relevant type then we can have to
use typecasting or eval() function.
Ex1:
age=input("Enter ur age:")
print(age)
print(type(age))
output:
Enter ur age:12
12
<class 'str'>
output:
Enter ur age:10
10
<class 'int'>
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[40]
Working with eval() function:
✓ The eval() function evaluates the specified expression, the expression must be a
legal Python statement.
✓ eval() function is used to convert any string type(int,float,complex) to its
relevant type ie it converts based on value.
✓ String input must be passing by enclosing in single quotes or double quotes.
Syntax:
evals(expression,[globals],[locals])
Ex 1:
a=eval(input("Enter integer value:"))
print(a)
print(type(a))
a=eval(input("Enter decimal value:"))
print(a)
print(type(a))
a=eval(input("Enter complex value:"))
print(a)
print(type(a))
Note:
Generally input function returns string, eval() function converts inputted string type
number to its relevant datatype based on the input.
Note:
eval() function will work with int and float datatype both, when input type is not
known in advance then, eval() function is recommended.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[41]
Using eval() function to evaluate expression:
output:
Enter an expression :2+5+10-5
12
input():
The input function treats the inputted data as string if the input is included in " "
quotes. Otherwise, the data is taken as it is, ie numbers as numbers and strings as
strings.
raw_input():
Always the inputted data is treated as string weather it is enclosed in quotes or not.
Note: deprecated in python 3.
python 3:
input():
Always treats the inputted data as string type.
Ex 1:
input = input("Enter any number of your choice:")
print(input)
print(type(input))
output:
Enter any number of your choice: 10 + 10
10 + 10
<class 'str'>
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[42]
We have entered an integer 10+ 10 where we were expecting a result of 20 (10 + 10)
but the input method returned a string of the same input entered.
output:
Enter any number of your choice: 10 + 10
20
<class 'int'>
In the case of eval, it returned the evaluated expression 20 in the form of an integer
given the string as input. 10 + 10 is an expression that returns 20 as a result.
Each of these methods have their advantages, and disadvantages that make them
cumbersome to use in practice.
This PEP proposed to add a new string formatting mechanism: Literal String
Interpolation. In this PEP, such strings will be referred to as "f-strings"
This PEP does not propose to remove or deprecate any of the existing string
formatting mechanisms.
In Python source code, an f-string is a literal string, prefixed with 'f', which contains
expressions inside braces. The expressions are replaced with their values.
PEP:
PEP stands for Python Enhancement Proposal. A PEP is a design document providing
information to the Python community or describing a new feature for Python or its
processes or environment. The PEP should provide a concise technical specification of
the feature and a rationale for the feature.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[43]
Example on Manual Formatting:
Ex:
name=input("Enter ur Name:")
age=int(input("Enter ur Age:"))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[44]
Formatting the output using f-string:
F-strings provide a concise and convenient way to embed python expressions inside
string literals for formatting.
Ex:
name=input("Enter ur Name:")
age=int(input("Enter ur Age:"))
print(f"Heyy My Name is,{name} and i am {age} years old")
name=input("Enter ur name:")
age=int(input("Enter ur age:"))
#manual formatting
print("Heyy My Name is",name,"and i am",age,"Years old")
#% formatting
print("Heyy My name is %s and i am %d years old"%(name,age))
#str.format()
print("Heyy My Name is {} and i am {} years old ".format(name,age))
#F string formatting
print(F"Heyy My name is {name} and i am {age} years old")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[45]
Standard Built-In Functions
✓ A function is a group of related statements that performs a specific task.
✓ built-in functions are those functions whose functionality is pre-defined.
✓ Python 3 comes with approx. 68 built in functions, that you can readily use in
any Python program.
✓ All these functions are categorized as based on their functionality as
o Math functions, String functions, type conversion functions, and iterables
and iterators, datatype related, input & output related etc.
o https://realpython.com/python-data-types/ - check for more details
✓ A brief overview you can See the Python documentation on built-in functions
for more detail.
o https://docs.python.org/3.6/library/functions.html
Ex 1:
# Example to work with python built-in functions
import math
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[46]
Working with alias while importing modules:
>>> import math as m
>>> math.sqrt(25)
5.0
>>> m.sqrt(25)
5.0
>>>
>python argsex.py 10 20
Note: Output of One application can be given as input to another application without
human involment.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[47]
ASCII Codes
Function: A function is block of statements which performs a task and Functions are
not tied to any Object, they are independent.
Method: A Method is also block of code which performs a task, Methods are also
Similar to Functions, but they are tied to Specific objects in which they are defined.
Write a Program to Read a character, Print its ASCII Code and read an integer, print
its ASCII Value.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[48]
Hands-On-Lab
1. Write a Program to Read two Numbers and print their sum.
2. Write a Program to read two inputs and display their datatypes and ids.
Note: Variables taken x and y
output format:
datatype of x is <class 'int'> and id of a is 1821488539856
3. Write a Program to read two integers and compare their identity.
4. Write a program to read total time in minutes and convert into hours and
minutes.
5. Write a program to find total and average for imputed 3 subjects.
6. Write a program calculate bill amount for the inputted quantity and price.
Note: price and quantity can be integer or decimal value.
7. Write a Program to print sum of two numbers(code should be written in one
line).
8. Program to swap the values of two variables A and B
9. Program to swap the values of two variables A and B without using 3rd variable.
Note:
a,b=b,a – This works only in Python
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[49]
3.Programming Constructs
Programs are designed and implemented using common building blocks, known as
programming constructs. These constructs are sequence, selection and iteration and
they form the basis for all programs.
Sequence is the order in which instructions are executed one by one from top to
bottom.
Conditional Statements
✓ In general, statements are executed sequentially ie statements are executed
from first to last one after the another. There may be a situation when you need
to execute statements only if a certain criterion is met.
✓ Decision making is the one of the most important aspects of almost all the
programming languages.
✓ Decision making allows us to run a particular block of code for a particular
decision.
✓ Conditional statements are also called decision-making statements. We use
those statements when we want to execute a block of code when the given
condition is true or false.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[50]
Indentation:
✓ One of the most distinctive features of python is indentation, which is used to
mark block of code.
✓ In c, cpp and java we use curly braces to represent block of code, in python curly
braces are not allowed to indicate block of code.
✓ Block of codes are denoted by indentation in python instead of curly braces ({}).
Block 1
Block 2
Block 3
Block 2, continuation
Block 1, continuation
Ex:
I am a Parent
I am a Child
I am grand Child
I am another Child
Note:
The number of spaces in the indentation is not fixed, but all statements with in the
block must be indented the same amount .
IF Statement:
IF the condition is satisfied then the statements of if block are executed.
Syntax:
If expression:
Statement 1:
Statement 2:
………………..
Statement N:
Example:
avg=eval(input("Enter ur average marks:"))
if avg>=40:
print("Ur Passed...")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[51]
IF Else Statement:
If else statement has two blocks, first block follows the expression and the second
block follows the else clause.
Syntax:
If expression:
Statement 1:
Statement 2:
………………..
Statement N:
else:
Statement 1:
Statement 2:
………………..
Statement N:
Importance of Indentation:
Program to check whether the student has passed or failed from the inputted
average marks.
Note: Print common statement Thank U ! for both passed and failed result.
avg=eval(input("Enter average marks:"))
if avg>=40:
print("Passed...")
print("Congrats...")
else:
print("Failed...")
print("Better luck next time...")
print("Thank U !") # Common statement
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[52]
Multiple if’s/elif statement:
This if-elif checks multiple conditions.
Syntax:
If expression:
Statement 1:
Statement 2:
………………..
Statement N:
elif:
Statement 1:
Statement 2:
………………..
Statement N:
else:
Statement 1:
Statement 2:
………………..
Statement N:
if avg>=60:
print("First Class...")
elif avg>50:
print("Second Class....")
elif avg>=40:
print("Third Class....")
else:
print("Failed....")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[53]
Nested if:
If expression:
If expression:
Statement 1:
Statement 2:
………………..
Statement N:
else:
Statement 1:
Statement 2:
………………..
Statement N:
else:
Statement 1:
Statement 2:
………………..
Statement N:
if a>b:
if a>c:
print("Biggest no is:",a)
else:
print("Biggest no is:",c)
else:
if b>c:
print("Biggest no is:",b)
else:
print("Biggest no is:",c)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[54]
Working with Logical Operators:
1. AND
2. OR
3. NOT
ch=input("Enter a character:")
ch=ch.lower()
print("Type of ch is:",type(ch))
if(ch=='a' or ch=='e' or ch=='i'or ch=='o'or ch=='u'):
print("Vowel...")
else:
print("Consonant...")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[55]
Working with NOT Operator:
Write a Program to Read a non-ZERO Integer no and Display "WELCOME" Message.
if(not no==0):
print("Welcome")
Ex1:
>>> x=10 if 5<8 else 99
>>> x
10
Ex2:
>>> x="welcome" if 10>5 else "Bye"
>>> x
'welcome'
Ex3:
>>> x="welcome" if 10<5 else "Bye"
>>> x
'Bye'
Biggest.py
a=eval(input("Enter first no...:"))
b=eval(input("Enter second no...:"))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[56]
Hands-On-Lab
1. Write a program to read 2 no’s and check which is the biggest one and check for
the similarity also.
2. Write a program to check whether the inputted no is positive, or negative or
neutral.
3. A company decided to give bonus of 10% to all the employees if they have more
than 5 years of Service. Ask the user for their salary and year of service and print
the bonus amount.
4. Read the values of length and breadth of a Shape from the user and check if it is
square or Rectangle.
5. A Departmental store Gives 10% Discount if the Total Bill Amount is more than
1000 other wise 5% Discount. Write a Program to Print Discount Amount and
Final Bill Amount.
6. A school has following rules for grading system:
a. Above 90% - A+
b. 80 – 90% - A
c. 70 – 80% - B+
d. 60 – 70% - B
e. 50 – 60% - C
f. Below 50% - Fail
Ask user to enter marks and print the corresponding grade.
7. Take input of age of 3 people by user and determine oldest among them.
8. Write a program to print absolute value of a number entered by user.
E.g.-
a. INPUT: 1 OUTPUT: 1
b. INPUT: -5 OUTPUT: 5
9. A student will not be allowed to sit in exam if his/her attendance is less than
75%.
a. Take following input from user
b. Number of classes held
c. Number of classes attended.
d. And print percentage of class attended
e. Is student is allowed to sit in exam or not.
f. Note: if he/she has medical cause. Ask user if he/she has medical cause or not
( 'Y' or 'N' ) and print accordingly.
10.Write a program to check if a year is leap year or not.
a. If a year is divisible by 4 then it is leap year but if the year is century year
like 2000, 1900, 2100 then it must be divisible by 400.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[57]
11.Write a Program to Check Whether the Person is Eligible for Bonus or not Based
Upon the Data Given Below.
Bonus is Given Only to the Following Persons.-
a. Persons who are married.
b. Unmarried Male above 30 years.
c. Unmarried Female above 25 years.
12.Note: Solve the Above Problem using logical operators also. Write a Program to
Read two Positive Integers and Display their absolute Difference.
13.Write a Program to Read name and Age of two Friends and Display who is elder
than whom.
14.AH Digitals is a Leading Mobile Store in the Market, they run various attractive
offers to sell High-end mobiles to their customers, They Offer Credit Facility to
their regular customers with certain criteria.
a. If the customer pays cash, then 25% discount is allowed. If a customer
buys on credit and paid within 7 days, then 15% of discount is allowed
else 10% extra is charged. Write a Program to generate Bill for the
Customer.
15.Write a program to read marks of 3 subjects, find total, average and grade only
if every subject cross 40 marks. Otherwise display in which subjects he is failed.
Avg Marks Grades
>=60% First
50-60% Second
40-50% Third
Below 40% Failed
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[58]
4.Loops
While loop:
While loop can execute set of statements if a condition is true.
Ex:
Print "Welcome" 10 Times
count=1
while count<=10:
print("Welcome")
count=count+1
Ex 1:
i=1
while i<=10:
print(i)
i+=1 #i=i+1
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[59]
Ex 2:
Write a Program to Print Sum of N Inputted Numbers:
count=1
sum=0
while count<=size:
no=int(input(F"Enter {count} no: "))
sum=sum+no
count+=1
print(F"Sum of {size} Numbers is {sum}")
Debugging:
Set Breakpoint (Click on the left margin(line numbers))
Run→ Debug
Run→ Run Debugging Actions
sum=0
no=1
while no<=10:
sum=sum+no
no=no+1
print("Sum is:",sum)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[60]
Ex 3:
Write a Program to Print Table no for the inputted no:
Ex 4:
Write a program to count number of digits from the inputted no.
no=int(input("Enter a no:"))
count=0
while no>0:
count+=1
no//=10
Ex 5:
Counting number of digits if Negative Number is inputted:
no=int(input("Enter a no...:"))
if no<0:
no=no*-1
count=0
while no>0:
no=no//10
count=count+1
print("No of Digits are:",count)
Note:
The above code can be solved using absolute function abs() also.
if no<0:
no=abs(no)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[61]
for loop:
✓ A Python for loop iterates over a sequence(string, list, tuple, set, range) or any
iterables object until that object is complete.
✓ For instance, you can iterate over the contents of a list or a string.
✓ The for loop uses the following syntax:
o for item in object, where “object” is the iterables over which you want to
iterate.
Ex 1:
Printing Natural numbers(0-9) using for loop and range()
for i in range(10):
print(i)
Ex 2:
Printing Natural numbers(1-10) using for loop and range()
for i in range(1,10+1):
print(i)
Ex 3:
Printing Even Numbers(10-20) using for loop and range()
for i in range(10,22,2):
print(i)
Ex 4:
Printing Numbers(10-1) using for loop and range()
for i in range(10,0,-1):
print(i)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[62]
Iterating over a String:
Ex 7:
str="AHCAREER"
for i in str:
print(i)
Ex 8:
We can define the string in for loop itself
for i in "Atish":
print(i)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[63]
Jump statements:
Jump statements used to control the loop flow by transferring the control from one
location to another location in the program.
There are 3 jump statements in python
1. Break
2. Continue
3. pass
Break:
Break statement is used to terminate/exit a loop(for/while). The purpose of this break
statement is to end the execution for the loop.
Ex1:
no=1
while no<=10:
print(no)
if no==5:
break
no+=1
print("End of while...")
Ex2:
stock=10
x=int(input("How Many Coke Tins you want:"));
c=1
while c<=x:
if c>stock:
print("out of stock..")
break;
Continue:
When you want to skip certain statements of a loop for the current iteration only and
continue execution of the loop with the next iteration, then continue statement is
used.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[64]
Ex:1
Print numbers in between 1 to 10 without multiple of 5 and 10
for i in range(1,10):
if i%5==0 or i%10==0:
continue
print(i)
Ex:2
cart=[12,23,45,100,56,76,35,200]
for i in cart:
if i>=100:
continue
print(i," is processed...")
print("Items processed successfully....")
pass statement:
pass is a null statement. It used to specify when no command or no action is to be
performed.
Ex:
no=int(input("Enter a no:"))
if no>10:
pass
else:
print("Hello....")
print("Thank U!")
Note: pass can be used with functions and classes also to mention that the block does
not contain any code.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[65]
while with else:
✓ We can have optional else block with while loop.
✓ The else part is executed if the condition in the while loop evaluates to false.
✓ The while loop can be terminated with a break statement.
✓ If while loop is terminated with break statement, then else part is ignored.
✓ Hence while loops else part runs if no break occurs and the condition is false.
Ex 1:
count=1
while count<=3:
print(count)
count+=1
else:
print("In else block...")
Ex 2:
count=1
while count<=10:
print(count)
count+=1
if count==5:
break
else: #this else block belongs to while
print("In else block...")
print("End of the Program")
Ex 1:
for i in range(1,11):
print(i)
else: #this else block belongs to for
print("In else block..")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[66]
Ex 2:
for i in range(1,11):
print(i)
if i%5==0:
break
else: #this else block belongs to for
print("In else block..")
print("End of Program")
Ex 3:
***Importance of Indentation:
for i in range(1,11):
print(i)
if i%5==0:
break
else: #this else block belongs to if
print("In else block..")
Ex 4:
for i in range(1,11):
print(i)
if i%5==0:
break
else: #this else block belongs to for
print("In else block..")
print("End of Program")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[67]
Prime No:
The Numbers Which are Divisible by one and itself only are called prime numbers.
Or
Numbers which have only two factors are called prime numbers.
if no==d:
print(no," is prime....")
else:
print(no," is not prime...")
Program to check whether the inputted no is prime or not – using while & else
no=int(input("Enter a no:"))
d=2
while d<no:
if no%d==0:
print("Not Prime...")
break
d=d+1
else:
print("Prime....")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[68]
Program to check whether the inputted no is prime or not – using for each
no=int(input("Enter a no:"))
for d in range(2,no):
if no%d==0:
print(no," is not prime...")
break
else:
print(no," is prime...")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[69]
Nested loops:
Loop within a loop is nested loops.
for i in range(1,4):
for j in range(1,4):
print(F"{i} - {j}")
print("-"*10)
if prime=='y':
print(no,end=" ")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[70]
Working with Patterns:
Ex1:
Output:
*****
*****
*****
*****
*****
Code:
print("* * * * *")
print("* * * * *")
print("* * * * *")
print("* * * * *")
print("* * * * *")
Ex2:
Output:
*****
*****
*****
*****
*****
Code:
for r in range(1,6):
for c in range(1,6):
print("*",end=" ")
print()
Pattern1:
Output:
Enter no of rows:5
*
* *
* * *
* * * *
* * * * *
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[71]
Code:
#Loigc 1:
tar=int(input("Enter How Many Rows:"))
for r in range(1,tar+1):
for c in range(1,tar+1):
if c<=r:
print("*",end=" ")
else:
print(" ", end=" ")
print()
Code:
#Loigc 2:
tar=int(input("Enter How Many Rows:"))
for r in range(1,tar+1):
for c in range(1,r+1):
print("*",end=" ")
print()
for i in range(n+1):
print("* "*i)
Pattern2:
Output:
Enter no of rows:5
1
22
333
4444
55555
Code:
rows=int(input("Enter no of rows:"))
for i in range(1,rows+1):
for j in range(1,i+1):
print(i,end=" ")
print()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[72]
using Multiplication Logic:
rows=int(input("Enter no of rows:"))
for i in range(1,rows+1):
print(str(i)*i)
Pattern3:
Output:
Enter no of rows:5
1
12
123
1234
12345
Code:
rows=int(input("Enter no of rows:"))
for i in range(1,rows+1):
for j in range(1,i+1):
print(j,end=" ")
print()
Pattern 4:
Enter No of Rows:5
*
***
*****
*******
*********
Code:
n=int(input("Enter No of Rows:"))
for r in range(1,n+1):
for c in range(1,(2*n)):
if c>=(n-r)+1 and c<=(n+r)-1:
print("*",end=" ")
else:
print(" ",end=" ")
print()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[73]
Using multiplication Logic:
n=5
for i in range(n):
print(" " * (n-i-1),end=" ")
print("*" * (2*i+1),end=" ")
print(" " * (n-i-1))
Pattern 5:
Enter No of Rows:5
**** ****
*** ***
** **
* *
Code:
n=int(input("Enter No of Rows:"))
for r in range(1,n+1):
for c in range(1,(2*n)):
if c>=(n-r)+1 and c<=(n+r)-1:
print(" ", end=" ")
else:
print("*", end=" ")
print()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[74]
Hands-On-Lab
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[75]
5.String – Data structure
✓ A String is a character array of bytes representing Unicode characters.
✓ Python does not have a character datatype; single character is also represented
as a string with length 1.
✓ The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.
✓ Each character is encoded in the ASCII or Unicode character. So, we can say that
Python strings are also called the collection of Unicode characters.
✓ Python supports str datatype to represent strings.
✓ Insertion order is preserved in string objects.
✓ Python supports both concatenation and multiplication of strings.
✓ Strings can be created by enclosing characters inside a single quote, double
quote, and triple quotes.
✓ Triple quotes are mainly used to represent multiline strings and doc strings.
Quotes in python:
Python accepts single('), double(") and triple (' ' ' or " " ") quotes to denote string
literals, as long as the same type of quote starts and ends the string.
Generally triple quotes are used to write the string across multiple lines.
For example:
gender='Male'
name="Raj Kumar Jain"
str="""This is a multi-line statement.
It is denoted by triple quotes"""
Note: ' ' ' Triple Quotes are Considered as comments if the string is not assigned to any
variable.
Syntax:
1. Creating string with single quotes
str='Coding Career Academy'
2. Creating string with double quotes
str="Coding Career Academy"
3. Creating string with triple Single quotes
str=''' Coding Career Academy '''
4. Creating string with triple Double quotes
str=""" Coding Career Academy """
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[76]
Example:
''' this is a Program to work with string data'''
name="Bhaskar"
gender='Male'
address='''Main Road
Near KLM Shopping Mall
Rajahmundry-533101'''
print(name)
print(gender)
print(address)
print(hobbies)
Ex:
str="this is"+\
" to"+\
" test"+\
" the course"
print(str)
String indexing:
✓ Every character in the string object is represented with unique index.
✓ String supports both forward and backward indexing
✓ Forward index starts with 0 and backward index starts with -1.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[77]
✓ we can access individual characters of a string using indexing and a range of
characters using slicing.
✓ if we try to access a character out of index range then interpreter will raise an
IndexError.
✓ The index must be an integer. If we try to access the data with non-integer
index values, then interpreter raises TypeError.
Indexing:
str="AHCAREER"
Forward index 0 1 2 3 4 5 6 7
A H C A R E E R
backward index -8 -7 -6 -5 -4 -3 -2 -1
Example:
str="AHCAREER"
print("The string is:",str)
print("The string Id is:",id(str))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[78]
print(str[-4])
print(str[-5])
print(str[-6])
print(str[-7])
print(str[-8])
Immutable string:
✓ String objects are immutable, i.e. we cannot modify the existing string contents.
✓ String objects cannot be modified, once modified new object is created in
Memory.
str="Raj"
print(str)
print("id of str is:",id(str))
str="Prem"
print(str)
print("id of str is:",id(str))
Note: Kindly observe the ids of old and new modified string.
str Raj
10980
Prem
78099
0
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[79]
String Slicing:
✓ We can use Slicing to get Part of the String.
✓ We can access range of characters using slicing. The slicing operator is (:)
Forward index 0 1 2 3 4 5 6 7
A H C A R E E R
backward index -8 -7 -6 -5 -4 -3 -2 -1
Syntax:
[starting index: Ending Index:[Step Value]]
Example:
str="AHCAREER"
print(str[2:5])# CAR
print(str[2:]) # CAREER
print(str[0:5:2]) # ACR # 3rd parameter is step
print(str[-8:-3]) # AHCAR
print(str[-8:]) # AHCAREER
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[80]
Few More Examples on Slicing:
Direction: using forward indexing
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[81]
String Methods/Functions:
String Methods are used to perform operations on string object.
2. title() This function converts first character of each word in the given
string into uppercase.
3. swapcase() This function swaps all uppercase letters into lowercase and vice
versa.
9. find() This function finds the index position of the specific character in
the given string.
10. split() This function splits the string into multiple string based on
delimiter.
11. lstrip() This function removes specific characters from leftside of the given
string.
12. rstrip() This function removes specific characters from rightside of the
given string.
13. strip() This function removes specific characters from both of the given
string.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[82]
14. reversed() This function reversed the given string.
15. replace() This function replaces existing character(s) with new character(s).
16 join() The join() string method returns a string by joining all the elements
of an iterable (list, string, tuple), separated by a string separator.
print("capatialize() method:",str.capitalize())
print("title() method:",str.title())
print("upper() method:",str.upper())
print("lower() method:",str.lower())
print("swapcase() method:",str.swapcase())
print("isupper() method:",name.isupper())
print("islower() method:",name.islower())
print("count() method:",str.count("e"))
print("find() method:",str.find("n"))
print("find() method:",str.find("n",10))
print("split() method:",str.split())
print("split() method:",str.split("is"))
name="***Atish***"
print("lstrip() method:",name.lstrip("*"))
print("rstrip() method:",name.rstrip("*"))
print("strip() method:",name.strip("*"))
print("replace() method:",str.replace("Python","Java"))
print("replace() method:",str.replace("to learn",""))
name="Atish"
print("join() method:","*".join(name))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[83]
String packing:
Joining multiple characters into one single string is known as string packing.
Ex:
x="R"
y="a"
z="j"
str="".join([x,y,z])
print(str)
String Unpacking:
✓ String unpacking allows extracting all characters of string into different values
automatically.
✓ The number of variable to assign must be equal to numbers of characters in the
string.
Ex:
str="Raj"
a,b,c=str
print(a)
print(b)
print(c)
del command:
We can delete the entire string object permanently by using del command.
str="Python"
print(type(str))
print(str)
print(id(str))
del str
print(str)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[84]
Displaying all the characters of a string in ascending order:
str="python"
print("".join(sorted(str)))
str="PYthon"
print("".join(sorted(str)))
str="raj"
print("".join(reversed(sorted(str))))
Displaying the given string with two dots between each character.
str="python"
nstr="..".join(str)
print(nstr)
Note:
The newly generated string is assigned to nstr variable.
ch=input("Enter a character:")[0]
Note:
In Python there is no character datatype, so we read string and access the first
character by using its index.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[85]
String Operators:
Sno Description
Operator
1 + Concatenates two strings
2 * It Concatenates Multiple copied of the same string
3 [] String Slicing, used to access sub-string of a particular string
4 [:] Range slice operator, used to access range of characters of a
particular string
5 In String Membership operator, used to check whether a string exists in
a main string or not, return True if exists
6 not in String Membership operator, used to check whether a string exists in
a main string or not, return True if does not exists
7 R/r Raw String
8 % String Formatting Operator
String concatenation:
✓ Combining two or more strings into single string is known as string
concatenation.
✓ + operator is used in python for string concatenation.
Example:
str1="Python "
str2="Programming"
str3=str1+str2
print("str1 id:",id(str1))
print("str2 id:",id(str2))
print("str3 id:",id(str3))
print("str3:",str3)
Note: A new string object is created which stores the resultant string.
String Multiplication:
✓ Python supports string multiplying or string repeating into N times.
✓ * operator is used repeat the string into N number of times.
Example:
str="Raj "
print(str*5)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[86]
Raw String in Python:
✓ Raw String is used when we don’t want Python to treat backslash(\) as as an
escape character.
✓ Raw string is created by prefixing a string literal with ‘r’ or ‘R’. Python raw string
treats backslash (\) as a literal character.
Example:
Print path of my python examples folder
str=r"d:\newlanguage\python"
print(str)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[87]
The format() method
The format() method is the most flexible and useful method in formatting strings. The
curly braces {} are used as the placeholder in the string and replaced by the format()
method argument.
# Positional Argument
print("{1} and {0} best players ".format("ML", "AI"))
# Keyword Argument
print("{a},{b},{c}".format(a="AI", b="ML", c="Deep
Learning"))
rollno=101
name="Raj"
age=19
weight=65.50
print("Hi ! I am %s ... My Rollno is: %d \ni am %d years
old and my Weight is %.2f kgs"%(name,rollno,age,weight))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[88]
Hands-On-Lab
Dear <name>,
You Admission for Python Course is Conformed !
4. Write a Program to Detect double space from the inputted string and print its
index position
5. Program to Replace double space with single space in the inputted string.
6. Program to Print a Leave Letter using escape sequence characters.
7. Write a Program to Reverse the inputted string using for loop
8. Write a Program to Reverse the inputted String using While loop
9. Write a Program to Check whether the inputted string Palindrome or not
without using any loops.
10. Write a Program to Read a String and Display Each Character of the String on
new line using for loop.
11. Write a program to read a string and display its length without using len()
function.
12.Write a Program to count number of uppercase letters, lowercase letters, digits
and special symbols from the inputted email id.
13.Write a Program to read First name and Last name in one variable and then
again read middle name in another variable, now insert middle name in the
middle of the first and last names.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[89]
14.Write a Program to Find the Last Position of the Word “Python” in the given
string.
Python is Very Easy and Powerful Language, Now days Python is Considered as
Beginners Language.
15. Write a Program to Find Length of the inputted string without spaces.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[90]
6.Data structures in Python
✓ A data structure is a particular way of organizing data in a computer so that it
can be used effectively.
✓ Data structures are used to organize, store, access and modify data efficiently.
✓ Earlier, we have seen primitive data types like integers, floats, Booleans, and
strings. Now, we’ll take a deeper look at the non-primitive Python data
structures.
✓ List, Tuple, Set, FrozenSet and Dictionary.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[91]
Creating list using list() function:
Ex 1:
# Creating Empty List using list() Function
x=list()
print("Elements of list x are:",x)
print("Type of List x is:",type(x))
Note:
Empty list object x is created.
Ex2:
# Creating List with elements using list() Function
x=list("Python")
print("Elements of list x are:",x)
print("Type of List x is:",type(x))
Note:
Empty list object a is created.
Ex2:
# Creating List with Numbers
marks=[67,87,67,89,90]
print("Marks are:",marks)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[92]
Creating list using range() function:
We can create list using range() function also.
Syntax:
range(sv,ev,step)
Here sv and step are optional, default sv is 0 and step is 1.
Ex2:
a=list(range(10))
print(a)
Ex3:
a=list(range(5,10))
print(a)
Ex4:
a=list(range(-3,3))
print(a)
Ex5:
a=list(range(0,10,2))
print(a)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[93]
List indexing:
✓ By using list indexing we can fetch specific element from the list.
✓ List supports both forward and backward indexing.
Ex1:
lst=[10,20,30,100,10,"Raj",12.50]
print("Element from index 0:",lst[0])
print("Element from index -1:",lst[-1])
List slicing:
✓ By using slicing we can fetch set of items from the list.
✓ Slicing also supports forward and backward indexing.
✓ Colon(:) is used as slicing operator.
Ex1:
lst=[10,20,30,100,10,"Raj",12.50]
print("Elements from index 2 to 5:",lst[2:5])
print("Elements from index 2 to till end of the
list:",lst[2:])
print("Elements from index 2 to 6 by skipping 1
element:",lst[2:6:2])
print("Elements from -3 to till last:",lst[-3:])
print("Elements from -5 to -2:",lst[-5:-2])
Ex:1
lst=[10,20,100,20]
print("id of the list lst:",id(lst))
print("Elements of the List lst:",lst)
lst.append(200)
print("id of the list lst after adding a new
element:",id(lst))
lst[0]=999
print("id of the list lst after updating one
element:",id(lst))
print("Elements of the List After Updation:",lst)
Note:
Here, the address of list lst is not changed before and after modification, Hence list is
known as mutable object.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[94]
List Concatenation:
Python supports concatenating two or more lists into single list.
Ex:
lst1=[10,20,30,100]
lst2=["Raj","Prem","Hari"]
lst3=lst1+lst2
print("List 1:",lst1)
print("List 2:",lst2)
print("List 3:",lst3)
Ex:
a=[10,20,"Python"]
print("List Multiplication:",a*3)
List functions/methods:
Sno Function/Method Description
1 count() This function counts number of occurrences of specific
element in the list.
2 index() This function find the index value for the specific element.
3 append() This function adds new element at the end of the list.
4 extend() This function adds multiple elements at the end of the list.
5 insert() This function adds any elememnt at the given position in the
list.
6 remove() This function removes specific elements from the existing
list. This function accepts one argument, and this argument
must be the element.
7 pop() This function removes specific elements based on the index
position. This function accept one argument that should be
index number.
Note: pop() with out index removes last element from the
list.
8 reverse() This function reverses the existing list.
9 copy() To Duplicate the existing list.
10 clear() This function clears or removes all the elements from the
list.
11 sort() This function sorts the elements of the list, default sorting
order is ascending.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[95]
Note:
To sort the list in reverse order pass parameter as True for
reverse attribute.
lst.sort(reverse=True)
# List Methods
print(F"The value 100 is available {lst.count(100)} times
in the list")
print(F"The value 100 is available at
index:",lst.index(100))
lst.remove(8888)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[96]
print("List After Removing 8888:",lst)
lst.pop(0)
print("List After pop(0) is:",lst)
lst.reverse()
print("List Elements after reverse() method:",lst)
newlist=lst.copy()
print("New List is:",newlist)
newlist.clear()
print("new List After clear() method:",newlist)
lst=[12,43,67,1,5,678,99]
lst.sort()
print("Elements of List After sort() method-Ascending
order:",lst)
lst.sort(reverse=True)
print("Elements of List After sort() method-Descending
order:",lst)
# function
marks=[45,78,65,89,76]
print("Length of marks list is:",len(marks))
print("Maximum Marks:",max(marks))
print("Minimum Marks:",min(marks))
print("Sum of Marks:",sum(marks))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[97]
Del command:
This command is used to remove specific element/s or entire list permanently.
x=[12,34,6,87,89,76]
print(x)
del x[0]
print(x)
del x[1:3]
print(x)
del x
#print(x) NameError: name 'lst' is not defined
Nested list:
List with in a List is known as Nested list.
lst1=[10,20,30,True,12.50]
lst2=["Raj","Prem"]
lst3=[1,2,3,4,5]
newlist=[lst1,lst2,lst3]
print(newlist)
We can also add multiple elements in the list at the required position using insert()
method, but those multiple elements should be nested list or sub list in the existing
list.
lst=[10, 20, 30, 100]
lst.insert(0,[1,2,3])
print(lst)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[98]
Accessing elements from nested list:
newlist=[[10, 20, 30, True, 12.5], ['Raj', 'Prem'], [1, 2,
3, 4, 5]]
print(newlist[0])
print(newlist[1])
print(newlist[2])
print(newlist[0][1])
print(newlist[1][0])
print(newlist[2][3])
Conversions:
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[99]
List packing:
A list can be created by using group of variables, it is called list packing.
a=10
b=20
c=30
d=True
lst=[a,b,c,d]
print(type(lst))
print(list)
List Unpacking:
✓ List unpacking allows you to extract all the elements automatically into different
variables.
✓ The number of variables must be equal to number of elements in the list.
lst=[10,20,30,True]
p,q,r,s=lst
print(p)
print(q)
print(r)
print(s)
List Comprehension:
List comprehensions are used for creating new lists from other iterables like tuples,
strings, arrays, lists, etc. A list comprehension consists of brackets containing the
expression, which is executed for each element along with the for loop to iterate over
each element.
Syntax:
newList = [ expression(element) for element in oldList if condition ]
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[100]
List Comprehensions vs For Loop:
There are various ways to iterate through a list. However, the most common approach
is to use the for loop. Let us look at the below example:
# Empty list
List = []
# Display list
print(List)
List Comprehension:
List Comprehensions translate the traditional iteration approach using for loop into a
simple formula hence making them easy to use. Below is the approach to iterate
through a list, string, tuple, etc. using list comprehension.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[101]
Tuple Data Structure
✓ Python Tuple is used to store the sequence of immutable Python objects.
✓ The tuple is like lists since the value of the items stored in the list can be
changed, whereas the tuple is immutable, and the value of the items stored in
the tuple cannot be changed.
✓ All elements are separated by commas(,) and enclosed by parenthesis.
parenthesis is optional.
✓ Tuple allows duplicate elements.
✓ Every element in the tuple is accessed using index.
✓ Tuple supports both forward and backward indexing.
✓ If we take only one element in the tuple then we must use comma (,) after the
single element.
✓ We can create tuple in different ways like tuple(), with () or without () also.
✓ Default group data representation is tuple only.
✓ The main difference between list and tuple is
o List is enclosed in brackets ([]), and their elements and size can be
modified.
o Tuple is enclosed in parentheses () and cannot be modified.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[102]
Creating tuple without parenthesis:
t=10,20,30
print("Type of t is:",type(t))
print("Elements of tuple t are:",t)
Note:
Default grouping data structure is tuple.
Note:
If you create tuple with single element, then it is considered as int type. Use comma(,)
after the single element to create tuple with single element.
tp=(10,)
print("Type of t is:",type(tp))
Tuple is immutable:
t=tuple([10,20,30,"Python",True])
#t[0]=999 - Error
Tuple indexing:
✓ Indexing is used to fetch a specific element from the tuple.
✓ Tuple also supports negative index to access elements in backward direction.
Ex:
t=(10,20,30,100,"Python",99,"Raj")
print("First Element of tuple t is:",t[0])
print("Last Element of tuple t is:",t[-1])
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[103]
Tuple slicing:
Using slicing we can fetch group of elements from the tuple.
Ex:
t=(10,20,30,100,"Python",99,"Raj")
print("Elements of Tuple from Index 1 to 5:",t[1:5])
print("Elements of Tuple from Index 4 to end:",t[4:])
print("Elements of Tuple from Index 1 to Index 8 - Step Value 2:",t[1:8:2])
print("Elements of Tuple from Index -5 to -1:",t[-5:-1])
Tuple concatenation:
t1=(10,20,30)
t2=("Raj","Prem","Kushi")
t3=t1+t2
print("Concatenation of t1 and t2 are:",t3)
Tuple functions/methods:
Sno Function/Method Description
1 count() This function counts number of occurrences of a specific
element.
2 index() This function is used to find the index value of a specific
element.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[104]
Functions which can be used on Tuple:
Sno Function Description
1 all() This function returns true if all elements are true(non-zero), if any
element is false(zero) then it will return false. For empty tuple it will
return True.
2 any() This function returns True if atleast one element is True.
3 len() This function returns number of elements in the tuple.
4 sum() This function returns sum of all the elements.
5 max() This function returns maximum value from the tuple elements.
6 min() This function returns minimum value from the tuple elements.
7 sorted() This function sorts the tuple elements. Default sorting order is
ascending.
Note: to sort the elements in descending order set the reverse
attribute to True.
sorted(t,reverse=True)
t = (1, 2, 3,0)
print("any() function when elements are non zero:",any(t))
t = (0,0,0,0)
print("any() function when an element is 0:",any(t))
t=(13,6,54,78,99,34,999)
print("Maximum Element of the Tuple is:",max(t))
print("Minimum Element of the Tuple is:",min(t))
print("Sum of Tuple Elements is:",sum(t))
t=(13,6,54,78,99,34,999)
t=tuple(reversed(t))
print("Tuple Elements in Reverse Order:",t)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[105]
del command:
we cannot delete individual elements of tuple because tuple is immutable, but we can
delete the entire tuple.
t=(1,100,0,True,1,"Raj")
print(t)
del t
#print(t) #error
t=(10,20,100,999,25)
t=reversed(t)
print(tuple(t))
Nested Tuple:
✓ Pyton supports nested tuple ie a tuple with in a tuple.
✓ Tuple allows list as its elements.
t1=(1,2,3)
t2=("Raj","Prem")
t3=(t1,100,200,t2)
print(t3)
print(t3[0])
print(t3[1])
print(t3[2])
print(t3[3])
print(t3[3][1])
print(t3[1:])
Tuple updating:
We cannot modify elements of tuple because tuple is immutable, but if tuple contains
list, then it can be modified.
tup=(1,2,3,[100,200,200],"Raj",True)
tup[3][0]=999
print(tup)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[106]
Conversions:
Converting tuple to list:
tup=(1,2,3,True,100,"Raj")
lst=list(tup)
print(lst)
print(type(lst))
Tuple packing:
✓ Creating tuple using existing individual variables is known as tupel packing.
a=100
b="Raj"
c=True
d=999
tup=(a,b,c,d)
print(tup)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[107]
Tuple Un packing:
✓ Extracting tuple elements and assigning to individual variables is known as tuple
unpacking.
✓ Number of variables should must be same as number of elements in the tuple.
tup=(10,20,30)
a,b,c=tup
print(a)
print(b)
print(c)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[108]
Set Data Structure
✓ A set is an unsorted collection of unique elements.
✓ Inserted order is not preserved but elements can be sorted.
✓ Set does not allow duplicate elements.
✓ Set is commonly used in membership testing, removing duplicates from
sequence, and computing mathematical operations such as intersection, union,
difference, and symmetric difference.
✓ The main advantage of using set against list is, set has highly optimized method
for checking whether a specific element is present in the set or not.
✓ Set doesnot support indexing and slicing.
✓ Set doesnot support concatenation and multiplication.
✓ There are two types of sets
o set
o frozenset
set:
The set type is mutable- the contents can be added or removed using methods like
add() and remove(). Set is mutable so it cannot be used as either a dictionary key or as
an element of another set.
frozenset:
The forzenset is immutable. Its contents cannot be altered once it is created, it can be
used as a dictionary key or as a element of another set.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[109]
3. Creating set() with curly braces( {} ).
s={12,34,56,False,"AHCAREER"}
print(type(s))
print(s)
Ex:
s={12,34,100,"AHCAREER",100,"Raj"}
print(12 in s)
print("Raj" in s)
print(120 in s)
print("Python" in s)
print(990 not in s)
print("Prem" not in s)
print(12 not in s)
print("Raj" not in s)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[110]
Operations on Sets:
In mathematics, a set is a collection of distinct objects, considered as an object. For
example, the numbers 2, 4, and 6 are distinct objects when considered separately, but
when they are considered collectively, they form a single set of size three, written
{2,4,6}.
In python, compared to list, the main advantage of using a set is that it has optimized
functions for checking whether a specific element is a member of the set or not. This is
based on a hash table data structure.
Operations on Sets
Operation Notation Meaning
Intersection A∩B all elements which are in both and
Union A∪B all elements which are in either or (or both)
Difference A−B all elements which are in but not in
Complement (or) all elements which are not in
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[111]
Other Set Functions/Methods of Set:
Sno Function Description
1 add() This function adds new elements to the
existing set.
2 remove() This function removes elements from the set.
Note:
If the element is not found in the set, then
python intrepreter will throw an error.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[112]
13 difference_update() This function will update the first set with the
result of difference between first set and
second set.
Ex 1:
s={12,34,"Raj",100,True,"Prem",99}
print(s)
s.add(100)
s.add(12.50)
print(s)
s.remove(100)
print(s)
# s.remove(555) - error because element not found
s.discard(555) # No error though element is not found
s.clear()
print(s)
Ex 2:
s1=set()
s2=set()
print(s1.isdisjoint(s2))
s1=set()
s2={1,2,3}
print(s1.isdisjoint(s2))
s1={1,2,3,4}
s2={1,2,3}
print(s1.isdisjoint(s2))
s1={1,2,3}
s2={1,2,3,4,5}
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[113]
print(s1.issubset(s2))
print(s2.issubset(s1))
print(s1<=s2)
print(s2<=s1)
print(s1.issuperset(s2))
print(s2.issuperset(s1))
print(s1>=s2)
print(s2>=s1)
s1={10,20,1,2,10,50}
s2={1,2,3,10}
print("s1 union s2:",s1.union(s2))
print("s1 | s2:",s1|s2)
s1={10,20,1,2,10,50}
s2={1,2,3,10}
s1={1,2,3,4,5}
s2={1,2,3,6,7}
print("symmetric difference:",s1.symmetric_difference(s2))
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s1.intersection_update(s2)
print("s1 intersection update:",s1)
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s1.difference_update(s2)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[114]
print("Difference update:",s1)
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s1.symmetric_difference_update(s2)
print("symmetric difference update:",s1)
s1=set([1,2,3])
s2=set([4,5,6])
s1=set([1,2,4])
s2=set([4,5,6])
s1=set([1,2,3,4,5,6])
s2=set([4,5,6])
print("s1 is subject of s2:",s1.issuperset(s2))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[115]
frozenset:
frozenset is same as set, but frozenset is immutable.
Ex:
fs=frozenset({10,20,30,100})
print(fs)
print(type(fs))
#fs.add(999) #error
Nested Sets:
✓ Sets can't have mutable (changeable) elements/members. A list, being mutable,
cannot be a member of a set.
✓ As sets are mutable, you cannot have a set of sets! You can have a set of
frozensets though.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[116]
Dictionary Data Structure
✓ Dictionary is an unordered set of keys: value pairs, here keys are unique.
✓ In dictionary keys are immutable and values mutable.
✓ Keys cannot be duplicated; values can be duplicated.
✓ A pair of braces ( { } ) creates an empty dictionary.
✓ Dictionary will not allow indexing and slicing.
✓ Insertion order is not preserved.
✓ The main operation on dictionary is storing a value with some key and
extracting the value using the key.
✓ Both key and values can be homogeneous and heterogeneous.
✓ Dictionaries are indexed by keys, which can be any immutable string type and
numbers can always be keys.
✓ Tuples can be used as keys if they contain only strings, numbers, or tuples.
✓ If a tuple contains any mutable object(ex: list) either directly or indirectly it
cannot be used as a key.
✓ Lists cannot be used as keys, since lists can be modified using index
assignments, slice assignments, or methods like append(), and extend().
✓ list object can also be used as keys, only if the elements are unique.
✓ Tuples can be used as keys to dictionary as tuple is immutable.
d={}
print(type(d))
d["a"]=10
d["b"]=20
d["c"]=30
print(d)
d1=dict({"Raj":99,"Prem":98,"Kushi":88})
print(d1)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[117]
3. Creating dictionary with curlybraces( {} ) with key:value pairs.
print(studentDetails["Name"])
print(studentDetails["Age"])
Ex2:
studentDetails={"id":101,"Name":"Raj","Subjects":["C","CPP
","Java"]}
print(studentDetails)
print(studentDetails["Subjects"])
#print(studentDetails["Key"]) - error
Note:
If you’re trying to access a key and if it is not available, then interpreter throws error.
We can use membership operator to check whether a key is available or not.
studentDetails={"id":101,"Name":"Raj","Subjects":["C","CPP
","Java"]}
print("age" in studentDetails)
studentDetails={"id":101,"Name":"Raj","Subjects":["C","CPP
","Java"]}
studentDetails["Age"]=15
print(studentDetails)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[118]
Deleting key:value pairs from dictionary:
studentDetails={"id":101,"Name":"Raj","Subjects":["C","CPP
","Java"]}
print(studentDetails.pop("id"))
If we need to delete all key:value pairs from then we can use, clear() function:
studentDetails={"id":101,"Name":"Raj","Subjects":["C","CPP
","Java"]}
studentDetails.clear()
print(studentDetails)
len() function:
This function counts no of pairs in the dictionary.
sd={'id': 101, 'Name': 'Raj', 'Age': 12, 'Marks': 99}
print(len(sd))
Dictionary Functions/Methods:
Sno Function Description
1 keys() It will return all keys from the dictionary.
2 values() it will return all values from the list.
3 copy() To duplicate a dictionary
4 pop() It removes specific key:value pair.
5 clear() It removes all key:value pairs from dictionary
6 fromkeys() We can use tuple elements as keys int the dictionary, where the
elements of the tuple must be unique.
By default values are None, to get the values as zero use the
following.
7 get() This function is used to get the value of the specified key.
8 items() This function is used to get all items ie all key:value pairs.
9 update() One dictionary will be updated with the another one.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[119]
Example:
sd={"id":101,"Name":"Raj","Age":12,"Marks":99}
print("Keys:",sd.keys())
print("Values:",sd.values())
print("Key and Values:",sd.items())
newsd=sd.copy()
print("Copied Dictionary:",newsd)
print("pop() Age:",sd.pop("Age"))
sd.clear()
print("After clear() Function:",sd)
tup=(1,2,3,4,5)
d1={}
d1=d1.fromkeys(tup)
print("Using fromkeys() function:",d1)
d1=d1.fromkeys(tup,0)
print("using fromkeys() function with default value:",d1)
print("Value of id:",sd.get("id"))
print("value of items:",sd.items())
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[120]
Performing Arithmetic operations on the values of a dictionary:
marks={"C":99,"CPP":98,"Java":95}
tot=sum(marks.values())
print(tot)
print(max(marks.values()))
print(min(marks.values()))
namedict={
"Adarsh" :"The one who has Principles",
"Aarav": "Represents Calm & Peaceful",
"Prem": "Symbol of Love & Affection"
}
a=input("Enter a Name:")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[121]
Hands - On - Lab
1. Write a Program to Store names of 5 friends in a list enter by the user.
2. Write a Program to Accept Marks of 5 subjects and display them in sorted order,
Print Sum, Maximim and Minimum Marks.
3. Write a Program to read a word and convert it into list and display using slicing.
4. Write a Program to Read Marks of N Subjects in a list, and display the maximum
and minimum marks without using max and min methods.
5. Write a Program to read N Hetrogeneious elements and Check whether the list
is empty or not, if the list is empty display message –“List is Empty” if list is not
empty then display the list of items.
6. Write a Program to Create Tuple with 1 element using parenthesis ().
7. Write a Program read 5 Fruits in tuple and replace with Fruit name with fruit
name and juice ex:
a. Apple → Apple Juice
8. Write a Python program to check whether an element exists within a tuple, if
exists then print how times it exists.
9. Write a Program to Create a Tuple with Employee information(Employee no,
Name, Salary) and assign it to the respective individual variables(Tuple
Unpacking).
10.Write a Program to Create Tuple with 10 Random Numbers in between 1 to 10,
read one element and check how many times the element appears.
11.Write a Python program to remove Last Element from a tuple.
12.Write a Python program to remove all empty tuple(s) from a list of tuples.
a. L = [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), (),('d')]
13.Write a Program to Create a Dictionary of Input-output Devices with their
usage. Provide user with an option to look it up.
ex: Keyboard – Its an input Device
14.Write a Program to input 10 numbers from the user and display all the unique
numbers in ascending and descending order
15.Create a set with 100 as int and 100 as string.
16.Create an empty set using curly braces.
17.Program read names of 5 students and their Favorite Programming Language
and Store in a Dictionary.
18.If keys of a dictionary (names of two persons) are same, What will Happen, try
with the previous program (ie Program no 17)
19.If values of a dictionary (Languages of two persons) are same, what will happen,
try with the previous program (ie Program no 17)
20.Create a tuple without using tuple() function and parenthesis.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[122]
21.Create one tuple and one list to store names and ages of 3 students without
using tuple() or list() functions.
22.Create a tuple with 10 Items and display fist and last elements.
Note: Don’t use backward indexing.
23.Write a Program to read Subject in list and their marks in tuple, if the student
gets 0 in any of the subject then display in which subject he got zeros.
24.Write a Program to demonstrate difference between remove() and discard()
method of a set.
25.Write a Program to store name and price of the products and display total of all
the products.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[123]
7.Arrays In Python
✓ Array is a variable which holds group of homogenous elements as one unit.
✓ In array all the elements are stored in continuous memory locations.
✓ Elements of array are accessed using its index no.
✓ Array index starts with 0 and ends with array size-1.
✓ Python array can be grown and shrink.
✓ Arrays Supports forward and Backward indexing
✓ Arrays Supports Slicing Operations too.
✓ In Python array functions are available in a module called array.
Note: Difference between List and Array is in Array all the elements are homogenous
and in Lists elements can be homogeneous and heterogenous.
Ex:
To read Mobile numbers strictly – Arrays
To read personal identity no(Aadhar no, Panno, PassPort no, Driving Licence) – Lists
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[124]
TypeCode C Type Python Type Minimum size in bytes
'b' signed char int 1
'B' unsigned char int 1
'u' Py_Unicode Unicode Character 2
'h' Signed short int 2
'H' Unsigned short Int 2
'i' Signed int Int 2
'I' Unsigned int Int 2
'l' Signed long Int 4
'L' Unsigned long Int 4
'f' Float float 4
'd' Double float 8
Example:
Array Operations:
Here are the Basic Operations on arrays.
1. Traverse – Accessing Elements one by one using its index
2. Search – Locating for an Element
3. Insertion – Adding an Element at Given Index
4. Update – Modifying an Element at Given Index
5. Deletion – Deleting an Element from a Given Index
Array Methods:
Some Built-in Array Methods that we can use on Arrays and Lists.
Sno Method Description
1 buffer_info() it will return array address and array size
2 append() Adds an Element at the End of the Array
3 remove() Removes the First Item with the Specified value
4 sort() Sorts the Arrays Elements.
5 ….. ……
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[125]
Ex1:
import array as arr
marks=arr.array('i',[12,3,54,67,54])
print(marks.buffer_info())
print(marks)
print(marks[0])
for i in range(0,5):
print(marks[i])
Ex2:
import array as arr
marks=arr.array('i',[12,3,54,67,54])
for i in range(len(marks)):
print(marks[i])
for i in marks:
print(i)
for v in vowels:
print(v)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[126]
User Input in Arrays:
from array import *
arr=array('i',[])
size=int(input("How many values you want to read:"))
for i in range(size):
x=int(input("Enter ur next value no:"))
arr.append(x)
print(arr)
for i in range(size):
x=int(input("Enter ur next value no:"))
arr.append(x)
print(arr)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[127]
Searching for an element in the array – Using Array Functions:
for i in range(size):
x=int(input("Enter ur next value no:"))
arr.append(x)
print(arr)
if key in arr:
print(key," is found at",arr.index(key))
else:
print(key," Not Found...")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[128]
NumPy
Introduction:
✓ NumPy stands for Numerical Python.
✓ NumPy is an Open-source library for the Python programming language,
Provides support for large, multi-dimensional arrays and matrices, along with a
large collection of high-level mathematical functions to operate on these arrays.
✓ It is an extension module of Python which is mostly written in C. It provides
various functions which can perform the numerical computations with a high
speed.
✓ NumPy Was Created by Travis Oliphant in 2005
There are the following advantages of using NumPy for data analysis.
✓ NumPy performs array-oriented computing.
✓ It is Faster than Python List
✓ It efficiently implements the multidimensional arrays.
✓ It performs scientific computations.
✓ It can perform Fourier Transform and reshaping the data stored in
multidimensional arrays.
✓ NumPy provides the in-built functions for linear algebra and random number
generation.
✓ Nowadays, NumPy in combination with SciPy and Mat-plotlib is used as the
replacement to MATLAB as Python is more complete and easier programming
language than MATLAB.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[129]
Goto IDLE:
>>> from numpy import *
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from numpy import *
ModuleNotFoundError: No module named 'numpy'
Note:
✓ By default, numpy package is not available in python.
✓ The Above error message indicates that numpy package is not installed.
What is PIP?
PIP is a package manager for Python packages, or modules.
Note: if you’re not getting any error message at IDEL Python Prompt, it means numpy
is successfully installed.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[130]
Installing NumPy in PyCharm IDE:
File → Settings
Project: <Project name>
Python Interpreter
There are many functions which are used to create arrays in NumPy
1. array()
2. zeros()
3. ones()
4. randint()
5. linspace()
6. logspace()
7. arange()
The NumPy's array class is known as ndarray or alias array. The numpy.array is not
the same as the standard Python library class array.array. The array.array handles
only one-dimensional arrays and provides less functionality.
arr2=array([10,20,30,40,50],int)
print(arr2)
Note: NumPy array() function takes list of elements as arguments.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[131]
Creating Array from a List:
Ex 1:
import numpy
mylist=[10,20,30]
arr=numpy.array(mylist)
Ex 2:
import numpy
mylist=[[10,20],[30,40]]
arr=numpy.array(mylist)
Ex 1:
import numpy
mylist=[10,20,30,40,50]
arr=numpy.array(mylist)
print(arr)
print("Size:",arr.size)
print("Datatype:",arr.dtype)
print("Dimenion:",arr.ndim)
print("Shape:",arr.shape)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[132]
Ex 2:
import numpy
mylist=[[10,20,30],[40,50,60]]
arr=numpy.array(mylist)
print(arr)
print("Size:",arr.size)
print("Datatype:",arr.dtype)
print("Dimenion:",arr.ndim)
print("Shape:",arr.shape)
Note: In the Above code one element is of type float, so automatically all the
elements are converted to float type.
Note: The above array contains float value(2.5) and datatype is mentioned as int so
all elements will be converted into int type.
Ex 1:
import numpy
list1=[1,2,3,4,5,6,7,8,9]
arr1=numpy.array(list1)
print(arr1)
arr2=arr1[1:5]
print(arr2)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[133]
Ex 2:
Extracting sub matrix from matrix
Syntax:
# [row_lwr:row:upp. col_lwr:col_upr]
import numpy
list1=[[1,2,3],[4,5,6],[7,8,9]]
matrix1=numpy.array(list1)
print("Actual Matrix:")
print(matrix1)
print("Sub Matrix:")
matrix2=matrix1[0:2,0:3]
print(matrix2)
Interview Question:
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[134]
Creating array using ndarray class:
Ex 1:
from numpy import *
n=int(input("Enter size of the array:"))
arr=ndarray(shape=n,dtype=int)
print("Array Elements:",arr)
Ex 2:
While using ndarray, if we do not mention the datatype, then by default it is taken as
float type.
from numpy import *
n=int(input("Enter size of the array:"))
arr=ndarray(shape=n)
print("Array Elements:",arr)
Ex 3:
Creating double dimensional array using ndarray() function.
from numpy import *
arr=ndarray(shape=(r,c),dtype=int)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[135]
for i in range(r):
for j in range(c):
arr[i][j]=int(input())
print("Matrix is:")
print(arr)
NumPy vs List:
Why should we use NumPy when we have Lists?
Here are the Advantages of NumPy Over List.
1. Less Memory
2. Speed
3. Convenient
Array Functions:
Here is the list of few functions on arrays.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[136]
Working with Indexing and Slicing:
Ex 1: Program to Read Array of N Elements and Print their Sum
import numpy as np
a=[] #Creating Empty List
for i in range(size):
a.append(int(input(F"Enter a no at index {i}:")))
for i in range(arr.size):
print(F"Element at index {i} is {arr[i]}")
sum=0
for i in range(arr.size):
sum=sum+arr[i]
Ex 2: Program to Read Array of N Elements and print second half of the array
import numpy as np
a=[] #Creating Empty List
arr=np.array(a)
for i in range(arr.size):
print(F"Element at index {i} is {arr[i]}")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[137]
NumPy Functions to create arrays:
Creating an Array with zeros() function:
✓ This function creates an array (one dimension or multi dimension) and fills all
the values with zeros.
✓ If we do not specify datatype at the time of creating array then by default all the
elements of the array are considered as float type.
✓ Multidimensional size must be given as tuple type ex: (row,col)
arr2=np.zeros((3,3))
print(“\n3*3 Array:”)
print(arr2)
arr2=np.zeros((3,3),int)
print(“\n3*3 Array:”)
print(arr2)
arr1=np.ones(5)
print(“1d Array:”)
print(arr1)
arr2=np.ones((3,3))
print(“\n3*3 Array:”)
print(arr2)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[138]
Creating an Array with eye() function:
✓ This Function creates an array with all the diagonal elements as 1 and rest as 0
in a square matrix.
✓ In a non-square matrix, the values are 1 till the diagonal shape and rest are 0’s
Ex 1:
import numpy as np
arr2=np.eye(3,4)
print("\n3*4 Array:")
print(arr2)
Output:
5*5 Array:
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
3*4 Array:
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[139]
Ex 2: eye() function with datatype int.
from numpy import *
arr1=eye(5,5,dtype=int)
print(arr1)
output:
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]]
✓ This function creates a two-dimensional array with all the diagonal elements as
given by the user and rest of the elements as 0.
✓ Diagonal elements are passed as list or tuple
Ex 1:
import numpy as np
arr1=np.diag([1,3,5,7])
print("4*4 Array:")
print(arr1)
output:
4*4 Array:
[[1 0 0 0]
[0 3 0 0]
[0 0 5 0]
[0 0 0 7]]
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[140]
Ex 2: Using diag() function we can print diagonal elements of an existing array.
import numpy as np
arr1=np.array( [[10,20,30],[40,50,60],[70,80,90]])
print(arr1)
print("\nDiagonal Elements of the above array:")
print(np.diag(arr1))
arr=np.random.rand(10)
print(arr)
arr=np.random.rand(3,3)
print()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[141]
seed() function:
seed() function is used to initialize the random number generator, once random
number generator is initialized then we can generate same set of random numbers.
Ex:
import numpy as np
np.random.seed(10)
arr=np.random.randint(10,20,5)
print(arr)
Note: Same Random Numbers will be generated based on the seed value.
import numpy as np
arr=arr.reshape(4,3)
print("Array Shape:",arr.shape)
print("Dimension:",arr.ndim)
arr=arr.reshape(6,2)
print("Array Shape:",arr.shape)
print("Dimension:",arr.ndim)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[142]
flatten() function:
This function converts multi dimension array to single dimension array.
output:
[1 2 3 4 5 6 7 8 9]
[[1 2 3]
[4 5 6]
[7 8 9]]
print(arr1)
output:
[1. 2. 3. 4. 5.]
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[143]
Ex: Create an array of 5 elements with values between 10 and 20
from numpy import *
arr1=linspace(10,20,5)
print(arr1)
Note: if 3rd parameter is not mentioned, then it will display 50 elements by default.
Ex:
from numpy import *
arr1=linspace(1,50,num=5,endpoint=False,retstep=True)
print(arr1)
Note:
num – number of elements required in the array
endpoint=False – It will exclude last number
retstep=True – To check difference between all the elements
arange():
arange() method returns the ndarray object containing evenly spaced values within
the given range.
Ex:
from numpy import *
arr1=arange(1,10,2)
print(arr1)
output:
[1 3 5 7 9]
logspace():
Return numbers spaced evenly on a log scale
from numpy import *
arr1=logspace(1,10,5)
print(arr1)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[144]
Array Operations:
We can Perform different types of operations on numpy arrays.
arr3=arr1+arr2
print("Addition of two arrays:",arr3)
arr3=arr1-arr2
print("Subtraction of two arrays:",arr3)
arr3=arr1*arr2
print("Multiplication of two arrays:",arr3)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[145]
Matrix:
✓ A matrix is a rectangular 2-dimensional array which stores the data in rows and
columns.
✓ The matrix can store any data type such as number, strings, expressions, etc.
The data is arranged in horizontal called rows, and vertical arrangements are
columns. The number of elements inside a matrix is (R) X (C), where R is rows
and C, columns.
✓ In python Matrix is implemented using Nested list, NumPy Arrays and Matrix
class.
✓ We can perform operations on matrix like addition, multiplication etc.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[146]
Array Operations on Matrix array(created using numpy array)
from numpy import *
a=array([[1,2,3],[4,5,6],[7,8,9]])
b=array([[2,1,2],[3,2,3],[1,5,1]])
c=a+b
print("Addition:\n",c)
c=a*b
print("Multiplication:\n",c)
c=a.dot(b)
print("Matrix Multiplication:\n",c)
c=a+b
print("Addition:\n",c)
c=a*b
print("Multiplication:\n",c)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[147]
Copying in Python:
When we use = operator to create a copy of an object, it creates a new variable that
shares the same reference of the original object.so to create a new copy of an existing
object we can use shallow copy or deep copy.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[148]
Deep copy Example:
from numpy import *
arr1=array([1,2,3,4,5])
arr2=arr1.copy()
arr1[1]=999
print(arr1)
print(arr2)
print(id(arr1))
print(id(arr2))
newarr=arr[1:3]
print("slilced array:",newarr)
newarr[:]=0 #changes are reflected in the original array
print("Orginal array:",arr)
newarr=arr[1:3].copy()
print("slilced array:",newarr)
newarr[:]=0 #changes are reflected in the original array
print("Orginal array:",arr)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[149]
Conditional Selection:
✓ when we apply any comparison operator to Numpy Array, then it will be applied
to each element in the array and a new bool Numpy Array will be created with
values True or False.
✓ if we pass this bool Numpy Array to subscript operator [] of original array then it
will return a new Numpy Array containing elements from Original array for
which there was True in bool Numpy Array.
Ex: Create an array with 10 ranom numbers between 1 and 20 and extract all the
numbers which are greater than 10
import numpy as np
arr=np.random.randint(1,20,10)
print(arr)
boolarr=arr>10
print(boolarr)
print(arr[boolarr])
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[150]
Hands-On-Lab
Python Array:
1. Write Program to Create an Array on 5 Elements and Display them in reverse
order using for loop.
2. Write a Program to Create Array of N elements and Perform Insertion,
Updation, Deletion and Search Operations.
3. Write a Program to read an Array of N elements and display the duplicate
elements only once.
Numpy:
4. Write a Program to Create an Array of N Elements and divide it into two parts
and display separately.
5. Write a Program to Create an array of 10 random numbers between 1 and 100
and display all the multiples of 10 using conditional Selection.
6. Write a Program to Create 2d array of 3*4 size using random numbers between
1 to 20.
7. Create an array of 10 integers using numpy and display in reverse order.
8. Create an array which contains the value 5, 10 times
9. Create an array of N Random integers between 50 and 100
10. Create an array of 12 elements and conert it into 4*3 matrix
11. Create an array of 10 elements, fill it with random numbers between 1 to 100
and replace all the even numbers with 0.
12. Create an array of 3*3 matrix, fill the elements with between 1 and 0.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[151]
8.Python functions
✓ Complex projects are divided into smaller individual modules and each module
is known as function.
✓ Function is a group of related statements that perform a specific task.
✓ Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
✓ Functions avoids code repetition, provide better modularity for our application
and a high degree of code reusing.
Library functions:
The functions which come along with language are known as library functions
print(), type(), len() etc..
Syntax:
Function definition:
def function_name(parameter(s)):
statement(s)
function call:
function_name(parameter(s))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[152]
Simple to SayHello()
def SayHello():
print("Hello Whatsup...")
SayHello()
SayHello("Raj")
SayHello("Prem")
print(F"Biggest no is : {max(234,999)}")
a=10
update(a)
print("a=",a)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[153]
Updating list elements using functions:
def update(x):
x[0]=999
print("id of x:",id(x))
print("list of items of x:",x)
lst=[10,20,30]
print("Id of list before update function call:",id(lst))
print("list of items before update function call:",lst)
update(lst)
print("List of items after update function call:",lst)
def result(c,java,python):
tot=c+java+python
avg=tot/3
return tot,avg
If no value is passed at the time of function call, the default value is taken.
Ex1:
def display_message(count,msg):
for i in range(count):
print(msg)
display_message(5,"Pyhton")
print("-----------------")
# display_message() # error
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[154]
Ex 2:
def display_message(count=3,msg=”Hello”):
for I in range(count):
print(msg)
display_message(5,”Pyhton”)
print(“-----------------")
display_message(3)
print(“-----------------")
display_message()
Ex 3:
def message(str="C Language",count=3):
for i in range(count):
print(str)
message("Hello",5)
message("Python",3)
message("Atish")
message()
we can set some default values to formal parameters in the function definition. Those
are called default arguments, if we don’t pass actual parameters in the function call
then interpreter takes formal parameters default values and continues operation.
Generally the first actual parameter will map to the first formal parameter and second
actual parameter will map to the second formal parameter so on…..
def display_message(count=3,msg="Hello"):
for i in range(count):
print(msg)
display_message("Hi..")
Note:
In the above example "Hi" is passed to function call, it will be mapped to first
parameter count, so this code will throw error.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[155]
Keyword argument:
Python allows functions to be called using keyword arguments. A keyword argument
in a function call identifies the argument by a formal parameter name.
Ex:
def display_message(count=3,msg="Hello"):
for i in range(count):
print(msg)
display_message(msg="Hi..")
display_message(5)
display_message(msg="Pyhton",count=2)
Ex:
def student(name,avg):
print(name)
print(avg)
student(avg=90,name="Raj")
def count(lst):
even=0
odd=0
for i in lst:
if i%2==0:
even=even+1
else:
odd=odd+1
return even,odd
lst=[11,23,43,12,11,23,345,756,76,654]
ec,oc=count(lst)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[156]
Fibonacci Series:
Fibonacci numbers are used to create technical indicators using a mathematical
sequence developed by the Italian mathematician, commonly referred to as
"Fibonacci," in the 13th century. The sequence of numbers, starting with zero and
one, is created by adding the previous two numbers.
Ex:
0 1 1 2 3 5 8 13 21……100
Ex:
def fibonacci(n):
a=1
b=0
for i in range(1,n+1):
c=a+b
print(c,end=" ")
a=b;
b=c
x=int(input("Enter a no:"))
res=fact(x)
print("Factorial of {} is {}".format(x,res))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[157]
What is Recursion?
When a function calls itself, then its known as recursion.
Ex 1:
def display(x):
if x>10:
return
else:
print(x,end=" ")
x = x + 1
display(x)
display(1)
Ex 2:
def sayHello():
print("Heyyy WhatsUp")
sayHello()
sayHello()
Error:
……………………..
Heyyy WhatsUp
Heyyy WhatsUp
Traceback (most recent call last):
File "D:/atish/python/myfirstproject/venv/first.py", line 5, in <module>
sayHello()
File "D:/atish/python/myfirstproject/venv/first.py", line 3, in sayHello
sayHello()
File "D:/atish/python/myfirstproject/venv/first.py", line 3, in sayHello
sayHello()
File "D:/atish/python/myfirstproject/venv/first.py", line 3, in sayHello
sayHello()
[Previous line repeated 993 more times]
File "D:/atish/python/myfirstproject/venv/first.py", line 2, in sayHello
print("Heyyy WhatsUp")
RecursionError: maximum recursion depth exceeded while calling a Python object
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[158]
Modified Code:
import sys
sys.setrecursionlimit(2000)
c=1
def sayHello():
global c # accesses the globally declared variable c
print(c,"Heyyy WhatsUp")
c=c+1
sayHello()
sayHello()
def fact(n):
f=1
if n<=1:
return 1;
else:
f=n*fact(n-1)
return f
no=int(input("Enter a no:"))
print("Factorial of 5 is:",fact(no))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[159]
Scope of the variables:
Scope of the variable defines, that at which part of the program they are accessed.
There are two types of scopes
1. Local variables
2. Global variables
Variables which are declared outside the function are called global variables and
variables which are declared with in a function are called local variables.
Ex:
gvar=10
def display():
lvar=20
print("Local variable:",lvar)
print("Global variable:",gvar)
display()
#print("Local variable:",lvar) # error
Ex2:
#Global varaibles
x=5
y=3
def add():
res=0 # Local variable
res=x+y
return res
def sub():
res=0 # Local variable
res=x-y
return res
print("Addition:",add())
print("Subtraction:",sub())
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[160]
Declaring global and local variable with the same name:
Ex:
a=10
def display():
a=100
print("a inside fun:",a)
display()
print("a outside fun:",a)
Note: In the Above code variable a outside the function is global and variable a inside
the function is local.
Ex:
a=10
def display():
global a
a=100
print("a inside fun:",a)
display()
print("a outside fun:",a)
Note: When we declare a variable using global keyword we canot declare local
variable with the same name as global variable.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[161]
Working with globals() function:
globals() functions returns all the global variables.
x=globals() – fetches all global variables
x=globals()[‘variable name’] – fetches specified variable
Ex:
a=10
def display():
a=999
x=globals()['a']
print("Global a:",x)
print("Local a:",a)
print(id(x))
globals()['a']=555
x = globals()['a']
print("Global a:", x)
display()
pos=-1
def search(list,key):
i=0
while(i<len(list)):
if list[i]==key:
globals()['pos']=i
return True
i=i+1
return False
list =[12,34,5,76,78,99,89]
key=199
if search(list,key):
print(key," is found at ",pos)
else:
print(key," is not found")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[162]
Binary Search using Functions:
pos=-1
def search(list,key):
l=0
u=len(list)-1
while(l<u):
m=(l+u)//2
if list[m]==key:
globals()['pos']=m
return True
else:
if key>list[m]:
l=m+1
else:
if key<list[m]:
u=m-1
return False
list =[12,34,5,76,78,99,89]
key=990
if search(list,key):
print(key," is found at ",pos)
else:
print(key," is not found")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[163]
Variable length arguments:
When we define a function to accept N parameters, then for that function we must
pass N parameters only. I.e., total number of Actual parameters should be equal to
total number formal parameters.
We use *args and **kwargs as an argument when we are unsure about the number of
arguments to pass in the functions.
Ex1:
Working with non-keyword arguments: using *args
def display(x,*arg):
print("Formal argument is:",x)
for i in arg:
print("The non-keyword argument is:",i)
return
display(101,"Raj",99)
Ex2:
def addnos(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:", sum)
addnos(3, 5)
addnos(4, 5, 6, 7)
addnos(1, 2, 3, 5, 6)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[164]
Ex3:
def display(a,*x):
print(type(x))
print("Formal arguemnt is:",a)
for i in x:
print("The non-keyword argument is:",i)
return
t1=(101,"Prem",99)
display(99,*t1)
Ex1:
def student(name,**data):
print(name)
print(data)
student("Raj",avg=90,mobileno=9123454321)
(or)
Displaying data using for loop
def student(name,**data):
print(name)
for i,j in data.items():
print(i,j)
student("Raj",avg=90,mobileno=9123454321)
Ex2:
def intro(**data):
print("\nData type of argument:",type(data))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[165]
using * and ** in one function:
def sample(*args, **kargs):
print(type(args))
print(args)
print(type(kargs))
print(kargs)
Argument unpacking:
def display(arg1,arg2,arg3):
print(arg1,arg2,arg3)
lst=[100,200,300]
display(lst)
output:
Error
To solve the above problem we have to unpack the list.
def display(arg1,arg2,arg3):
print(arg1,arg2,arg3)
lst=[100,200,300]
display(*lst)#unpacking
Argument packing:
When we don’t know the number of arguments to be passed to a function, then we
can pack all the arguments in a tuple.
def sumofargs(*args):
sum=0
for i in range(0,len(args)):
sum+=args[i]
return sum
print(sumofargs(10,20,30))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[166]
Formatting functions:
We can use placeholder( {} ) to format the output.
Lambda functions:
Python allows you to create anonymous function i.e function having no name using a
facility called lambda function.
lambda functions are small functions usually not more than a line. It can have any
number of arguments just like a normal function. The body of lambda functions is very
small and consists of only one expression. The result of the expression is the value
when the lambda is applied to an argument. Also there is no need for any return
statement in lambda function.
print(add(10,20))
ex1:
r = lambda x, y: x + y
res=r(12,13)# call the lambda function
print(res)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[167]
Ex2:
a=lambda x,y: x if x>y else y
print("Biggest no is:",a(10,99))
print("Biggest no is:",a(100,99))
Lambda functions are mainly used in combination with filter(), map() and reduce()
functions.
Filter:
filter() function mainly takes two arguments, first one is a function name and the
second one is a list of arguments.
Ex: Filter() functions which returns even numbers list, with Normal function
def checkeven(n):
return n%2==0
nos=[12,11,34,45,6,7,65,10,100]
evens=list(filter(checkeven,nos))
print(evens)
Ex: Filter() functions which returns even numbers list, with Lambda function
nos=[12,11,34,45,6,7,65,10,100]
evens=list(filter(lambda x:x%2==0,nos))
print(evens)
Write a function to return only odd nos from the list of 10 nos:
lst=[12,11,20,100,1,5,7,45,12,9]
oddres=list(filter(lambda x:(x%2==1),lst))
print(oddres)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[168]
map():
The map() function contains two arguments like,
r=map(func,seq)
it maps the elements of one sequence to another sequence.
Ex1:
a=[1,2,3,4,5]
b=[10,11,12,13,14]
reduce():
The reduce() function is defined in functools module in Python. It accepts two
arguments, a function and an iterable, and returns a single value.
Ex1:
from functools import reduce
lst=[1,2,3,4,5]
Ex:
Working with Filter,Map and Reduce in one example:
from functools import reduce
nos=[12,34,45,65,67,43,11,13,20]
evennos=list(filter(lambda x:x%2==0,nos))
print(evennos)
add10=list(map(lambda x:x+10,evennos))
print(add10)
sum=reduce(lambda x,y:x+y,add10)
print(sum)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[169]
Decorators:
A decorator is a design pattern in Python that allows a user to add new functionality to
an existing object without modifying its structure. Decorators are usually called before
the definition of a function you want to decorate.
Note: Every thing in python is considered as object, even functions and we can define
identiers to bound these objects.
Ex1:
def plus_one(number):
return number + 1
displayno = plus_one
print(displayno(5))
Ex2:
def minus(a,b):
print(a-b)
def changeorder(func):
def inner(a,b):
if a<b:
a,b=b,a
return func(a,b)
return inner
minus=changeorder(minus)
minus(10,5)
minus(5,10)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[170]
Sorting:
Arranging elements in an order ie ascending or descending
Bubble Sort:
Bubble is the Simplest algorithm that works by repeatedly swapping the adjacent
elements if they are not in sorted order.
Iteration 1:
5 3 8 6 7 2
3 5 8 6 7 2
3 5 8 6 7 2
3 5 6 8 7 2
3 5 6 7 8 2
3 5 6 7 2 8
Iteration 2:
3 5 6 7 2 8
3 5 6 2 7 8
And so on….
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[171]
Bubble Sort:
def bubblesort(nos):
for i in range(0,len(nos)-1):
for j in range(0,len(nos)-i-1):
if nos[j]>nos[j+1]:
temp=nos[j]
nos[j]=nos[j+1]
nos[j+1]=temp
nos=[12,34,45,3,4,1,99,25,500];
bubblesort(nos);
print(nos)
Selection Sort:
Selection sort is an algorithm that selects the smallest element from an unsorted list in
each iteration and places that element at the beginning of the unsorted list.
Step 2: Compare minimum with the second element. If second element is smaller than
minimum, assign the second element as minimum.
{20,12,10,15,2}
{20,12,10,15,2}
{20,12,10,15,2}
{20,12,10,15,2}
And so on..
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[172]
Selection Sort:
def selectionsort(nos):
for i in range(len(nos)-1):
minpos=i
for j in range(i+1,len(nos)-1):
if(nos[j]<nos[minpos]):
minpos=j;
temp=nos[i]
nos[i]=nos[minpos]
nos[minpos]=temp
nos=[12,34,45,3,4,1,99,25,500];
selectionsort(nos);
print(nos)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[173]
Hands-On-Lab
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[174]
9.Object Oriented Programming in Python
The program till now we have developed, runs around functions. I.e., block of
statements which manipulates data. This is called procedure-oriented programming.
Another way of programming is object-oriented programming, which combines data
and functionality into one single unit called object.
Object Oriented Programming is all about Mapping Real world objects to virtual
world(Software World).
Classes and objects are two basic building blocks of object-oriented programming.
A class creates a new type where an object is an instance of the class.
Class:
Class is a blueprint, or prototype from which objects can be created. Class can be
defined as a user defined datatype which is used to create variables of that class type.
Objects:
Object is an Instance of a class. It can also be defined as Object is a variable of class
type.
Ex:
Architectural Design of a house is a class and Constructed houses based on that design
are objects of that class.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[175]
Defining a class:
In Python, a class is defined by using a keyword class.
Syntax:
class <ClassName>:
<statement 1>
<statement 2>
.
.
<statement N>
Note:
There are some special attributes which starts with double underscore(_ _).
Ex:
__doc__ is an attribute which is used to access the document string of python class.
Example:
class Hello:
"Welcome to Object Oriented Programming"
print(Hello.__doc__)
Accessing variables:
# defining a class
class Sample:
str="Python"
def display(self):
print("Python is very simple and easy...")
# creating an object
obj1=Sample()
print(type(obj1))
print(obj1.str)
We can create multiple objects with the same class (which is having variables and
functions). Each object has its own copy of the variables.
# defining a class
class Sample:
str="Python"
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[176]
# creating an object
obj1=Sample()
obj2=Sample()
obj2.str="Data Science"
print(obj1.str)
print(obj2.str)
print(id(obj1))
print(id(obj2))
Note: Every time when a new object is created, It gets allocated space on heap
memory. Id’s will be different every time when the code is run.
Accessing functions:
We can also access functions of a class using object reference.
class Test:
def display(self):
print("This from display function...")
#creating objects
t1=Test()
t1.display()
self:
self is mandatory parameter for every function defined in a class. self refers to object
itself, self is like this parameter of c++ and java.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[177]
Write a Program to Create an Employee class and Create two objects.
class Employee:
empid=101
name="John"
salary=90000
def displayempinfo(self):
print("Employee id:",self.empid)
print("Employee Name:",self.name)
print("Employee Salary:",self.salary)
print("-----------------------------")
e1=Employee()
e2=Employee()
e1.displayempinfo()
e2.displayempinfo()
Passing Parameters to Methods to initialize Employee Objects:
class Employee:
empid=101
name="John"
salary=90000
def store(self,empid,name,salary):
self.empid=empid
self.name=name
self.salary=salary
def displayempinfo(self):
print("Employee id:",self.empid)
print("Employee Name:",self.name)
print("Employee Salary:",self.salary)
print("-----------------------------")
e1=Employee()
e2=Employee()
e2.store(102,"Raj",98000)
e1.displayempinfo()
e2.displayempinfo()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[178]
Types of Variables:
In Python Classes we can have two types of variables:
1.Static Variables
2.Instance Variables
Example:
class Student:
#class attribute
college="IIT"
#instance attributes
def __init__(self,name,avg):
self.name=name
self.avg=avg
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[179]
#create object of Student class
s1=Student("Raj Jain",90)
s2=Student("Prem Jain",99)
#access class attributes
print("{} is studying at {}".format(s1.name,s1.__class__.college))
print("{} is studying at {}".format(s2.name,s2.__class__.college))
Note:
__class__ attribute is used to access class attributes of a class, class attributes are
same for all the instances of a class.
Instance attributes are accessed using object reference ie s1 and s2, instance attriutes
are different for each instance of a class.
Example:
A class with instance variables and methods.
class Employee:
# instance attributes
def __init__(self,empno,ename,sal):
self.empno=empno
self.ename=ename
self.sal=sal
self.bonus=0
# instance methods
def calcBonus(self):
self.bonus=self.sal*10/100
def display(self):
print("Employee No:",self.empno)
print("Employee Name:",self.ename)
print("Employee Salary:",self.sal)
print("Employee Bonus:",self.bonus)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[180]
e1=Employee(101,"Raj",50000)
e1.calcBonus()
e1.display()
e2=Employee(102,"Prem",40000)
e2.calcBonus()
e2.display()
def __init__(self,name,age):
self.name=name
self.age=age
def display(self):
print(self.name+" is "+str(self.age)+" Years Old")
def compare(self,temp):
if(self.age==temp.age):
print("Both are of Same Age")
else:
print("Both are of Different Age")
s1.display()
s2.display()
s1.compare(s2)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[181]
Types of Methods:
There are Basically 3 types of methods in python.
1. Instance methods
2. Class methods
3. Static methods
Instance methods:
Instance methods performs operations on object instances, Instance methods can be
further classified as Accessor methods and Mutator methods.
Ex:
class Student:
University="Atish University"
def __init__(self,c,python,java):
self.c=c
self.python=python
self.java=java
#Accessor Methods
def getC(self):
return self.c
def getPython(self):
return self.python
def getJava(self):
return self.java
def avg(self):
return((self.c+self.python+self.java)/3)
#Mutator Methods
def setC(self,c):
self.c=c
def setPython(self,python):
self.python=python
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[182]
def setJava(self,java):
self.java=java
s1=Student(67,88,78)
print(Student.University,"Marks of First Student:",str(s1.getC())+"
"+str(s1.getPython())+" "+str(s1.getJava()))
print(s1.avg())
s1.setC(99)
s1.setPython(99)
s1.setJava(99)
print(s1.avg())
Class Methods:
Class Methods are used to perform operations on class variables.
Static Methods:
Static methods are self-contained methods, static methods cannot access class
variables or instance variables.
print(Student.University)
Student.update()
print(Student.University)
Student.info()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[183]
Data hiding:
✓ Instance variables of a class cannot be accessed outside the class directly, this
feature is known as data hiding.
✓ After performing proper validation/verification only the data is made available.
✓ By declaring data members(variable) as private (_ _) we can achieve data hiding.
Ex:
1. After validating username and password only u can access ur mail account.
2. Even though we are valid customer of the bank, we cannot access the account
information directly.
Ex:
class Account:
__balance=100;
def getBalance(self):
return self.__balance
a=Account()
a.__balance=900 # no affect
print(a.getBalance())
Data abstraction:
Hiding the functionality and highlighting the services is nothing but abstraction.
Encapsulation:
✓ The process of binding data members and corresponding methods into single
unit is called encapsulation.
✓ Every python class is an example of encapsulation.
✓ If a component follows data hiding and abstraction, then that component is
called encapsulated component.
✓ Encapsulation = data hiding+abstraction
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[184]
Inner classes:
Class inside Class is known as inner classes.
class Student:
def __init__(self,name,avg):
self.name=name
self.avg=avg
self.m=self.Mobile()
def display(self):
print(self.name,self.avg)
self.m.display()
class Mobile:
def __init__(self):
self.brand="IPhone"
self.model=11
self.price=80000
def display(self):
print(self.brand,self.model,self.price)
s1=Student("Raj",99)
s1.display()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[185]
Inheritance:
Inheritance is a way of creating a new class by using the attributes and methods of
existing class without modifying it. The old class is referred as base class(Parent) and
the newly created class is referred as Derived class(Child). The main advantage of
inheritance is reusability.
Single inheritance:
The process of inheriting all attributes from one class to the other class is known as
single inheritance.
Example:
class A:
a=100
def methodA1(self):
print("Method1 belong to class A")
def methodA2(self):
print("Method2 belong to class A")
class B(A):
b=200
def methodB1(self):
print("Method1 belong to class B")
def methodB2(self):
print("Method2 belong to class B")
objb=B()
print(objb.a)
print(objb.b)
objb.methodA1()
objb.methodA2()
objb.methodB1()
objb.methodB1()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[186]
Constructors in Inheritance:
Ex:
class A:
def __init__(self):
print("Class A Constructor...")
class B(A):
pass
b=B()
Note: Python Intrepreter looks for B Class constructor, if its not found then it invokes
its super class constructor ie Class A
Ex:
class A:
def __init__(self):
print("Class A Constructor...")
class B(A):
def __init__(self):
print("Class B Constructor…")
b=B()
Note: In the above code sub class ie B constructor is available so it invokes sub class ie
B Class constructor, to invoke super class constructor too use super keyword inside
sub class constructor.
Ex:
class B(A):
def __init__(self):
super().__init__()
print("Class B Constructor…")
Example:
class Person:
def __init__(self,id,name):
self.id=id
self.name=name
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[187]
def display(self):
print("{} - {}".format(self.id,self.name))
class Employee(Person):
def __init__(self,id,name,salary):
super().__init__(id,name)
self.salary=salary
def displayEmployee(self):
print("{} - {} - {}".format(self.id,self.name,self.salary))
e1=Employee(101,"Raj",90000)
e1.display()
e1.displayEmployee()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[188]
Multi-level inheritance:
class Person:
name="Raj"
class Student(Person):
fees=9000
class Result(Student):
avg=99
r=Result()
Hierarchical inheritance:
The process of inheriting all data members from one base class to multiple derived
classes is called hierarchical inheritance.
Example:
class Person:
id=101;
name="Raj"
class Student(Person):
avg=99
class Employee(Person):
salary=9000
s=Student()
e=Employee()
print("Student Details")
print("{} - {} - {}".format(s.id,s.name,s.avg))
print("Employee Details")
print("{} - {} - {}".format(e.id,e.name,e.salary))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[189]
Multiple inheritance:
Creating a derived class from multiple base classes.
class Student:
id=101
name="Raj"
def disp1(self):
print("{} - {}".format(self.id,self.name))
class Marks:
avg=99
def disp2(self):
print("{}".format(self.avg))
class Report(Student,Marks):
None
r=Report()
r.disp1()
r.disp2()
Note:
If the name of the method is same in both the base classes then only one method of
the base class will be invoked, the class which is inherited first gets the priority.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[190]
Constructors in Multiple Inheritance:
class A:
def __init__(self):
print("Class A Constructor...")
class B:
def __init__(self):
print("Class B Constructor")
class C(A,B):
def __init__(self):
super().__init__()
print("Class C Constructor....")
c=C()
Note: Constructor calling takes from left to right based on inheritance order.
class A:
def feature1(self):
print("Class A - F1...")
class B:
def feature1(self):
print("Class B - F1...")
class C(A,B):
pass
c=C()
c.feature1()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[191]
Calling Methods using Super keyword:
class A:
def feature1(self):
print("Class A - F1...")
class B:
def feature2(self):
print("Class B - F2...")
class C(A,B):
def display(self):
super().feature1()
super().feature2()
c=C()
c.display()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[192]
Encapsulation:
To provide security for our data items we can declare them as private, this is known as
encapsulation. private attributes declared using __ or _ (single or double underscore)
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
In Python, all classes inherit from the object class implicitly. It means that the
following two class definitions are equivalent.
class MyClass:
pass
class MyClass(object):
pass
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[193]
Polymorphism
Polymorphism means the ability to take multiple forms. The characteristic of being
able to assign different meaning or usage to something in different contexts.
Ex: A person behaves differently at different situations i.e. A person can behave like a
Father in the house and can be an Employee at office.
Note:
Generally, polymorphism is implemented through method overloading and
method overriding, python doesn’t support method overloading.
class HighSchool:
def read(self):
print("Reading...High School Student Marks....")
print("Calculating Total & Average...")
class University:
def read(self):
print("Reading...University Student Marks....")
print("Calculating Total & Average...")
class Student:
def Calculate(self,hs):
hs.read()
if x=='h':
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[194]
m = HighSchool()
elif x=='u':
m = University()
else:
print("Wrong Type input")
exit(0)
s1=Student()
s1.Calculate(m)
Operator Overloading:
When a operator behaves differently in different situations.
Ex:
a=10
b=20
print(a+b)
print(int.__add__(a,b))
a="Atish"
b="Jain"
print(a+b)
print(str.__add__(a,b))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[195]
s1=Student(12)
s2=Student(10)
s3=s1+s2 #s3=Student.__add__(s1,s2)
print(s3.age)
def __str__(self):
return str(self.age)
s1=Student(15)
s2=Student(18)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[196]
class Sample:
def display(self):
print("in display function...")
def display(self,a):
print("in display function...",a)
s=Sample()
s.display()
s.display(10)
Example:
class Sample:
def sum(self,a=None,b=None,c=None):
res=0
if a!=None and b!=None and c!=None:
res=a+b+c
elif a!=None and b!=None:
res=a+b
else:
res=a
return res
s1=Sample()
print(s1.sum(10,20,30))
print(s1.sum(10,5))
class B(A):
#pass
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[197]
def show(self):
print("Class B - show()")
a1=B()
a1.show()
Ex:
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
bird.swim()
#instantiate objects
blu = Parrot()
peggy = Penguin()
# passing the object
flying_test(blu)
flying_test(peggy)
Example:
class Dog:
def sound(self):
print("Bow Bow..")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[198]
class Cat:
def sound(self):
print("Meow...")
def makeSound(animal):
animal.sound()
d=Dog()
c=Cat()
makeSound(d)
makeSound(c)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[199]
10.Exception Handling
An error describes any issue that arises unexpectedly that cause a computer Program
to not function properly.
Types of Errors:
1. Compile Time or Syntax Errors
2. Logical Errors
3. Runtime Errors
Syntax:
try:
code
except exception 1:
exception code
except exception 2:
exception code
…….
…….
except exception N:
exception code
else:
when there is no exception execute else block code
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[200]
Example:
n=int(input("Enter a no:"))
d=int(input("Enter Divider:"))
try:
res=n/d
print("Result is:", res)
except Exception as e:
print(e)
print("Cannot Divide a no by 0")
else:
print("Success....")
Example:
n=int(input("Enter a no:"))
d=int(input("Enter Divider:"))
try:
res=n/d
except ArithmeticError:
print("Cannot Divide a no by 0")
else:
print("Success....")
print("Result is:",res)
Finally block:
Code of finally block is guaranteed to execute whether exception is raised or not.
res=n/d
except ArithmeticError as obj:
print(obj)
except:
print("Invalid input")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[201]
else:
print("Success....")
finally:
print("Always here...")
print("Result is:",res)
Example:
Program to Check whether the Student is Major, or Minor based on age.
def checkage(age):
if age < 0:
raise NegativeAgeException("Age cannot be negative")
if age >=18 :
print("Major....")
else:
print("Minor....")
try:
num = int(input("Enter your age: "))
checkage(num)
except NegativeAgeException as obj:
print(obj)
except:
print("something is wrong")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[202]
11.File Handling (I/O)
File is a name of the location on DISK where information is stored.
File is a name of the location on Secondary storage device(Hard Disk) where
information is stored. The Data on Disk is stored permanently. Secondary storage
devices are known as non-volatile memory devices.
Since RAM is volatile which loses its data when the machine is turned off. So, we use
files to store the data permanently so it will be used for future usage.
We can specify mode while opening file. The following table shows the different file
opening modes.
Mode Description
R Open a file for reading(default mode)
W Open a file for writing. Creates a new file if it does not exist or truncates the
file if it exists.
X Opens a file for exclusive creation. If the file already exists, the operation fails.
A Opens a file for appending, the contents are added from the end of the file,
creates new file if the does not exists.
T Opens a file in text mode(Default)
B Opens a file in Binary mode- binary mode is used for non-text data like images,
audio, video etc.
+ Opens a file in dual mode (reading and writing)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[203]
Ex # 1
Creating a file and writing text to it.
# open a file for writing and create if it doesn’t exist
f=open("sample.txt","w+")
f.write("This is to test the file")
f.close()
print("File is written");
Ex # 2
Creating file and appending data to it.
# open a file for Appending and create if it doesn’t exist
f=open("sample.txt","a+")
f.write("This is to test the file\n")
f.close()
print("File is written");
Ex # 3
Create a file and read data from it:
# open a file for reading
f=open("sample.txt","r")
if f.mode=="r":
str=f.read()
print(str)
Create fruits.txt:
Apple
Banana
PineApple
Mango
Grapes
Ex # 4
Read all lines from fruits.txt file
# open a file for reading all lines
f=open("fruits.txt","r")
for line in f:
print(line,end="")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[204]
Ex: 5
Reading Data from a Text File
File Name: Sample.txt
Heyy My Self Atish Jain
I Train Students to Excel in Coding Skills
My Technical Expertise are:
C Language
Object Oriented Programming using C++
DBMS Using Oracle
Java SE
Python
Note:
To Read Single Line use,
print(f.readline(),end=' ')
f=open('C:\\Users\\DELL\\OneDrive\\Atish Personals\\edited
pics\\Atish 1-jpg.jpg','rb')
f1=open('mynewpic.jpeg','wb')
for i in f:
f1.write(i)
print("Success")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[205]
Iterator
Ex:1
lst=[12,34,45,65,67]
itr=iter(lst)
#Method 1
print(itr.__next__())
#Method 2
print(next(itr))
#Method 3
for i in lst:
print(i)
Ex:2
class Students:
def __init__(self):
self.rollno=101
def __iter__(self):
return self
def __next__(self):
if self.rollno<110:
value=self.rollno
self.rollno=self.rollno+1
return value
else:
raise StopIteration
s=Students()
for i in s:
print(s.rollno)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[206]
Generators
Ex1:
def Items():
yield 10
yield 11
yield 12
yield 13
yield 14
yield 15
codes=Items()
print(codes.__next__())
for i in codes:
print(i)
Ex2:
def square():
n=1
while n<=10:
sq=n*n
yield sq
n+=1
s=square()
for i in s:
print(i)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[207]
Internal Working of Python:
computer only understands machine language and every programming language
comes with compiler converts source code to machine language.
PVM is also called Python Interpreter, and this is the reason Python is called an
Interpreted language.
And from the above process it is very much clear that python is compiled and
interpreted language.
Implementations of Python:
CPython:
This is the Default implementation of Python; it is written in C Language.
JPython:
Its Python for Java, Writing Python Programs using Java.
IronPython:
Python for .Net, Writing Python Programs using .Net Supported Languages.
PyPy:
Its Implemented in Python itself, and uses JIT Compiler
And there may more implementations…
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[208]
12.Modules & Packages
Breaking down the Application into Small Parts Based on their functionality is achieved
through modules.
Modules in Python are simply Python files with .py extension. The name of the module
will be name of the file. A Python Module can have set of functions, classes or
variables defined and implemented.
Advantages of Modules:
1. Reusability
2. Categorization
Importing modules:
There are different ways in which a module can be imported.
1. Using import statement
a. Import filename1, filename2,…
2. Using from… import statement
a. From import statement is used to import a particular attribute from a
module. If you don’t want to import whole module then from import is
recommended.
b. from module_name import attribute1, attribute2,…
Note:
To import multiple modules, use comma separator.
Ex: import addition, subtraction,…
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[209]
Using from import statement:
area.py
def circle(r):
print (3.14*r*r)
return
def square(s):
print (s*s)
return
def rectangle(l,b):
print(l*b )
return
def triangle(b,h):
print(0.5*b*h)
return
test.py:
from area import square,rectangle
square(5)
rectangle(10,20)
def sub(x,y):
return(x-y)
def mult(x,y):
return(x*y)
def div(x,y):
return(x/y)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[210]
File name: first.py
import calc
a=10
b=20
print("Addition:",calc.add(a,b))
print("Subtraction:",calc.sub(a,b))
print("Multiplication:",calc.mult(a,b))
print("Division:",calc.div(a,b))
Built in modules:
There are many built in modules in python, some of them are:
math, random, threading, collections, os, string etc..
Packages in python:
A Package is simply a collection of similar modules, sub-packages etc.
Each package in Python is a directory which MUST contain a special file called
__init__.py. This file can be empty, and it indicates that the directory it contains is a
Python package, so it can be imported the same way a module can be imported.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[211]
Package/Library File - (Directory)
(Having __init__ file)
Module 1 Module 2
(.py file) (.py file)
Function 1 Function 3
Function 2 Function 4
Create a directory.
create.py
import os
os.mkdir("Info")
print("Directory created")
sub.py
def sub():
print("This is from subtraction..")
3) Create a file __init__.py in Info Directory which specifies attributes in each module.
__init__.py
from Info import add
from Info import sub
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[212]
test.py
from Info import *
add.add()
sub.sub()
Special variables:
_ _name_ _
Ex:
print("Module name is:",__name__)
Note: The Moment we Import a module, then all the functios of that moule are
executed.
def sub():
print("Performing Subtraction....")
def main():
print("From Calc Main...")
add()
sub()
if(__name__=="__main__"):
main()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[213]
File name: First.py
from calc import add
def fun1():
add()
print("From Fun 1")
def fun2():
print("From Fun 2")
def main():
fun1()
fun2()
main()
Note:
Remove the if statement of calc.py run first.py and observe the output.
Calc.Py
def add():
print("Performing Addition....")
def sub():
print("Performing Subtraction....")
def main():
print("From Calc Main...")
add()
sub()
main()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[214]
13.Regular Expressions
A Regular expression is a special sequence of characters that helps you to match or
find strings or set of strings using a specialized syntax held in a pattern.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[215]
Where regular expressions used:
Logfile – extract a specific data from logfile.
Emailid – to verify email ids.
Phonenos – to validate phone no based on some format.
Database – update database contents based on some format using regex.
Patterns:
^ - matches start of a string.
Ex:
^Python
$ - matches for end of the string
Ex:
com$
. – anything other than line(\n)
* - 0 or more occurances
Ex:
x* = x,xx,xxx,xxxx
+ - 1 or more occurances
Ex:
x+ = x,xx,xxx,xxxx
? 0 or 1 occurrence
'x?' = x
{} – multiplication
x{2}=xx
x[2,]=xx,xxx,xxx
x[3,5] – min 3 max 5
a|b – either a or b
() – to group the regular expression
\s – for space
\S – nonwhite space
\d -single digit
\D – single non digits.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[216]
RE functions:
✓ match()
✓ search()
✓ findall()
✓ replace()
✓ split()
✓ compile()
match():
Tests the input String with the given pattern, returns match object if the match is
found or returns None
Ex:1
import re
str="Python is Very Important Language"
res1=re.match(r'Python',str)
print("Found: ",res1)
res2=re.match(r'Java',str)
print("Not Found:",res2)
Ex2:
import re
str="Python is Very Important Language"
found=re.match(r'Python',str)
if found:
print("Match found")
else:
print("Match Not Found")
Syntax:
re.match(pattern,string,[flag])
Ex:
import re
str="Hey:Ram Where are you Going"
match=re.match(r"Hey:\w\w\w",str)
print(match.group(0))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[217]
Ex:
import re
str="Hey:Ram Where are you Going"
match=re.match(r"Hey:\w\w\w\w",str)
if match:
print(match.group(0))
else:
print("Match not found")
search():
syntax:
re.search(pattern,string,[flag])
Ex:
import re
str="Learn Python, Because is Python is Easy and Powerful"
res1=re.match(r"Python",str)
res2=re.search(r"Python",str)
print(res1)
print(res2)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[218]
findall():
It will search entire string for all occurances.
Ex:
import re
str="Learn Python, Because is Python is Easy and Powerful"
res1=re.search(r"Python",str)
print(res1.group(0))
res2=re.findall(r"Python",str)
print(res2)
Result :
Raj:12
Prem:10
Kushi:8
Example:
import re
nameage='''
Raj is 12 Prem is 10
Kushi is 8'''
ages=re.findall(r'\d{1,3}',nameage)
names=re.findall(r'[A-Z][a-z]*',nameage) #String starting
with Uppercase followed by any number of lowercase
characters,
agedict={}
x=0
for en in names:
agedict[en]=ages[x]
x=x+1
print(agedict)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[219]
Cursor in search String and regex:
str="AH CAREER PVT LTD"
regex="CPL"
Ex1:
import re
str="I am learning Python at AH CAREER"
if re.search("Python",str):
print("Its found")
Ex2:
import re
str="I am learning Python at AH CAREER, Python is easy to learn"
word=re.findall("Python",str)
print(word)
for eachword in word:
print(eachword)
Find iterator:
Finds starting and ending index of the search string.
import re
str="I am learning Python at AH CAREER, Python is easy to learn"
for i in re.finditer("Python",str):
x=i.span()
print(x)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[220]
Match words with a particular Pattern:
import re
str="sat, rat, Hat, mat, bat, cat, zat"
result=re.findall("[srhmb]at",str)
for i in result:
print(i)
Replace a string:
import re
str="sat, rat, Hat, mat"
res=re.compile("[r]at")
str1=res.sub("Head",str)
print(str1)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[221]
Note:
\b – backspace
\f – form feed
\r – carrage return
\t – tab
\v – vertical tab
\d – matches for all digits [0-9]
\D – matches for all non digits.
import re
str="My Mobile no is 9949"
print(re.findall("\d",str))
print("Matches:",len(re.findall("\d",str)))
print(re.findall("\d{2}",str))
print("Matches:",len(re.findall("\d{2}",str)))
print(re.findall("\d{3,5}",nos))
print("Matches:",len(re.findall("\d{3,5}",nos)))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[222]
Symbol Description
. dot matches any character except newline
\w matches any word character i.e letters, alphanumeric, digits and underscore
(_)
\W matches non word characters
\d matches a single digit
\D matches a single character that is not a digit
\s matches any white-spaces character like \n, \t, spaces
\S matches single non white space character
[abc] matches single character in the set i.e either match a, b or c
[^abc] match a single character other than a, b and c
[a-z] match a single character in the range a to z.
[a-zA- match a single character in the range a-z or A-Z
Z]
[0-9] match a single character in the range 0-9
^ match start at beginning of the string
$ match start at end of the string
+ matches one or more of the preceding character (greedy match).
* matches zero or more of the preceding character (greedy match).
Using \w:
import re
phno1="9900-143-111"
phno2="990-1430-111"
if re.search("\w{4}-\w{3}-\w{3}",phno1):
print("Valid Phone no")
else:
print("Not Valid Phone no")
if re.search("\w{4}-\w{3}-\w{3}",phno2):
print("Valid Phone no")
else:
print("Not Valid Phone no")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[223]
using \w and \d:
import re
phno1="990a-143-111"
phno2="9900-143-111"
if re.search("\w{4}-\w{3}-\w{3}",phno1):
print("Valid Phone no")
else:
print("Not Valid Phone no")
if re.search("\d{4}-\d{3}-\d{3}",phno2):
print("Valid Phone no")
else:
print("Not Valid Phone no")
if re.search("\w{2,20}\s\w{2,20}",name):
print("Name is valid")
else:
print("Name is in valid")
Email verification:
Email address should include:
✓ 1 to 20 lowercase and uppercase, numbers, plus _%+-
✓ An @ symbol
✓ 2 to 20 lowercase and uppercase letters, numbers, plus.
✓ A period
✓ 2 to 3 lowercase and uppercase letters.
Ex:
import re
emailid="[email protected] [email protected] [email protected]"
print("Email matches:",len(re.findall("[\w]@[\w].[a-
z]",emailid)))
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[224]
Ex:
import re
def isValid(email):
if(re.match("^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-
]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$", email) !=
None):
return True
return False
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[225]
14.GUI Programing in Python
Graphical User Interface(GUI), an interface to the computer applications using
graphical elements instead of a command line interface. This allows to interact with
the programs using buttons and input fields.
The following are the different GUI Libraries from Different Programming languages.
✓ TKinter is a Python GUI Library.
✓ QT is a C++ GUI Library
✓ Swing is a Java GUI Library.
To create GUI applications in python we should use any one of the libraries from the
following libraries.
✓ TKinter
✓ PyQt4
✓ PyQt5
✓ WxPython
Introduction to Tkinter:
Tkinter provides various GUI elements, which we can use to build GUI interface-such
as textfields, radiobuttons, buttons etc. we can call these elements as widgets.
Ex:
import tkinter
frame=tkinter.Tk()
frame.title("Welcome to Python GUI")
frame.mainloop()
mainloop() is a method on the main window which we execute when we want to run
our application. This method will loop forever, waiting for events from the user, until
the user exits the program – either by closing the window, or by terminating the
program with a keyboard interrupt in the console.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[226]
Ex:
from tkinter import *
root = Tk()
l = Label(root,text="Welcome to AH Career");
b1= Button(root,text="Submit")
b2= Button(root,text="Reset")
l.pack()
b1.pack()
b2.pack()
root.mainloop()
Layout Options:
Python TKinter provides three different geometry managers.
pack() - Arranges all the widgets vertically inside the parent container from top to
bottom.
We can use optional parameter side to change the alignment to top, bottom, left Or
right.
grid() is recommended to avoid complexity and places controls in a more flexible way.
Ex:
from tkinter import *
window = Tk()
window.title("Welcome to AH CAREER")
window.geometry('350x200')
window.mainloop()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[227]
Ex:
from tkinter import *
window = Tk()
window.title("Welcome to AH CAREER")
window.geometry('350x200')
def clicked():
lbl.configure(text="Button was clicked !!")
window.mainloop()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[228]
15.Multithreading
class Bye:
def run(self):
for i in range(5):
print("Bye")
t1=Welcome()
t2=Bye()
t1.run()
t2.run()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[229]
Ex1:
# creating thread without using a class
for i in range(5):
t=Thread(target=display)
t.start()
for i in range(5):
t=Thread(target=display, args=('AH CAREER',))
t.start()
Note:
Arguments are passed in a tuple, so in tuple when we are passing single argument
comma is required.
class MyThread(Thread):
#override run method
def run(self):
for i in range(1,6):
print(i)
t1=MyThread()
t1.start()
t1.join()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[230]
Working with Multiple Threads:
from threading import *
from time import *
class Message:
def __init__(self,str):
self.str=str
def disp(self):
for i in range(1,6):
print(self.str,":",i,end="\n")
sleep(1)
Example on Multi-threading:
from threading import *
from time import *
class Welcome(Thread):
def run(self):
for i in range(5):
print("Welcome")
sleep(1)
class Bye(Thread):
def run(self):
for i in range(5):
print("Bye")
sleep(1)
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[231]
t1=Welcome()
t2=Bye()
t1.start()
t2.start()
class Bye(Thread):
def run(self):
for i in range(5):
print("Bye")
sleep(1)
t1=Welcome()
t2=Bye()
t1.start()
t2.start()
t1.join()
t2.join()
print("I am from Main")
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[232]
16.Python – MySql Database
Till now the data what we save stored it’s in temporary storage, to storage the data
permanently we need external databases.
Database:
MySql – Search for MySQL Installer in google
https://dev.mysql.com/downloads/installer/
Note: ByDefault you will get one user, root if required you can more users at the
time of installation only.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[233]
Working with MySql Client:
Windows Menu → MySql Client →
Password : root
> status
MySql Commands:
→ Show databases
→ create database mydb
→ use mydb
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[234]
Installing MySql-Connector in PyCharm IDE:
File → Settings -> Project :<Project Name> → Python Interpreter → Click on (+) →
MySql-Connector → Install Package
conn = mysql.connector.connect(
user='root',
password='root',
host='127.0.0.1',
database='mydb')
cur = conn.cursor()
cur.execute(query)
cur.close()
conn.close()
conn = mysql.connector.connect(
user='root',
password='root',
host='127.0.0.1',
database='mydb')
cur = conn.cursor()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[235]
no = int(input("Enter Rollno:"))
name = str( input("Enter name:"))
age = int(input ("Enter age:"))
conn.commit()
cur.execute(query)
cur.close()
conn.close()
conn = mysql.connector.connect(
user='root',
password='root',
host='127.0.0.1',
database='mydb')
cur = conn.cursor()
no = int(input("Enter Rollno:"))
name = str( input("Enter name:"))
age = int(input ("Enter age:"))
conn.commit()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[236]
query = ("SELECT * FROM student")
cur.execute(query)
cur.close()
conn.close()
import mysql.connector
conn = mysql.connector.connect(
user='root',
password='root',
host='127.0.0.1',
database='mydb')
cur = conn.cursor()
conn.commit()
query = ("SELECT * FROM student")
cur.execute(query)
for (no,name,age) in cur:
print("{},{},{}".format(no,name,age))
cur.close()
conn.close()
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[237]
17.Anaconda Setup
Python is So Famous Because it’s easy to use, it Provides different libraries to work
with different requirements.
URL:
https://www.anaconda.com/
Command Prompt:
Anaconda Prompt → Python → print(“Hello”)
Spyder:
Spyder is an open-source cross-platform integrated development environment (IDE)
for scientific programming in the Python language.
Jypter Notebooks:
The Jupyter Notebook is an open-source web application that you can use to create
and share documents that contain live code, equations, visualizations, and text.
Jupyter Notebook is maintained by the people at Project Jupyter.
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[238]
Working on Projects:
GIT:
Create your Account on GitHub
https://github.com/
Python Documentation:
https://docs.python.org/3/contents.html
Education is the most powerful weapon, which you can use to change the world.
-Nelson Mandela
[239]