Python Notes
Python Notes
------------------------------
Python is a simple, general purpose, high level, and
object-oriented programming language.
2) Expressive Language
Python can perform complex tasks using a few lines of
code. A simple example, the hello world program you
simply type print("Hello World"). It will take
only one line to execute, while Java or C takes
multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python
program is executed one line at a time. The advantage
of being interpreted language, it makes debugging easy
and portable.
4) Cross-platform Language
Python can run equally on different platforms such as
Windows, Linux, UNIX, and Macintosh, etc. So, we can
say that Python is a portable language. It enables
programmers to develop the software for several
competing platforms by writing a program only once.
5) Free and Open Source
Python is freely available for everyone. It is freely
available on its official website www.python.org. It
has a large community across the world that is
dedicatedly working towards make new python modules
and functions. Anyone can contribute to the Python
community. The open-source means, "Anyone can download
its source code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts
of classes and objects come into existence. It supports
inheritance, polymorphism, and encapsulation, etc. The
object-oriented procedure helps to programmer to write
reusable code and develop applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the
code and thus it can be used further in our Python code.
It converts the program into byte code, and any platform
can use that byte code.
4. Keep Practicing
The next important step is to do the practice. It needs
to implementing the Python concepts through the code.
We should be consistence to our daily coding practice.
Consistency is the key of success in any aspect of life
not only in programming. Writing code daily will help
to develop muscle memory.
7. Do small Projects
After understanding Python’s basic concept, a beginner
should try to work on small projects. It will help to
understand Python more deeply and become more component
in it. Theoretical knowledge is not enough to get
command over the Python language. These projects can
be anything as long as they teach you something. You
can start with the small projects such as calculator
app, a tic-toc-toe game, an alarm clock app, a to-do
list, student or customer management system, etc.
Once you get handy with a small project, you can
easily shift toward your interesting domain (Machine
Learning, Web Development, etc.).
8. Teach Others
There is a famous saying that "If you want to learn
something then you should teach other". It is also
true in case of learning Python. Share your
information to other students via creating blog
posts, recording videos or taking classes in local
training center. It will help us to enhance the
understanding of Python and explore the unseen
loopholes in your knowledge. If you don’t want
to do all these, join the online forum and post
your answers on Python related questions.
Types of Applications
1) Web Applications
We can use Python to develop web applications. It
provides libraries to handle internet protocols such
as HTML nd XML, JSON, Email processing, request,
beautifulSoup, Feedparser, etc. One of Python
web-framework named Django is used on Instagram.
Python provides many useful frameworks,
and these are given below:
3) Console-based Application
Console-based applications run from the command-line
or shell. These applications are computer program
which are used commands to execute. This kind of
application was more popular in the old generation
of computers. Python can develop this kind of
application very effectively. It is famous for
having REPL, which means the Read-Eval-Print Loop
that makes it the most suitable language for the
command-line applications.
Python provides many free library or module which helps to build the
command-line apps. The necessary IO libraries are
used to read and write. It helps to parse argument and create console
help text out-of-the-box. There are also advance
libraries that can develop independent console apps.
4) Software Development
Python is useful for the software development process.
It works as a support language and can be used to
build control and management, testing, etc.
6) Business Applications
Business Applications differ from standard applications.
E-commerce and ERP are an example of a business
application. This kind of application requires
extensively, scalability and readability, and Python
provides all these features.
7) Audio or Video-based Applications
Python is flexible to perform multiple tasks and can be
used to create multimedia applications. Some multimedia
applications which are made by using Python are
TimPlayer, cplay, etc. The few multimedia libraries
are given below.
Gstreamer
Pyglet
QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design
engineering related architecture. It is used to
develop the 3D representation of a part of a system.
Python can create a 3D CAD application by using the
following functionalities.
Fandango (Popular )
CAMVOX
HeeksCNC
AnyCAD
RCAM
9) Enterprise Applications
Python can be used to create applications that can be
used within an Enterprise or an Organization. Some
real-time applications are OpenERP, Tryton, Picalo, etc.
OpenCV
Pillow
SimpleITK
----------------------------------------------------------------
First Python Program
In this Section, we will discuss the basic syntax of
Python, we will run a
simple program to print Hello
World on the console.
Using the script mode, we can write multiple lines code into a file which can
be executed later. For this purpose,
we need to open an editor like notepad, create a file named and save it with
.py extension, which stands for "Python".
Now, we will implement the above example using the script mode.
print("hello world") #here, we have used print() function to print the message
on the console.
----------------------------
Multi-line Statements
Multi-line statements are written into the notepad like an editor and saved it
with .py extension. In the following
example, we have defined the execution of the multiple code lines using the
Python script.
---------------------------
print("Hai to python")
print("OOPS")
print("Data science")
output:
Hai to python
OOPS
Data science
------------------------------------------------
Python Variables
Variable is a name that is used to refer to memory
location. Python variable is also known as an
identifier and used to hold value.
---------------------------------------------
Declaring Variable and Assigning Values
Python does not bind us to declare a variable before
using it in the application.
It allows us to create a variable
at the required time.
a = 50
b =100
shabeeb = 90
------------------------------------------
Variable Names
We have already discussed how to declare the valid
variable. Variable names can be any length can have
uppercase, lowercase (A to Z, a to z), the digit (0-9),
and underscore character(_). Consider the following
example of valid variables names.
-------------------
name = "Devansh"
age = 20
marks = 80.50
print(name)
print(age)
print(marks)
output:
Devansh
20
80.5
-------------------------------------------------
Consider the following valid variables name.
name = "Hai"
Name = "Boy"
naMe = "C"
NAME = "D"
n_a_m_e = "E"
_name = "F"
name_ = "G"
_name_ = "H"
na56me = "I"
print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)
----------------------------------------
Camel Case :- In the camel case, each word or abbreviation in the middle of
begins with a capital letter.
There is no intervention of whitespace.
For example - nameOfStudent,
valueOfVaraible, etc.
Pascal Case :- It is the same as the Camel Case, but
here the first word is also capital. For example -
NameOfStudent, etc.
Snake Case :- In the snake case, Words are separated
by the underscore.
For example - name_of_student, etc.
-----------------------------
Multiple Assignment
Python allows us to assign a value to multiple variables
in a single statement,
which is also known as multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value
to multiple variables or assigning
multiple values to multiple variables.
output:
5
10
15
-----------------------------------
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
del <variable_name>
----------------
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x) # error
---------------------------------
Print Single and Multiple Variables in Python
We can print multiple variables within the single print statement.
------------------
# printing single value
a=5
print(a)
output:
5
---------------------------
#Printing Multiple Variables
a=5
b=6
# printing multiple variables
print(a,b)
# separate the variables by the comma
print(1, 22, 3, 4, 5, 6, 7, 8)
output:
56
1 22 3 4 5 6 7 8
---------------------------------------
Python Data Types
Variables can hold values, and every value has a
data-type. Python is a dynamically
typed language; hence we do not need to define the
type of the variable while declaring it. The
interpreter implicitly binds the value with its type.
a=5
The variable a holds integer value five and we did not
define its type. Python interpreter will automatically
interpret variables a as an integer type. Python
enables us to check the type of the variable used in
the program. Python provides us the type() function,
which returns the type of the variable passed.
------------------
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
output:
<class ’int’>
<class ’str’>
<class ’float’>
-------------------------------------
Standard data types
A variable can hold different types of values. For example, a person’s
name must be stored as a string whereas its id must be stored as
an integer.
Python provides various standard data types that define the storage method on
each of them. The data types defined in Python are given below.
Numbers
Sequence Type
Boolean
Set
Dictionary
-----------------------
Numbers
Number stores numeric values. The integer, float, and complex values belong
to a Python Numbers data-type. Python provides the type() function to
know the data-type of the variable.
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
output:
The type of a <class ’int’>
The type of b <class ’float’>
The type of c <class ’complex’>
-------------------------
Int - Integer value can be any length such as integers 10, 2, 29, -20,
-150 etc. Python has no restriction on the length of an integer.
Its value belongs to int Float - Float is used to store floating-point
numbers like 1.9, 9.902, 15.2, etc.
It is accurate upto 15 decimal points.
complex - A complex number contains an ordered pair, i.e., x + iy
where x and y denote the real and imaginary parts, respectively.
The complex numbers
like 2.14j, 2.0 + 2.3j, etc.
--------------------------------------
Python Keywords
Python Keywords are special reserved words that convey a special meaning
to the compiler/interpreter. Each keyword
has a special meaning and a specific operation. These keywords can’t be
used as a variable. Following is the List
of Python Keywords.
Example:
-----------------
tx=’hello to python’
print(tx)
output:
hello to python
--------------------
Multi-line String - A piece of text that is written in multiple lines
is known as multiple lines string.
output:
India is my country
-------------------------
2) Using triple quotation marks:-
a=""" India
is my
country"""
print(a)
output:
India
is my
country
------------------
b=’’’ India
is my
country’’’
print(b)
output:
India
is my
country
-------------------------
Numeric literals:
Int(signed integers)
Numbers( can be both positive and negative) with no
fractional part.eg: 100
-----------
Long(long integers)
Integers of unlimited size followed by lowercase or
uppercase L eg: 87032845L
float(floating point)
Real numbers with both integer and fractional part
eg: -26.2
--------------------
#numericals
output:
20
129
141
301
------------------
# Float Literal
float_1 = 100.5
float_2 = 1.5e2
print(float_1)
print(float_2)
output:
100.5
150.0
-------------------
# Complex Literal
a = 5 + 3.14j
print(a, a.imag, a.real)
output:
(5+3.14j) 3.14 5.0
------------------------
II. Boolean literals:
A Boolean literal can have any of the two values: True or
False.
-------------
a=True
b=False
print(a)
print(b)
print(type(a))
print(type(b))
output:
True
False
<class ’bool’>
<class ’bool’>
---------------------
Python Operators
The operator can be defined as a symbol which is
responsible for a particular operation between two
operands. Operators are the pillars of a program
on which the logic is built in a specific programming
language. Python provides a variety of operators,
which are described
as follows.
Arithmetic operators
Comparison operators
Assignment Operators
Logical Operators
Membership Operators
Identity Operators
----------------------
Python Arithmetic Operators
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand
is less than the second operand, the value results negative. For example, if a = 20, b = 10 => a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a/b = 2.0
* (Multiplication) It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a * b =
200
% (reminder) It returns the reminder after dividing the first operand by the second operand.
For example, if a = 10, b = 4 => a%b = 2
** (Exponent)5**2 => 25 It is an exponent operator represented as it calculates the first operand power to
the second operand.
// (Floor division) 5//2 =>2 It gives the floor value of the quotient produced by dividing the two operands.
--------------------
x=5
y=3
print(x + y)
output:
8
----------------------
x=5
y=3
print(x - y)
------------------
x=5
y=3
print(x * y)
--------------
x = 12
y=3
print(x / y)
-----------------
x=5
y=2
print(x % y)
output:
1
----------
x=2
y=5
print(x // y) #7
#the floor division // rounds the result down to the nearest whole numbe
--------------------------
Comparison operator
Comparison operators are used to comparing the value of the two operands
and returns Boolean true or false accordingly.
The comparison operators are described in the following table.
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition becomes true.
>= If the first operand is greater than or equal to the second operand, then the condition becomes true.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
----------------------
x=5
y=3
print(x == y)
print(x != y)
print(x > y)
print(x < y)
------------------------
x=5
y=3
print(x >= y)
---------------------------
x=5
y=3
print(x <= y)
output:
15
----------------
x=5
x /= 3 vvvv#same as x=x/3
print(x)
---------------------
Python Logical Operators
Logical operators are used to combine conditional
statements:
Logical operators,and, or not.
-----------------
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is
less than 10
---------------
True and True => True
True and False => False
False and True => False
False and Fals => False
---------------------------
or Returns True if one of the statements is true x < 5 or x < 4
----------------
x=5
print(x > 3 or x < 4)
# returns True because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)
-------
’or’ working
-----------------------------
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
x=5
print(not(x > 3 and x < 10))
# returns False because not is used to reverse the result
------------
’not’ meaning
not(True) =>False
not(False)=> True
----------------------
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same
object,
with the same memory location:
is Returns True if both variables are the same object x is y
-----------
st1="hello"
st2="hello"
print(st1 is st2)
output:
True
---------
st1="hello"
st2="Hello"
print(st1 is st2)
output:
False
-------------
is not Returns True if both variables are not the same object x is not y
------------------
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
output:
True
------------------
Python Comments
Python Comment is an essential tool for the programmers. Comments are
generally used to explain the code.
We can easily understand the code if it has a proper explanation.
A good programmer must use the comments
because in the future anyone wants to modify the code as well as implement
the new module; then, it can be done easily.
output:
Hello Python
-------------------
Multiline Python Comment
We must use the hash(#) at the beginning of every line of code to apply
the multiline Python comment.
------------------
# First line of the comment
# Second line of the comment
# Third line of the comment
#print("hello")
print("okay")
output:
okay
----------------
# Variable a holds value 5
# Variable b holds value 10
# Variable c holds sum of a and b
# print("hey")
a=5
b = 10
c = a+b
print("The sum is:", c)
output:
15
---------------------
We can also use the triple quotes (’’’) or (""") for multiline comment.
The triple quotes are also used to string formatting.
a=5
b = 10
c = a+b
print("The sum is:", c)
output:
15
#----------------------------------------
Taking input in Python
Developers often have a need to interact with users, either to get data or
to provide some sort of result.
Syntax:
input( prompt message )
-------------
# Python program showing
# a use of input()
abc = input("Enter your value: ")
print(abc)
output:
Enter your value: kochi
kochi
-----------------------------
Python indentation
Python indentation uses to define the block of the
code. The other programming languages such as C,
C++, and Java use curly braces {}, whereas Python
uses an indentation. Whitespaces are used as
indentation in Python.
Block1:
stat1
stat2
...
Block11:
Stat1
Stat2
...
Block2:
Stat1
Stat2
...
--------------------------------
Python If-else statements
Decision making is the most important aspect of almost all the programming
languages. As the name implies, decision making allows us to run a
particular block of code for a particular decision. Here, the decisions
are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.
-----------------
If Statement The if statement is used to test a specific condition. If the
condition is true, a block of code (if-block) will be executed.
If - else Statement The if-else statement is similar to if statement except
the fact that, it also provides the block of the code for the false case of
the condition to be checked. If the condition provided in the if statement
is false, then the else statement will be executed.
if expression:
statement
output:
enter the number:12
Number is even
--------------------
#Program to print the largest of the three numbers.
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
if a>b and a>c:
print("a is largest")
if b>a and b>c:
print("b is largest")
if c>a and c>b:
print("c is largest")
output:
Enter a: 10
Enter b: 20
Enter c: 30
c is largest
--------------------
The if-else statement
The if-else statement provides an else block combined with the if statement
which is executed in the false case of the condition.
output:
Enter your age:17
Sorry! you have to wait !!
---------------------------
Program to check whether a number is even or not.
output:
enter the number:30
Number is even...
--------------------------------
The elif statement
The elif statement enables us to check multiple conditions and execute the
specific block of statements depending upon the true condition among them.
We can have any number of elif statements in our program
depending upon our need. However, using elif is optional.
#syntax
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
...
...
...
else:
# block of statements
-----------------------
# example elif
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")
-----------------------
# example elif
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50")
elif number==100:
print("number is equal to 100")
else:
print("number is not equal to 10, 50 or 100")
---------------------------------
Nested if Statement
if statement can also be checked inside other if statement. This conditional
statement is called a nested if statement. This means that inner if condition
will be checked only if outer if condition is true and by this,
we can see multiple conditions to be satisfied.
----------------------
Nested if Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
-------------------
#largest of 3-numbers using nested if
if a > b:
if a>c:
print("a is larger")
else:
print("c is larger")
else:
if b>c:
print("b is larger")
else:
print("c is larger")
-----------------------------
Python Loops:
The flow of the programs written in any programming language is sequential
by default. Sometimes we may need to alter the flow of the program. The execution
of a specific code may need to be repeated several numbers of times. For this
purpose, The programming languages provide various types of loops which are
capable of repeating some specific code several numbers of times.
---------------
str = "Python"
for i in str:
print(i)
output:
P
y
t
h
o
n
---------------------
For loop Using range() function
The range() function
Syntax of range():
range(start,stop,step size)
for i in range(10):
print(i, end = ’ ’)
output:
0123456789
------------------
#Program to print table of given number.
output:
Enter the number:5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
---------------------------
#Program to print even number using step size in range().
n = int(input("Enter the limit number:"))
for i in range(2,n,2):
print(i)
output:
Enter the limit number:20
2
4
6
8
10
12
14
16
18
-----------------------
Nested for loop in python:
Python allows us to nest any number of for loops inside a for loop. The inner
loop is executed n number of times for every iteration of the outer loop.
Syntax:
output:
Enter the rows:7
*
**
***
****
*****
******
*******
--------------
1
22
333
4444
55555
----------------
1
12
123
1234
-----------------------
Using else statement with for loop:
Unlike other languages like C, C++, or Java, Python allows us to use the
else statement with the for loop which can be executed only when all the
iterations are exhausted. Here, we must notice that if the loop contains
any of the break statement then the else statement will not be executed.
-------------------------
for i in range(0,5):
print(i)
break
else:
print("for loop is exhausted")
output:
0
The loop is broken due to break statement...came out of the loop
--------------------------------
Python While loop:
The Python while loop allows a part of the code to be executed until the given
condition returns false. It is also known as a pre-tested loop.
while expression:
statements
-----------------
#print numbers from 0 to 8
i=0
while i<8:
print(i)
i=i+1
output:
0
1
2
3
4
5
6
7
---------------
Using else with while loop:
Python allows us to use the else statement with the while loop also. The else
block is executed when the condition given in the while statement becomes false.
Like for loop, if the while loop is broken using break statement, then the else
block will not be executed, and the statement present after else block will be
executed.
The else statement is optional to use with the while loop.
---------------------
#else with while
i=0
while i<8:
print(i)
i=i+1
else:
print(" no breaks")
print("outside loop")
output:
0
1
2
3
4
5
6
7
no breaks
outside loop
---------------
#else with while
i=0
while i<25:
if i==5:
break
print(i)
i=i+1
else:
print(" no breaks")
print("outside loop")
output:
0
1
2
3
4
outside loop
----------------
Loop Control Statements:
We can change the normal sequence of while loop’s execution using the loop
control statement. When the while loop’s execution is completed, all automatic
objects defined in that scope a re demolished. Python offers the following
control statement to use within the while loop.
i=0
while i < 30:
if i == 10:
i =i+ 1
continue
print(’Current number :’, i)
i += 1
-------------------------
# execution breaks when reading reaches at 15
i=0
while i < 30:
if i == 15:
break
print(’Current number :’, i)
i += 1
print("outside while")
-----------------------
Python String:
Till now, we have discussed numbers as the standard data-types in Python.
In this section , we will discuss the most popular data type in Python, i.e.,
string. Python string is the collection of the characters surrounded by
single quotes, double quotes, or triple quotes.
Consider the following example in Python to create a string.
Syntax:
str="Hi python"
Here, if we check the type of the variablestrusing a Python script
print(type(str)) then it will print as <class ’str’>.
-------------
Creating String in Python:
We can create a string by enclosing the characters in single-quotes or
double- quotes. Python also provides triple-quotes to represent the string,
-------------------
# Using single quotes
str1 = ’Hello Python’
print(str1)
output:
Hello Python
-----------------
# Using double quotes
str2 = "Hello Python"
print(str2)
output:
Hello Python
--------------
# Using triple quotes
str3 = ’’’Triple quotes are generally used for
represent the multiline or
docstring’’’
print(str3)
output:
Triple quotes are generally used for
represent the multiline or
docstring
-----------------
output:
Triple quotes are generally used for
represent the multiline or
docstring
--------------------------
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0.
-----------------
str = "HELLO"
print(str[0]) # returns H
print(str[1]) # returns E
print(str[2]) # returns L
print(str[3]) # returns L
print(str[4]) # returns O
# It returns the IndexError because 6th index doesn’t exist
print(str[6]) #error
-------------
slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in Python
to access the substring from the given string.
# Given String
str = "INTERNATIONAL"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
-------------------
We can do the negative slicing in the string; it starts from the rightmost
character, which is indicated as -1.
The second rightmost index indicates -2, and so on.
# Given String
str = "INTERNATIONAL"
print(str[-1]) # L
print(str[-3]) # N
print(str[-2:]) #AL
print(str[-4:-1]) #ONA
print(str[-7:-2]) #ATION
# Reversing the given string
print(str[::-1]) #reverse
print(str[-12]) #N
------------------
Reassigning Strings
Updating the content of the strings is as easy as assigning it to
a new string. The string object doesn’t support item assignment
i.e., A string can only be replaced with new string since its content
cannot be partially replaced.
-------------
str = "HELLO"
print(str)
str = "hello"
print(str)
output:
HELLO
hello
---------
but,
-------
str = "HELLO"
str[0] = "h" #error
print(str)
---------------
Deleting the String:
As we know that strings are immutable. We cannot delete or remove the characters
from the string. But we can delete the entire string using the del keyword.
--------------
str = "python"
del str[1] #raise error
---------
Now we are deleting entire string.
str1 = "python"
del str1
print(str1) #error
-------------------
String Operators:
+ ,It is known as concatenation operator used to join the strings
given either side of the operator.
* ,It is known as repetition operator. It concatenates the
multiple copies of the same string.
[] ,It is known as slice operator. It is used to access the
sub-strings of a particular string.
[:] ,It is known as range slice operator. It is used to access
the characters from the specified range.
in ,It is known as membership operator. It returns if a particular sub-string is
present in the specified string. not in ,It is also a membership
operator and does the exact reverse of in. It returns true
if a particular substring is not present in the specified string.
r/R ,It is used to specify the raw string. Raw strings are used in the cases where we need to print the
actual meaning of
escape characters such as "C://python". To define any string as a raw string, the character r or R is
followed by the string.
% ,It is used to perform string formatting. It makes use of the format specifiers used in C programming like
%d or %f
to map their values in python. We will discuss how formatting is done in python.
------------------------------
str = "Hello"
str1 = " world"
print(str*3) #prints HelloHelloHello
print(str+str1) #prints Hello world
print(str[4]) #prints o
print(str[2:4]) #prints ll
print(’w’ in str) #prints false as w is not present in str
print(’wo’ not in str1) # prints false as wo is present in str1.
print(r’C://python37’) # prints C://python37 as it is written
print("The string str : %s and str1:%s" % (str,str1)) # prints The
string str : Hello
---------------------------------------------------------------
Python String Formatting:
Escape Sequence
Let’s suppose we need to write the text as - They said, "Hello what’s going on?"-
the given statement can be written in single quotes or double quotes but it will
raise the SyntaxError as it contains both single and double-quotes.
output:
Python1 Python2 Python3
#-----------------------
\\ Backslash
print("\\")
output:
\
#---------------------
\’ Single Quotes
print(’\’’)
output:
’
#------------------------
\" Double Quotes
print("\"")
output:
"
#----------------------------
\b ASCII Backspace(BS)
print("Hello \b World")
#-------------------------
\n new line
print("Hello \n World!")
output:
Hello
World!
#--------------------------
\t ASCII Horizontal Tab
print("Hello \t World!")
output:
Hello World!
#-----------------------------------
We can ignore the escape sequence from the given string by using the raw string. We can do this
by writing r or R in front of the string.
print(r"C:\\Users\\DEVANSH SHARMA\\Python32")
output:
C:\\Users\\DEVANSH SHARMA\\Python32
#-------------------------------------
Python String Formatting Using % Operator:
Python allows us to use the format specifiers used in C’s printf statement. The
format specifiers in Python are treated in the same way as they are treated in C.
However, Python provides an additional operator %, which is used as an
interface between the format specifiers and their values. In other words,
we can say that it binds the format specifiers to the values.
-------------------------------
var1 = 10
var2 = 1.290
var3 = "Devansh"
print("Integer: %d\nFloat:%f\n arString:%s" % (var1,var2,var3))
output:
Integer: 10
Float:1.290000
String:Devansh
----------------------------------
Python String functions:
Python String capitalize() Method
Python capitalize() method converts first character of the string into uppercase
without altering the whole string.
It changes the first character only and skips rest of the string unchanged.
Signature:
capitalize()
Parameters:
No parameter is required.
Return Type
It returns a modified string.
# Python capitalize() function example
------------------
# Variable declaration
str = "python data"
# Calling function
str2 = str.capitalize()
# Displaying result
print("Old value:", str)
print("New value:", str2)
output:
Old value: python data
New value: Python data
----------------------------------------
Python String Count() Method
It returns the number of occurences of substring in the specified range. It takes
three parameters, first is a substring, second a start index and third is last
index of the range. Start and end both are optional whereas substring is required.
Signature
count(sub, start, end)
Parameters
sub (required)
start (optional)
end (optional)
Return Type
It returns number of occurrences of substring in the range.
----------------
# Python count() function example
# Variable declaration
str = "Hello python"
str2 = str.count(’o’)
# Displaying result
print("occurences:", str2)
output:
2
----------------------------------
Python String endswith() Method
Python endswith() method returns true of the string ends with the specified
substring, otherwise returns false.
Signature
endswith(suffix, start, end)
Parameters
suffix : a substring
start : start index of a range
end : last index of the range
Start and end both parameters are optional.
Return Type
It returns a boolean value either True or False.
------------------
# Python endswith() function example
# Variable declaration
str = "Hello this is python"
isends = str.endswith("on")
# Displaying result
print(isends)
output:
True
----------------------
Python String find() Method
Python find() method finds substring in the whole string and returns index of
the first match. It returns -1 if substring does not match.
Signature
find(sub, start, end)
Parameters
sub : substring
start : start index a range
end : last index of the range
Return Type
If found it returns index of the substring, otherwise -1.
---------------------
# Python find() function example
# Variable declaration
str = "Weltcome to the python"
# Calling function
str2 = str.find("to")
# Displaying result
print(str2)
output:
9
--------------------------------
Python String format() Method
Python format() method is used to perform format operations on string. While
formatting string a delimiter {} (braces) is used to replace it with the value.
This delimeter either can contain index or positional argument.
Signature
format(*args, **kwargs)
Parameters
*args : substring
**kwargs : start index a range
Return Type
It returns a formatted string.
-----------------
# Python format() function example
# Variable declaration
str = "Java"
str2 = "C#"
# Calling function
str3 = "{} and {} both are programming languages".format(str,str2)
# Displaying result
print(str3)
output:
Java and C# both are programming languages
--------------------------
Python String index() Method
Python index() method is same as the find() method
except it returns error on failure.
This method returns index of
first occurred substring and an error if there is no
match found.
Signature
index(sub, start, end)
Parameters
sub : substring
start : start index a range
end : last index of the range
Return Type
If found it returns an index of the substring, otherwise an error ValueError.
-------------------
# Python index() function example
# Variable declaration
str = "Welcome to the python"
# Calling function
str2 = str.index("py")
# Displaying result
print(str2)
output:
15
----------------------------------------
Python String isalnum() Method
Python isalnum() method checks whether the all characters of the string is
alphanumeric or not. A character which is either a letter or a number is known
as alphanumeric. It does not allow special chars even spaces.
Signature
isalnum()
Parameters
No parameter is required.
Return
It returns either True or False.
-----------
# Python isalnum() function example
# Variable declaration
str = "Welcome"
# Calling function
str2 = str.isalnum()
# Displaying result
print(str2)
output:
True
#-------------------------------
Python String isalpha() Method
Python isalpha() method returns true if all characters in the string are alphabetic. It returns False if the
characters are not alphabetic. It returns either True or False.
Signature
isalpha()
Parameters
No parameter is required.
Return
It returns either True or False
------------------------
# Python isalpha() method example
# Variable declaration
str = "python"
# Calling function
str2 = str.isalpha()
# Displaying result
print(str2)
output:
True
--------------------------------
Python String isdigit() Method
Python isdigit() method returns True if all the characters in the string are digits.
It returns False if no character
is digit in the string.
Signature
isdigit()
Parameters
No parameter is required.
Return
It returns either True or False.
-----------------
# Python isdigit() method example
# Variable declaration
str = ’12345’
# Calling function
str2 = str.isdigit()
# Displaying result
print(str2)
output:
True
---------------------------
Python String islower() Method
Python string islower() method returns True if all characters in the string are
in lowercase.
It returns False if not in lowercase.
Signature
islower()
Parameters
No parameter is required.
Return
It returns either True or False.
-------------------
# Python islower() method example
# Variable declaration
str = "python"
# Calling function
str2 = str.islower()
# Displaying result
print(str2)
output:
True
#-----------------------------
Python String isupper() Method
Python isupper() method returns True if all characters in the string are in uppercase.
It returns False if characters are not in uppercase.
Signature
isupper()
Parameters
No parameter is required.
Return
It returns either True or False.
---------------
# Python isupper() method example
# Variable declaration
str = "WELCOME TO PYTHON"
# Calling function
str2 = str.isupper()
# Displaying result
print(str2)
output:
True
----------------------
Python String isspace() Method
Python isspace() method is used to check space in the string. It returna true if
there are only whitespace characters in the string. Otherwise it returns false.
Space, newline, and tabs etc are known as whitespace characters and are defined
in the Unicode character database as Other or Separator.
Signature
isspace()
Parameters
No parameter is required.
Return
It returns either True or False.
-----------------
# Python isspace() method example
# Variable declaration
str = " " # empty string
# Calling function
str2 = str.isspace()
# Displaying result
print(str2)
output:
True
#------------------------------------
Python String istitle() Method
Python istitle() method returns True if the string is a titlecased string. Otherwise
returns False.
Signature
istitle()
Parameters
No parameter is required.
Return
It returns either True or False.
-------------
# Python istitle() method example
# Variable declaration
str = "Welcome To Python"
# Calling function
str2 = str.istitle()
# Displaying result
print(str2)
output:
True
#------------------------
Python String lower() Method
Python lower() method returns a copy of the string after converting all the characters into lowercase.
Signature
lower()
Parameters
No parameter.
Return
It returns a lowercase string.
------------------
# Python lower() method example
# Variable declaration
str = "Python"
# Calling function
str = str.lower()
# Displaying result
print(str)
output:
python
-----------------------------------
Python String lstrip() Method
Python lstrip() method is used to remove all leading characters from the string. It takes a char type
parameter
which is optional. If parameter is not provided, it removes all the leading spaces from the string.
Signature
lstrip([chars])
Parameters
chars (optional) : A list of chars
Return
It returns a string.
-------------------
# Python lstrip() method example
# Variable declaration
str = " python "
# Calling function
str2 = str.lstrip()
# Displaying result
print(str)
print(str2)
------------------------------
Python String replace() Method
Return a copy of the string with all occurrences of substring old replaced by new.
If the optional argument count is given, only the first count occurrences are replaced.
Signature
replace(old, new)
Parameters
old : An old string which will be replaced.
output:
Old String:
Java is a programming language
New String:
C is a programming language
#----------------------------------
Python String rstrip() Method
Python rstrip() method removes all the trailing characters from the string. It means
it removes all the specified characters from right side of the string. If we don’t
specify the parameter, It removes all the whitespaces from the
string. This method returns a string value.
Signature
rstrip([chars])
Parameters
chars: character to be removed from the string.
Return
It returns string.
---------------------
# Python rstrip() method example
# Variable declaration
str = "Java and C# "
# Calling function
str2 = str.rstrip()
# Displaying result
print("Old string: ",str)
print("New String: ",str2)
---------------------------------
Python String split() Method
Python split() method splits the string into a comma separated list. It separates
string based on the separator delimiter. This method takes two parameters and both
are optional. It is described below.
Signature
split(sep=None)
Parameters
sep: A string parameter acts as a seperator.
------------------
# Python split() method example
# Variable declaration
str = "Java is a programming language"
# Calling function
str2 = str.split(" ")
# Displaying result
print(str)
print(str2)
output:
Java is a programming language
[’Java’, ’is’, ’a’, ’programming’, ’language’]
#-------------------------------------------
Python String startswith() Method
Python startswith() method returns either True or False. It returns True if the
string starts with the prefix, otherwise False. It takes two parameters start and
end. Start is a starting index from where searching starts and end index is where
searching stops.
Signature
startswith(prefix, start, end)
Parameters
prefix : A string which is to be checked.
Return
It returns boolean value either True or False.
--------------
# Python String startswith() method
# Declaring variable
str = "Hello Python"
# Calling function
str2 = str.startswith("Hello")
# Displaying result
print (str2)
output:
True
#-----------------------------------
Signature
swapcase()
Parameters
No Parameter
Return
It returns a string.
----------------
# Python String swapcase() method
# Declaring variable
str = "Hello Python"
# Calling function
str2 = str.swapcase()
# Displaying result
print (str2)
output:
hELLO pYTHON
#---------------------------------
title() It is used to convert the string into the title-case i.e., The string meEruT
will be converted to Meerut.
# Declaring table and variables
str = "Hello python"
# Calling function
str2 = str.title()
# Displaying result
print(str2)
output:
Hello Python
#----------------------------------------
Python String upper() Method
Python upper() method converts all the character to uppercase and returns a uppercase
string.
Signature
upper()
Parameters
No parameters
Return
It returns a string.
--------------------------
# Python upper() method
# Declaring table and variables
str = "Hello python"
# Calling function
str2 = str.upper()
# Displaying result
print(str2)
output:
HELLO PYTHON
#--------------------------------------
#*************************************
#--------------------------------------
Python Lists
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data,
the other 3 are Tuple,
Set, and Dictionary, all with different qualities and usage.
#--------------------------
Create a List:
output:
[’apple’, ’banana’, ’cherry’]
#-------------------------
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second
item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have
a defined order, and that order will
not change.
If you add new items to a list, the new items will be placed at
the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove
items in a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
#----------------------------------------------------
Lists allow duplicate values:
output:
3
#-----------------------------------------------------
List Items - Data Types
List items can be of any data type:
String, int and boolean data types:
print(list1)
print(list2)
print(list3)
output:
[’apple’, ’banana’, ’cherry’]
[1, 5, 7, 9, 3]
[True, False, False]
#-----------------------
A list can contain different data types:
A list with strings, integers and boolean values:
output:
[’abc’, 34, True, 40, ’male’]
#---------------------
type()
From Python’s perspective, lists are defined as objects with the
data type ’list’:
<class ’list’>
data type of a list?
-------------------------
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
output:
<class ’list’>
#---------------------------------------------------------------
The list() Constructor
It is also possible to use the list() constructor when creating a
new list. Using the list() constructor to make a List:
output:
[’apple’, ’banana’, ’cherry’]
[’apple’, ’banana’, ’cherry’]
#----------------------------------------------------
Python - Access List Items
Access Items
List items are indexed and you can access them by referring to the index number:
Print the second item of the list:
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
output:
cherry
#----------------------------------------------------
Python - Access List Items
Access Items
List items are indexed and you can access them by referring to
the index number:
Print the second item of the list:
output:
[’orange’, ’kiwi’, ’melon’]
#--------------------------------------------------------
Check if Item Exists
To determine if a specified item is present in a list use the in keyword:
output:
[’apple’, ’blackcurrant’, ’cherry’]
#----------------------------------------
Change a Range of Item Values
To change the value of items within a specific range, define a list with the new values, and refer to the
range of
index numbers
where you want to insert the new values:
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
output:
[’apple’, ’blackcurrant’, ’watermelon’, ’cherry’]
#-----------------------------------------------------
Note: The length of the list will change when the number of
items inserted does not match the number
of items replaced.
If you insert less items than you replace, the new items will
be inserted where you specified, and the remaining items will
move accordingly:
Change the second and third value by replacing it with one value:
output:
[’apple’, ’watermelon’]
#------------------------------------------------------------
Insert Items
To insert a new list item, without replacing any of the existing
values, we can use the insert() method.
output:
[’apple’, ’banana’, ’watermelon’, ’cherry’]
#------------------------------------------------------------------------
Python - Add List Items
Append Items
To add an item to the end of the list, use the append() method:
Using the append() method to append an item:
output:
[’apple’, ’banana’, ’cherry’, ’orange’]
#--------------------------------------------------
Insert Items
To insert a list item at a specified index, use the insert() method.
output:
[’apple’, ’orange’, ’banana’, ’cherry’]
-----------------------------
thislist = ["apple", "banana", "cherry"]
pk=["jackfruit",’Mango’]
thislist.insert(1, pk)
print(thislist)
output:
[’apple’, [’jackfruit’, ’Mango’], ’banana’, ’cherry’]
#------------------------------------------------------------
Extend List
To append elements from another list to the current list, use
the extend() method.
Add the elements of tropical to thislist:
output:
[’apple’, ’banana’, ’cherry’, ’mango’, ’pineapple’, ’papaya’]
output:
[’apple’, ’banana’, ’cherry’, ’kiwi’, ’orange’]
#-----------------------------------------------
Python - Remove List Items
Remove Specified Item
The remove() method removes the specified item.
Remove "banana":
output:
[’apple’, ’cherry’]
#---------------------------------------------
Remove Specified Index
The pop() method removes the specified index.
Remove the second item:
output:
[’apple’, ’cherry’]
output:
[’apple’, ’banana’]
#---------------------------------------------------------
The del keyword also removes the specified index:
Remove the first item:
output:
[’banana’, ’cherry’]
#-------------------------------------------------
The del keyword can also delete the list completely.
Delete the entire list:
output:
[’apple’, ’banana’, ’cherry’]
[]
#----------------------------------------
Python - Loop Lists
Loop Through a List
You can loop through the list items by using a for loop:
Print all items in the list, one by one:
output:
apple
banana
cherry
#-----------------------------------------------------
Loop Through the Index Numbers
You can also loop through the list items by referring to their
index number.
output:
apple
banana
cherry
#------------------------------------------------------------
Using a While Loop
You can loop through the list items by using a while loop.
Use the len() function to determine the length of the list, then start at 0 and loop your way through the list
items by refering to their indexes.
Print all items, using a while loop to go through all the index numbers
output:
apple
banana
cherry
#----------------------------------------------------------------------
Python - Sort Lists
Sort List Alphanumerically
List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:
Sort the list alphabetically:
output:
[’banana’, ’kiwi’, ’mango’, ’orange’, ’pineapple’]
#--------------------------------------------------------
Sort the list numerically:
output:
[23, 50, 65, 82, 100]
#-----------------------------------
Sort Descending
To sort descending, use the keyword argument reverse = True:
Sort the list descending:
output:
[100, 82, 65, 50, 23]
#----------------------------------------
Reverse Order
What if you want to reverse the order of a list, regardless of
the alphabet?
The reverse() method reverses the current sorting order of the elements.
Reverse the order of the list items:
output:
[’cherry’, ’Kiwi’, ’Orange’, ’banana’]
#---------------------------------------------------------------------
Python - Copy Lists
Copy a List
You cannot copy a list simply by typing list2 = list1, because:
list2 will only be a reference to list1,
and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Make a copy of a list with the copy() method:
output:
[’apple’, ’banana’, ’cherry’]
#-------------------------------------------------
Another way to make a copy is to use the built-in method list().
Make a copy of a list with the list() method:
output:
[’apple’, ’banana’, ’cherry’]
#-------------------------------------------------
Python - Join Lists
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
output:
[’a’, ’b’, ’c’, 1, 2, 3]
#---------------------------------------------------
Another way to join two lists is by appending all the items from list2 into list1, one by one:
Append list2 into list1:
output:
[’a’, ’b’, ’c’, 1, 2, 3]
#-------------------------------------------------------
Or you can use the extend() method, which purpose is to add
elements from one list to another list:
Use the extend() method to add list2 at the end of list1:
list1.extend(list2)
print(list1)
output:
[’a’, ’b’, ’c’, 1, 2, 3]
#-----------------------------------------------
Python - List Comprehension
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.
Without list comprehension you will have to write a for statement with a conditional test inside:
----------------------------------
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
output:
[’apple’, ’banana’, ’mango’]
#------------------------------------------------------------
With list comprehension you can do all that with only one line of code:
print(newlist)
output:
[’apple’, ’banana’, ’mango’]
#----------------------------------------------------------
The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that only accepts the items that valuate to True.
print(newlist)
output:
[’banana’, ’cherry’, ’kiwi’, ’mango’]
------------------------------
The condition if x != "apple" will return True for all elements other than "apple", making the new list
contain
all fruits except "apple".
print(newlist)
output:
[’apple’, ’banana’, ’cherry’, ’kiwi’, ’mango’]
#--------------------------------------------------------
Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
You can use the range() function to create an iterable:
newlist = [x for x in range(10)]
print(newlist)
output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#--------------------------------------------------------------
Accept only numbers lower than 5:
newlist = [x for x in range(10) if x < 5]
print(newlist)
output:
[0, 1, 2, 3, 4]
#-------------------------------------------
Expression
The expression is the current item in the iteration, but it is also the outcome, which you can manipulate
before
it ends up like a list item in the new list:
print(newlist)
output:
[’APPLE’, ’BANANA’, ’CHERRY’, ’KIWI’, ’MANGO’]
#---------------------------------------------------------------
Set all values in the new list to ’hello’:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
output:
[’hello’, ’hello’, ’hello’, ’hello’, ’hello’]
#------------------------------------------------------------
#***************************************************************************
#---------------------------------------------------------------------------
Python Tuples
Tuple
Tuples are used to store multiple items in a single
variable.
output:
(’apple’, ’banana’, ’cherry’)
#---------------------------------------------------
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate
values.
Tuple items are indexed, the first item has index [0],
the second item has index [1] etc.
Ordered:
When we say that tuples are ordered, it means that the
items have a defined order, and that order
will not change.
Unchangeable:
Tuples are unchangeable, meaning that we cannot change,
add or remove items after the tuple has been created.
Allow Duplicates:
Since tuples are indexed, they can have items with the
same value:
#-------------------------------------------------------------
#Tuples allow duplicate values:
output:
(’apple’, ’banana’, ’cherry’, ’apple’, ’cherry’)
#-------------------------------------------------------------
Tuple Length
To determine how many items a tuple has, use the len()
function:
output:
3
#----------------------------------------------------------
Create Tuple With One Item
To create a tuple with only one item, you have to add a
comma after the item,
otherwise Python will not recognize it as a tuple.
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
output:
<class ’tuple’>
<class ’str’>
#-------------------------------
Tuple Items - Data Types
Tuple items can be of any data type:
print(tuple1)
print(tuple2)
print(tuple3)
#--------------------------------------------------------
type()
From Python’s perspective, tuples are defined as objects
with the data type ’tuple’:
<class ’tuple’>
What is the data type of a tuple?
-------------------------------------
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
output:
<class ’tuple’>
#---------------------------------------------------------------------------
The tuple() Constructor
It is also possible to use the tuple() constructor to
make a tuple.
Using the tuple() method to make a tuple:
output:
(’apple’, ’banana’, ’cherry’)
(’apple’, ’banana’, ’cherry’)
#--------------------------------------------------------------------------
Access Tuple Items
You can access tuple items by referring to the index
number, inside square brackets:
Print the second item in the tuple:
output:
banana
output:
cherry
#---------------------------------------------------------------------
Range of Indexes
You can specify a range of indexes by specifying where
to start and where to end the range.
output:
(’cherry’, ’orange’, ’kiwi’)
output:
(’apple’, ’banana’, ’cherry’, ’orange’)
#---------------------------------------------------------------------
By leaving out the end value, the range will go on to
the end of the list:
returns the items from "cherry" and to the end:
output:
(’cherry’, ’orange’, ’kiwi’, ’melon’, ’mango’)
#-----------------------------------------------------------------------
Range of Negative Indexes
Specify negative indexes if you want to start the search
from the end of the tuple:
returns the items from index -4 (included) to index
-1 (excluded)
output:
(’orange’, ’kiwi’, ’melon’)
#------------------------------------------------------------------------
Check if Item Exists
To determine if a specified item is present in a tuple
use the in keyword:
output:
Yes, ’apple’ is in the fruits tuple
#---------------------------------------------------------------------
Update Tuples
Tuples are unchangeable, meaning that you cannot change,
add, or remove items once the tuple
is created.
output:
(’apple’, ’kiwi’, ’cherry’)
#-------------------------------------------------------------------------------
Add Items
Since tuples are immutable, they do not have a build-in
append() method, but there are
other ways to add items to a tuple.
Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
print(thistuple)
output:
(’apple’, ’banana’, ’cherry’, ’orange’)
#---------------------------------------------------------------------------------------------------
2. Add tuple to a tuple. You are allowed to add tuples
to tuples, so if you want to add one item, (or many),
create a new tuple with the item(s), and add it to the
existing tuple:
Create a new tuple with the value "orange", and add
that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
output:
(’apple’, ’banana’, ’cherry’, ’orange’)
#---------------------------------------------------------------------------------------
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items
from it, but you can use the same workaround as
we used for changing and adding tuple items:
Convert the tuple into a list, remove "apple", and
convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
print(thistuple)
output:
(’banana’, ’cherry’)
#-----------------------------------------------------------------------------
can delete the tuple completely:
The del keyword can delete the tuple completely:
Packing a tuple:
output:
(’apple’, ’banana’, ’cherry’)
#--------------------------------------------------------------------------------------
But, in Python, we are also allowed to extract the values
back into variables. This is called
"unpacking":
Unpacking a tuple:
----------------------------
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
output:
apple
banana
cherry
-----------------------------------
Note: The number of variables must match the number
of values in the tuple, if not,
you must use an asterisk to collect the remaining
values as a list.
#------------------------------------------------------------------------------------
Using Asterisk*
If the number of variables is less than the number of
values, you can add an * to the
variable name and the values will be assigned to the
variable as a list:
Assign the rest of the values as a list called "red":
-----------------------
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
output:
apple
banana
[’cherry’, ’strawberry’, ’raspberry’]
#------------------------------------------------------------------------------
If the asterisk is added to another variable name than
the last, Python will assign values to
the variable until the number of values left matches
the number of variables left.
output:
apple
[’mango’, ’papaya’, ’pineapple’]
cherry
#-----------------------------------------------------------------------------
Loop Through a Tuple
You can loop through the tuple items by using a for loop.
Iterate through the items and print the values:
output:
apple
banana
cherry
#-------------------------------------------------------------------------------
Loop Through the Index Numbers
You can also loop through the tuple items by referring
to their index number.
output:
apple
banana
cherry
#-----------------------------------------------------------------------------
Using a While Loop
You can loop through the list items by using a while loop.
output:
apple
banana
cherry
#--------------------------------------------------------------------------------
Python - Join Tuples
Join Two Tuples
To join two or more tuples you can use the + operator:
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
output:
(’a’, ’b’, ’c’, 1, 2, 3)
#--------------------------------------------------------------------------
Multiply Tuples
If you want to multiply the content of a tuple a given
number of times, you can use
the * operator:
Multiply the fruits tuple by 2:
output:
(’apple’, ’banana’, ’cherry’, ’apple’, ’banana’, ’cherry’)
#-------------------------------------------------------------------------------------------
Python - Tuple Methods
Python Tuple count() Method
Return the number of times the value 5 appears in
the tuple:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
print(x)
output:
2
#-------------------------------------------------------------------------
Python Tuple index() Method
Search for the first occurrence of the value 8, and return its position:
thistuple = (10, 30, 70, 80, 70, 50, 40, 60, 80, 50)
x = thistuple.index(80)
print(x)
output:
3
#------------------------------------------------------------------------
#*****************************************************
#---------------------------------------------------------
Python Sets
Set
Sets are used to store multiple items in a single variable.
* Note: Set items are unchangeable, but you can remove items and add new items
Sets are written with curly brackets.
#--------------------------------------------------------------------------------
Create a Set:
output:
{’apple’, ’banana’, ’cherry’}
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
#--------------------------------------------------------------------------
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by index or
key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been created.
Once a set is created, you cannot change its items, but you can remove items and add new items.
#-----------------------------------------------------------
Get the Length of a Set
To determine how many items a set has, use the len() function.
Get the number of items in a set:
print(len(thisset))
output:
3
#---------------------------------------------------------------------
Set Items - Data Types
Set items can be of any data type:
String, int and boolean data types:
---------------------
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1)
print(set2)
print(set3)
output:
{’banana’, ’apple’, ’cherry’}
{1, 3, 5, 7, 9}
{False, True}
#----------------------------------------------------------
A set can contain different data types:
A set with strings, integers and boolean values:
output:
{True, 34, 40, ’abc’, ’male’}
#---------------------------------------------------------------
type()
From Python’s perspective, sets are defined as objects with the data type ’set’:
<class ’set’>
What is the data type of a set?
--------------------
myset = {"apple", "banana", "cherry"}
print(type(myset))
output:
<class ’set’>
#------------------------------------------------------------------
The set() Constructor
It is also possible to use the set() constructor to make a set.
Using the set() constructor to make a set:
---------------------
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
output:
{’apple’, ’banana’, ’cherry’}
#-----------------------------------------------------------------------------
Python - Access Set Items
Access Items
You cannot access items in a set by referring to an
index or a key.
But you can loop through the set items using a for
loop, or ask if a specified value is present in a set,
by using the in keyword.
output:
banana
apple
cherry
#----------------------------------------------------------------------------
Check if "banana" is present in the set:
-------------------
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
output:
True
------------------------
Change Items
Once a set is created, you cannot change its items,
but you can add new items.
#---------------------------------------------------------------------------------
Python - Add Set Items
Add Items
Once a set is created, you cannot change its items,
but you can add new items.
output:
{’pineapple’, ’cherry’, ’banana’, ’mango’, ’papaya’, ’apple’}
#-------------------------------------------------------------------
Add Any Iterable
The object in the update() method does not have to be
a set, it can be any iterable object
(tuples, lists, dictionaries etc.).
Add elements of a list to at set:
-------------------------
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
output:
{’apple’, ’banana’, ’cherry’, ’kiwi’, ’orange’}
#----------------------------------------------------------------
Python - Remove Set Items
Remove Item
To remove an item in a set, use the remove(), or the
discard() method.
Remove "banana" by using the remove() method:
-------------------
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
output:
{’cherry’, ’apple’}
----------------------
Note: If the item to remove does not exist, remove()
will raise an error.
#------------------------------------------------------------------
Remove "banana" by using the discard() method:
------------------
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
output:
{’apple’, ’cherry’}
-----------------
-----------------------
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
output:
cherry
{’banana’, ’apple’}
---------------
Note: Sets are unordered, so when using the pop() method, you do not know which item that gets
removed.
#----------------------------------------------------------------------------------
The clear() method empties the set:
output:
set()
#--------------------------------------------------------
The del keyword will delete the set completely:
#-----------------------------------------------------------------
Join Two Sets
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both sets
The union() method returns a new set with all items from both sets:
#------------------------------------------------------------------
The update() method inserts the items in set2 into set1:
output:
{’c’, 1, 2, 3, ’a’, ’b’}
#---------------------------------------------------------
Python Set Operations
Set can be performed mathematical operation such as union, intersection, difference, and symmetric
difference.
Python provides the facility to carry out these operations with operators or methods.
output:
{’Wednesday’, ’Tuesday’, ’Thursday’, ’Saturday’, ’Friday’, ’Monday’, ’Sunday’}
-------------------
Python also provides the union() method which can also be used to calculate the union of two sets.
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1.union(Days2)) #printing the union of the sets
output:
{’Tuesday’, ’Wednesday’, ’Sunday’, ’Friday’, ’Saturday’, ’Monday’, ’Thursday’}
#---------------------------------------------------------------------
Intersection of two sets
The intersection of two sets can be performed by the and & operator or the intersection() function.
The intersection of the two sets is given as the set of the elements that common in both sets.
output:
{’Tuesday’, ’Monday’}
---------------------
2: Using intersection() method
output:
{’Martin’, ’David’}
#--------------------------------------------------------------
Difference between the two sets
The difference of two sets can be calculated by using the subtraction (-) operator or intersection()
method.
Suppose there are two sets A and B, and the difference is A-B that denotes the resulting set will be
obtained that element of A, which is not present in the set B.
output:
{’Wednesday’, ’Thursday’}
---------------
2 : Using difference() method
----------------------------
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2
output:
{’Wednesday’, ’Thursday’}
#-----------------------------------------------------------------------------------------
Symmetric Difference of two sets
The symmetric difference of two sets is calculated by ^ operator or symmetric_difference() method.
Symmetric difference of sets, it removes that element which is present in both sets.
1: Using ^ operator
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a^b
print(c)
output:
{3, 4, 5, 6, 8, 9, 10}
------------------------
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a.symmetric_difference(b)
print(c)
output:
{3, 4, 5, 6, 8, 9, 10}
#------------------------------------------------------------------------------
Set comparisons
Python allows us to use the comparison operators i.e.,
<, >, <=, >= , == with the sets by using which we can
check whether a set is a subset, superset, or equivalent
to other set. The boolean true or false
is returned depending upon the items present inside
the sets.
------------------
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
#Days1 is the superset of Days2 hence it will print true.
print (Days1>Days2)
output:
True
False
False
#----------------------------------------------------------------------
Python Set issubset() Method
Return True if all items in set x are present in set y:
output:
True
#---------------------------------------------------------------------
Python Set issuperset() Method
Return True if all items set y are present in set x:
output:
{’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 1964}
#-----------------------------------------------
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
#--------------------------------------------------------------------------------------------
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
output:
Ford
#-----------------------------------------------------------------
Ordered or Unordered?
When we say that dictionaries are ordered, it means that the items have a defined order,
and that order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an
item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
output:
{’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 2020}
#---------------------------------------------------------------------------------
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Print the number of items in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))
output:
3
#-----------------------------------------------
Dictionary Items - Data Types
The values in dictionary items can be of any data type:
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(thisdict)
output:
{’brand’: ’Ford’, ’electric’: False, ’year’: 1964, ’colors’: [’red’, ’white’, ’blue’]}
#-------------------------------------------------------------------------------
type()
From Python’s perspective, dictionaries are defined as objects with the data type ’dict’:
<class ’dict’>
Print the data type of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
output:
<class ’dict’>
#------------------------------------------------------------------
Python - Access Dictionary Items
Accessing Items
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
output:
Mustang
#--------------------------------------------------------------
There is also a method called get() that will give you the same result:
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model")
print(x)
output:
Mustang
#---------------------------------------------------------------
Get Keys
The keys() method will return a list of all the keys in the
dictionary.
Get a list of the keys:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)
output:
dict_keys([’brand’, ’model’, ’year’])
#------------------------------------------------------------
Add a new item to the original dictionary, and see that
the keys list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
output:
dict_keys([’brand’, ’model’, ’year’])
dict_keys([’brand’, ’model’, ’year’, ’color’])
#-------------------------------------------------------------------
Get Values
The values() method will return a list of all the values
in the dictionary.
Get a list of the values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.values()
print(x)
output:
dict_values([’Ford’, ’Mustang’, 1964])
#--------------------------------------------------------------
Make a change in the original dictionary, and see that
the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
output:
dict_values([’Ford’, ’Mustang’, 1964])
dict_values([’Ford’, ’Mustang’, 2020])
#------------------------------------------------------------------------
output:
dict_values([’Ford’, ’Mustang’, 1964])
dict_values([’Ford’, ’Mustang’, 1964, ’red’])
#----------------------------------------------------------------------
Get Items
The items() method will return each item in a dictionary,
as tuples in a list
Get a list of the key:value pairs
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.items()
print(x)
output:
dict_items([(’brand’, ’Ford’), (’model’, ’Mustang’), (’year’, 1964)])
#---------------------------------------------------------------------------
Make a change in the original dictionary, and see that the
items list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
output:
dict_items([(’brand’, ’Ford’), (’model’, ’Mustang’), (’year’, 1964)])
dict_items([(’brand’, ’Ford’), (’model’, ’Mustang’), (’year’, 2020)])
#---------------------------------------------------
Add a new item to the original dictionary, and see that
the items list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
output:
dict_items([(’brand’, ’Ford’), (’model’, ’Mustang’), (’year’, 1964)])
dict_items([(’brand’, ’Ford’), (’model’, ’Mustang’), (’year’, 1964), (’color’, ’red’)])
#------------------------------------------------------------------------------
Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword:
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, ’model’ is one of the keys in the thisdict dictionary")
#-------------------------------------------------------------------------------
Change Values
You can change the value of a specific item by referring to its key name:
Change the "year" to 2018:
------------------
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
output:
{’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 2018}
#----------------------------------------------------------------------------
Update Dictionary
The update() method will update the dictionary with the
items from the given argument.
output:
{’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 1964, ’color’: ’red’}
#-------------------------------------------------------------------
Update Dictionary
The update() method will update the dictionary with the items from a given argument. If the item does not
exist,
the item will be added.
output:
{’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 1964, ’color’: ’red’}
#-------------------------------------------------------------------------------------
Python - Remove Dictionary Items
Removing Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key name:
----------------------
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
output:
{’brand’: ’Ford’, ’year’: 1964}
#-----------------------------------------------------------------------------
The popitem() method removes the last inserted item
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
output:
{’brand’: ’Ford’, ’model’: ’Mustang’}
#-----------------------------------------------------------
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
output:
{’brand’: ’Ford’, ’year’: 1964}
#-------------------------------------------------------------------------
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because
"thisdict" no longer exists.
#------------------------------------------------------------------------------------
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
output:
{}
#--------------------------------------------------
Python - Loop Dictionaries
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
output:
brand
model
year
#-----------------------------------------------------------------
Print all values in the dictionary, one by one:
----------------
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
output:
Ford
Mustang
1964
-----------------------
output:
Ford
Mustang
1964
#----------------------------------------------------------------
You can use the keys() method to return the keys of a
dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.keys():
print(x)
#--------------------------------------------------------------------
Loop through both keys and values, by using the items() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in thisdict.items():
print(x, y)
output:
brand Ford
model Mustang
year 1964
#-------------------------------------------------------------------
Python - Copy Dictionaries
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and
changes made in dict1 will automatically also be made
in dict2.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
output:
{’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 1964}
#-------------------------------------------------------------------------------
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
output:
{’brand’: ’Ford’, ’model’: ’Mustang’, ’year’: 1964}
#--------------------------------------------------------------------------
Python - Nested Dictionaries
Nested Dictionaries
A dictionary can contain dictionaries, this is called
nested dictionaries.
Create a dictionary that contain three dictionaries:
--------------------
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
output:
{’child1’: {’name’: ’Emil’, ’year’: 2004}, ’child2’: {’name’: ’Tobias’, ’year’: 2007}, ’child3’: {’name’: ’Linus’,
’year’: 2011}}
#-----------------------------------------------------------------------
Create three dictionaries, then create one dictionary that
will contain the
other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)
output:
{’child1’: {’name’: ’Emil’, ’year’: 2004}, ’child2’: {’name’: ’Tobias’, ’year’: 2007}, ’child3’: {’name’: ’Linus’,
’year’: 2011}}
#--------------------------------------------------------
**********************************************
#----------------------------------------------------
Python Function
Functions are the most important aspect of an application.
A function can be defined
as the organized block of reusable
code, which can be called whenever required.
def my_function(parameters):
function_block
[return expression]
# function calling
hello()
output:
hello world...bye
-----------------------------
The return statement:
The return statement is used at the end of the function
and returns the result of the function.
It terminates the function execution and transfers the
result where the function is called.
The return statement cannot be used outside of the function.
Syntax:
return [expression_list]
output:
The sum is: 30
----------------------------------------------------
Creating function without return statement
----------
# Defining function
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())
output:
None
------------------------------
In the above code, we have defined the same function without the return statement as
we can see that
the sum() function returned the None object to the caller function.
Arguments in function
The arguments are types of information which can be passed into the function.
The arguments are
specified in the parentheses. We can pass any number of arguments, but they must
be separate them with a comma.
-------------------
# Python function to calculate the sum of two variables
# defining the function
def sum(a, b):
return a + b
output:
Enter a: 20
Enter b: 30
Sum = 50
-----------------------------------------------------
Passing mutable Object (List)
# defining the function
def change_list(list1):
list1.append(20)
list1.append(30)
print("list inside function = ", list1)
output:
list inside function = [10, 30, 40, 50, 20, 30]
list outside function = [10, 30, 40, 50, 20, 30]
------------------------------------------------------
Passing Imutable Object (String)
------------
# defining the function
def change_string(str):
str = str + " Hows you "
print("printing the string inside function :", str)
output:
printing the string inside function : Hi I am there Hows you
printing the string outside function : Hi I am there
#----------------------------------------------------------
Types of arguments
There may be several types of arguments which can be passed
at the time of function call.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
We can provide the arguments at the time of the function
call. As far as the required arguments are concerned,
these are the arguments which are required to be passed
at the time of function calling with the exact match of
their positions in the function call and function
definition. If either of the arguments is not provided
in the function call, or the position of the arguments
is changed, the Python interpreter
will show the error.
#---------------------------------------------------------------------
1. Required arguments
def func(name):
message= "Hi "+name
return message
output:
Enter name:Amal
Hi Amal
#-----------------------------------------------------------
#the function simple_interest accepts three arguments and
returns the simple interest accordingly
------------
def simple_interest(p,t,r):
return (p*t*r)/100
output:
Enter the principle amount:10000
Enter the rate of interest:7
Enter the time in years:5
Simple Interest: 3500.0
#-----------------------------------------------------
#the function calculate returns the sum of two arguments a
and b
---------------------
def calculate(a,b):
return a+b
print(calculate(3,5))
print(calculate(10)) # error
# this causes an error as we are missing a required arguments b.
#-----------------------------------------------------------------
Default Arguments
Python allows us to initialize the arguments at the
function definition. If the value of any of the
arguments is not provided at the time of function call,
then that argument can be initialized with the value
given in the definition even if the argument is not
specified at the function call.
#--------------------------------------------------------
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john") #the variable age is not passed
output:
My name is john and age is 22
--------------------------
into the function however the default
value of age is considered in the function
printme(age = 10,name="David") #the value of age
is overwritten here, 10 will be printed as age
#-----------------------------------------------------------------------------
Variable-length Arguments (*args)
In large projects, sometimes we may not know the number
of arguments to be passed in advance. In such cases,
Python provides us the flexibility to offer the
comma-separated values which are internally treated
as tuples at the function call.
By using the variable-length arguments, we can pass
any number of arguments.
printme("john","David","smith","nick")
printme(10,20)
output:
john
David
smith
nick
10
20
#----------------------------------------------------------------------------------------------
In the above code, we passed *names as variable-length
argument. We called the function and passed values
which are treated as tuple internally. The tuple is an
iterable sequence the same as the list. To print the
given values, we iterated *arg names using for loop.
#-------------------------------------------------
Keyword arguments(**kwargs)
Python allows us to call the function with the keyword
arguments. This kind of function call will enable us
to pass the arguments in the random order.
def func(name,message):
print("printing the message with",name,"and ",message)
#name and message is copied with the values John and hello respectively
func(name = "John",message="hello")
output:
printing the message with John and hello
#---------------------------------------------------------------
Providing the values in different order at the calling
------------
#The function simple_interest(p, t, r) is called with the keyword arguments the order
of arguments doesn’t matter in this case
def simple_interest(p,t,r):
return (p*t*r)/100
output:
Amt: 8750.0
-----------------------
# doesn’t find the exact match of the name of the arguments (keywords)
print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900))
#----------------------------------------------------------------------------
The Python allows us to provide the mix of the required
arguments and keyword arguments at the time of function
call. However, the required argument must not be given
after the keyword argument,
i.e., once the keyword argument is encountered in the
function call, the following arguments must also be
the keyword arguments.
-------------------
def func(name1,message,name2):
print("printing the message with",name1,",",message,",and",name2)
#the first argument is not the keyword argument
func("John",message="hello",name2="David")
output:
printing the message with John , hello ,and David
#------------------------------------------------------------------------
The following example will cause an error due to an
in-proper mix of keyword and required arguments being
passed in the function call.
------------------------
def func(name1,message,name2):
print("printing the message with",name1,",",message,",and",name2)
func("John",message="hello","David") #error
#------------------------------------------------------------------------
Python provides the facility to pass the multiple
keyword arguments which can be represented as **kwargs.
It is similar as the *args but it stores the argument
in the dictionary format.
This type of arguments is useful when we do not know
the number of arguments in advance.
Many arguments using Keyword argument
-------------------
def food(**kwargs):
print(kwargs)
food(a="Apple")
food(fruits="Orange", Vagitables="Carrot")
output:
{’a’: ’Apple’}
{’fruits’: ’Orange’, ’Vagitables’: ’Carrot’}
#-----------------------------------------------------------------------------
Scope of variables
The scopes of the variables depend upon the location
where the variable is being declared.
The variable declared in one part of the program may
not be accessible to the other parts.
Global variables
Local variables
The variable defined outside any function is known to
have a global scope, whereas the variable defined
inside a function is known to have a local scope.
#---------------------------------------------------------------------
Local Variable
def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the function itself
print(message)
print_message()
print(message) # this will cause an error since a local
variable cannot be accessible here.
#--------------------------------------------
Global Variable
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
output:
Absolute value of -40.83 is: 40.83
#------------------------------------------------------
Python bin() Function
The python bin() function is used to return the binary
representation of a specified integer.
A result always starts with the prefix 0b.
Python bin() Function Example
-------------------------
x = 28
y = bin(x)
print (y)
output:
0b11100
#----------------------------------------------
Python sum() Function
As the name says, python sum() function is used to get
the sum of numbers of an iterable, i.e., list.
Python sum() Function Example
------------------------
s = sum([1, 2,4 ])
print(s)
s = sum([1, 2, 4], 10)
print(s)
output:
7
17
#----------------------------------------------------
Python float()
The python float() function returns a floating-point
number from a number or string.
Python float() Example
---------------
# for integers
print(float(9))
# for floats
print(float(8.19))
# integer
print(format(123, "d"))
# float arguments
print(format(123.4567898, "f"))
# binary format
print(format(12, "b"))
output:
123
123.456790
1100
#----------------------------------------------------
Python iter() Function
The python iter() function is used to return an iterator
object. It creates an object which can be
iterated one element at a time.
Python iter() Function Example
--------------------
# list of numbers
list = [1,2,3,4,5]
listIter = iter(list)
# prints ’1’
print(next(listIter))
# prints ’2’
print(next(listIter))
# prints ’3’
print(next(listIter))
# prints ’4’
print(next(listIter))
# prints ’5’
print(next(listIter))
#---------------------------------------------
Python len() Function
The python len() function is used to return the length
(the number of items) of an object.
Python len() Function Example
--------------------
strA = ’Python’
print(len(strA))
output:
6
#----------------------------------------------------------
Python list()
The python list() creates a list in python.
Python list() Example
------------
# empty list
print(list())
# string
String = ’abcde’
print(list(String))
# tuple
Tuple = (1,2,3,4,5)
print(list(Tuple))
# list
List = [1,2,3,4,5]
print(list(List))
output:
[]
[’a’, ’b’, ’c’, ’d’, ’e’]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
#---------------------------------------
Python object()
The python object() returns an empty object. It is a
base for all the classes and holds the built-in
properties and methods which are default for all the
classes.
----------------------
Python object() Example
obj = object()
print(type(obj))
print(dir(obj))
output:
<class ’object’>
[’__class__’, ’__delattr__’, ’__dir__’, ’__doc__’, ’__eq__’, ’__format__’, ’__ge__’, ’__getattribute__’,
’__gt__’, ’__hash__’, ’__init__’, ’__init_subclass__’, ’__le__’, ’__lt__’, ’__ne__’, ’__new__’, ’__reduce__’,
’__reduce_ex__’, ’__repr__’, ’__setattr__’, ’__sizeof__’, ’__str__’, ’__subclasshook__’]
#-------------------------------------------------
Python complex()
Python complex() function is used to convert numbers or
string into a complex number. This method takes two
optional parameters and returns a complex number. The
first parameter is called a real and second as imaginary
parts.
# Python complex() function example
# Calling function
a = complex(1) # Passing single parameter
b = complex(1,2) # Passing both parameters
# Displaying result
print(a)
print(b)
output:
(1+0j)
(1+2j)
#---------------------------------
Python dir() Function
Python dir() function returns the list of names in the
current local scope. If the object on which
method is called has a method named __dir__(), this
method will be called and must return the list of
attributes.
It takes a single object type argument.
output:
[’__annotations__’, ’__builtins__’, ’__cached__’,
’__doc__’, ’__file__’, ’__loader__’, ’__name__’,
’__package__’, ’__spec__’]
#----------------------------------
Python divmod() Function
Python divmod() function is used to get remainder and
quotient of two numbers. This function takes two numeric
arguments and returns a tuple. Both arguments are
required and numeric
output:
{}
{’a’: 1, ’b’: 2}
#----------------------------------
Python hash() Function
Python hash() function is used to get the hash value of
an object. Python calculates the hash value by using the
hash algorithm. The hash values are integers and used to
compare dictionary keys during a dictionary lookup. We
can hash only the types which are given below:
Hashable types: * bool * int * long * float * string * Unicode * tuple * code object.
output:
0x1
0x156
#--------------------------------------
Python id() Function
Python id() function returns the identity of an object.
This is an integer which is guaranteed to be unique.
This function takes an argument as an object and returns
a unique integer number which represents identity.
Two objects with non-overlapping lifetimes may have the
same id() value.
# Calling function
val = id("python") # string object
val2 = id(1200) # integer object
val3 = id([25,336,95,236,92,3225]) # List object
# Displaying result
print(val)
print(val2)
print(val3)
#------------------------------------
Python sorted() Function
Python sorted() function is used to sort elements. By
default, it sorts elements in an ascending order
but can be sorted in descending also. It takes four
arguments and returns a collection in sorted order.
In the case of a dictionary, it sorts only keys, not
values.
output:
[’h’, ’i’, ’n’, ’n’, ’o’, ’o’, ’p’, ’p’, ’t’, ’t’, ’y’]
#--------------------------------------------------
Python next() Function
Python next() function is used to fetch next item from
the collection. It takes two arguments, i.e.,
an iterator and a default value, and returns an element.
output:
Octal value of 10: 0o12
#----------------------------------
Python pow() Function
The python pow() function is used to compute the power
of a number. It returns x to the power of y.
If the third argument(z) is given, it returns x to the
power of y modulus z
# negative x, positive y
print(pow(-4, 2))
# negative x, negative y
print(pow(-4, -2))
#--------------------------------------------
Python print() Function
The python print() function prints the given object
to the screen or other standard output devices.
# for tuple
Tuple = (’J’, ’a’, ’v’, ’a’)
print(list(reversed(Tuple)))
# for range
Range = range(8, 12)
print(list(reversed(Range)))
# for list
List = [1, 2, 7, 5]
print(list(reversed(List)))
#--------------------------------------
Python round() Function
The python round() function rounds off the digits of a
number and returns the floating point number.
# for integers
print(round(10))
# even choice
print(round(6.6))
output:
10
11
7
#--------------------------------------------
Python str
The python str() converts a specified value into a string.
Python str() Function Example
s1="hai"
s=s1 +","+str(25)
print(s)
output:
hai,25
#------------------------------------------
Python tuple() Function
The python tuple() function is used to create a tuple
object.
#-----------------------------------------
Python Lambda Functions
Python Lambda function is known as the anonymous function
that is defined without a name. Python allows us to not
declare the function in the standard manner, i.e., by
using the def keyword. Rather, the anonymous functions
are declared by using the lambda keyword. However,
Lambda functions can accept any number of arguments,
but they can return only one value in the form of
expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
output:
15
#----------------------------------------------------------------
Lambda functions can take any number of arguments:
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
output:
30
#------------------------------------------------
Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
output:
13
#--------------------------------------------------
Why Use Lambda Functions?
The power of lambda is better shown when you use them as
an anonymous function inside another function.
def myfunc(n):
return lambda a : a * n
#------------------------------------------------------------------
Use that function definition to make a function that always
doubles the number you send in:
Example
------------
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
output:
22
#---------------------------------------------------------
Or, use the same function definition to make a function
that always triples the number you send in:
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
output:
33
#--------------------------------------------------
or, use the same function definition to make both functions, in the same program:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
#------------------------------------------------
Python Modules
A python module can be defined as a python program file
which contains a python code including python functions,
class, or variables. In other words, we can say that our
python code file saved with the extension (.py) is treated
as the module. We may have a runnable code inside the python
module.
#----------------------------
Hence, if we need to call the function displayMsg() defined in the file file.py, we have to
import that file as a module into our module as shown in the example below.
---------------
import file
name = input("Enter the name:")
file.displayMsg(name)
file.show()
output:
Enter the name:kochi
Hi kochi
show here
#---------------------------------
The from-import statement
Instead of importing the whole module into the namespace, python provides the flexibility to import only
the
specific attributes of a module. This can be done by using from? import statement. The syntax to use the
from-import
statement is given below.
from < module-name> import <name 1>, <name 2>..,<name n>
-----------------------------
Consider the following module named as calculation which contains three functions as summation,
multiplication,
and divide.
calculation.py
-----------------
#place the code in the calculation.py
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
#-----------------------------------------
Main.py:
output:
Enter the first number10
Enter the second number20
Sum = 30
#-----------------------------------------------------
The from...import statement is always better to use if we know the attributes to be imported from the
module
in advance. It doesn’t let our code to be heavier. We can also import all the attributes from a module by
using *.
output:
2022-09-17 15:54:58.143493
Date Output
The date contains year, month, day, hour, minute, second, and microsecond.
---------------------
The datetime module has many methods to return information about the date object.
Return the year and name of weekday:
----------
Creating Date Objects
To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.
-------------------
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
output:
2020-05-17 00:00:00
----------------------
The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond,
tzone),
but they are optional, and has a default value of 0
------------------------------
The strftime() Method
The datetime object has a method for formatting date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the format of the returned
string:
import datetime
x = datetime.datetime.now()
print(x.strftime("%A"))
output:
Friday
-------------------------
%w Weekday as a number 0-6, 0 is Sunday
import datetime
x = datetime.datetime.now()
print(x.strftime("%w"))
output:
5
----------------
%d Day of month 01-31 27
---------------------
%b Month name, short version Jan
----------------------
%B Month name, full version January
-------------------------
%m Month as a number 01-12 1
-------------------------
%y Year, short version, without century 23
-----------------------------------
%Y Year, full version 2023
----------------------------
%H Hour 00-23 10
-------------------------
%I Hour 00-12 05
----------------------------
%p AM/PM PM
-------------------
%M Minute 00-59 41
-------------------------
%S Second 00-59 08
-----------------------
%f Microsecond 000000-999999 548513
--------------------
%j Day number of year 001-366 365
------------------------------
%W Week number of year, Monday as the first day of week, 00-53 52
---------------------
%C Ce
--------------
Python Math Module
Python math module is defined as the most famous
mathematical functions,
which includes trigonometric functions,
representation functions, logarithmic functions, etc.
math.pow(x,y)
This method returns the power of the x corresponding
to the value of y.
If value of x is negative or y is not
integer value than it raises a ValueError.
-------------------
import math
number = math.pow(10,2)
print("The power of number:",number)
output:
The power of number: 100.0
-------------------
math.floor(x)
This method C It returns the less than or equal value
to x.
--------------
import math
number = math.floor(10.25201)
print("The floor value is:",number)
output:
The floor value is: 10
-----------------------------
math.ceil(x)
This method returns the ceil value of the x. It returns
the greater than or equal value to x.
----------------
import math
number = math.ceil(10.25201)
print("The ceil value is:",number)
output:
The ceil value is: 11
--------------------------------
math.factorial()
This method returns the factorial of the given
number x. If x is not integral,
it raises a ValueError.
-------------
import math
number = math.factorial(7)
print("The factorial of number:",number)
output:
The factorial of number: 5040
-------------------------
math.modf(x)
This method returns the fractional and integer parts
of x. It carries the sign of x is float.
import math
number = math.modf(44.5)
print("The modf of number:",number)
output:
The modf of number: (0.5, 44.0)
-------------------------------
Python has also a built-in module called math, which
extends the list of mathematical functions.
output:
8
----------------------
The math.pi constant, returns the value of PI
(3.14...):
---------------------------
import math
x = math.pi
print(x)
-------------------
Python math.fmod() Method
Return the remainder of x/y:
--------------------
# Import math Library
import math
# Return the remainder of x/y
print(math.fmod(20, 4))
print(math.fmod(20, 3))
print(math.fmod(15, 6))
print(math.fmod(-10, 3))
#print(math.fmod(0, 0)) Error, div with zero
output:
0.0
2.0
3.0
-1.0
---------------
Python math.fsum() Method
Return the sum of all items:
-----------------------
# Import math Library
import math
# Print the sum of all items
print(math.fsum([1, 2, 3, 4, 5]))
print(math.fsum([100, 400, 340, 500]))
print(math.fsum([1.7, 0.3, 1.5, 4.5]))
output:
15.0
1340.0
8.0
----------------------
Python math.gcd() Method
Find the greatest common divisor of the two integers:
-----------------------------
#Import math Library
import math
#find the the greatest common divisor of the two
integers
print (math.gcd(3, 6))
print (math.gcd(6, 12))
print (math.gcd(12, 36))
print (math.gcd(-12, -36))
print (math.gcd(5, 12))
print (math.gcd(10, 0))
print (math.gcd(0, 34))
print (math.gcd(0, 0))
output:
3
6
12
12
1
10
34
0
-----------------------
Python math.isinf() Method
Check whether a value is infinity or not:
-----------------------------
# Import math Library
import math
# Check whether the values are infinite or not
print(math.isinf(56))
print(math.isinf(-45.34))
print(math.isinf(+45.34))
print(math.isinf(math.inf))
print(math.isinf(float("nan")))
print(math.isinf(float("inf")))
print(math.isinf(float("-inf")))
print(math.isinf(-math.inf))
output:
False
False
False
True
False
True
True
True
----------------------------------
Python math.isnan() Method
Check whether a value is NaN or not:
-------------------
# Import math Library
import math
# Check whether some values are NaN or not
print (math.isnan (56))
print (math.isnan (-45.34))
print (math.isnan (+45.34))
print (math.isnan (math.inf))
print (math.isnan (float("nan")))
print (math.isnan (float("inf")))
print (math.isnan (float("-inf")))
print (math.isnan (math.nan))
output:
False
False
False
False
True
False
False
True
---------------------
Python Random Module
Python Random module is an in-built module of Python
which is used to generate random numbers. These are
pseudo-random numbers means these are not truly
random. This module can be used to perform random
actions such as generating random numbers, print
random a value for a list or string, etc.
Syntax :
randint(start, end)
# Python3 program explaining work
# of randint() function
---------------------------------
# import random module
import random
# Generates a random number between
# a given positive range
r1 = random.randint(5, 15)
print("Random number between 5 and 15 is %d" % (r1))
output:
Random number between 5 and 15 is 13
Random number between -10 and -2 is -8
-------------------------------------------------
Creating Random Floats
random.random() method is used to generate random
floats between 0.0 to 1.0
Syntax:
random.random()
# Python3 program to demonstrate
# the use of random() function .
--------------------------------
# import random
from random import random
# Prints random item
print(random())
output:
0.4981855042679951
----------------------
Shuffling List
random.shuffle() method is used to shuffle a sequence
(list). Shuffling means changing the position of the
elements of the sequence. Here, the shuffling
operation is inplace.
Syntax:
random.shuffle(sequence)
--------------------------------
# import the random module
import random
# declare a list
sample_list = [1, 2, 3, 4, 5]
print("Original list : ")
print(sample_list)
# first shuffle
random.shuffle(sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
# second shuffle
random.shuffle(sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)
---------------------------------------
Python statistics module
Python statistics module provides the functions to
mathematical statistics of numeric data.
There are some popular statistical functions defined
in this module.
mean() function
The mean() function is used to calculate the arithmetic
mean of the numbers in the list.
-------------------------------
import statistics
# list of positive integer numbers
datasets = [5, 2, 7, 4, 2, 6, 8]
x = statistics.mean(datasets)
# Printing the mean
print("Mean is :", x)
-----------------------------
median() function
The median() function is used to return the middle
value of the numeric data in the list.
-----------------------
import statistics
datasets = [4, -5, 6, 6, 9, 4, 5, -2]
# Printing median of the
# random data-set
print("Median of data-set is : % s " % (statistics.median(datasets)))
---------------------
mode() function
The mode() function returns the most common data that
occurs in the list.
-------------------------------
import statistics
# declaring a simple data-set consisting of real valued
positive integers.
dataset =[2, 4, 7, 7, 2, 2, 3, 6, 6, 8]
# Printing out the mode of given data-set
print("Calculated Mode % s" % (statistics.mode(dataset)))
-----------------------
stdev() function
The stdev() function is used to calculate the standard
deviation on a given sample which is
available in the form of the list.
----------------------------------
import statistics
# creating a simple data - set
sample = [7, 8, 9, 10, 11]
# Prints standard deviation
print("Standard Deviation of sample is % s " % (statistics.stdev(sample)))
-----------------------------------
median_low()
The median_low function is used to return the low median of numeric data in the list.
-------------------
import statistics
# simple list of a set of integers
set1 = [4, 6, 2, 5, 7, 7]
# Note: low median will always be a member of the data-set.
# Print low median of the data-set
print("Low median of data-set is % s " % (statistics.median_low(set1)))
----------------------------
median_high()
The median_high function is used to return the high median of
numeric data in the list.
import statistics
# list of set of the integers
dataset = [2, 1, 7, 6, 1, 9]
print("High median of data-set is %s " % (statistics.median_high(dataset)))
-----------------------
Python JSON
JSON is a syntax for storing and exchanging data.
import json
output:
{’name’: ’John’, ’age’: 30, ’city’: ’New York’}
30
-----------------------------
Convert from Python to JSON
If you have a Python object, you can convert it into a JSON string by using
the json.dumps() method.
Convert from Python to JSON:
-------------------
import json
# a Python object (dict):
x={
"name": "John",
"age": 30,
"city": "New York"
}
dict
list
tuple
string
int
float
True
False
None
Convert Python objects into JSON strings, and print the
values:
-------------------------
import json
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
output:
{"name": "John", "age": 30}
["apple", "bananas"]
["apple", "bananas"]
"hello"
42
31.76
true
false
-----------------
Convert a Python object containing all the legal data
types:
----------------
import json
x={
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
output:
{"name": "John", "age": 30, "married": true, "divorced": false, "children": ["Ann", "Billy"], "pets": null, "cars":
[{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}]}
---------------------------
Format the Result
The example above prints a JSON string, but it is not
very easy to read, with no indentations
and line breaks.
output:
{
"name": "John",
"age": 30,
"married": true,
"divorced": false,
"children": [
"Ann",
"Billy"
],
"pets": null,
"cars": [
{
"model": "BMW 230",
"mpg": 27.5
},
{
"model": "Ford Edge",
"mpg": 24.1
}
]
}
------------------
You can also define the separators, default value is (", " , ": "), which means
using a comma and a space
to separate each object, and a colon and a space to separate keys from values:
Use the separators parameter to change the default separator:
---------------------------
import json
x={
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
# use . and a space to separate objects, and a space, a = and a space to separate keys from their
values:
print(json.dumps(x, indent=4, separators=(". ", " = ")))
output:
{
"name" = "John".
"age" = 30.
"married" = true.
"divorced" = false.
"children" = [
"Ann".
"Billy"
].
"pets" = null.
"cars" = [
{
"model" = "BMW 230".
"mpg" = 27.5
}.
{
"model" = "Ford Edge".
"mpg" = 24.1
}
]
}
-----------------------
Order the Result
The json.dumps() method has parameters to order the keys in the result:
Use the sort_keys parameter to specify if the result should be sorted or not:
--------------------------
import json
x={
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
output:
{
"age": 30,
"cars": [
{
"model": "BMW 230",
"mpg": 27.5
},
{
"model": "Ford Edge",
"mpg": 24.1
}
],
"children": [
"Ann",
"Billy"
],
"divorced": false,
"married": true,
"name": "John",
"pets": null
}
-------------------------------
Python Exception
An exception can be defined as an unusual
condition in a program resulting in the
interruption in the flow of the program.
Common Exceptions:
Python provides the number of built-in exceptions,
but here we are describing the common standard
exceptions. A list of common exceptions that can
be thrown from a standard Python program
is given below.
output:
Enter a:5
Enter b:0
Traceback (most recent call last):
File "F:\DATASCIENCE\PROJECTS\MLProjects\TestWorks.py", line 4, in <module>
c = a/b
ZeroDivisionError: division by zero
#--------------------------------
The above program is syntactically correct, but it
through the error because of unusual input. That
kind of programming may not be suitable or
recommended for the projects because these
projects are required uninterrupted execution.
That’s why an exception-handling plays an essential
role in handling these unexpected exceptions.
-------------------------------------------------------------------------------
The try-except statement:
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
-----------------
#Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("result:",c)
print("hi..")
except:
print("Can’t divide with zero")
print("outside exception")
output:
Enter a:5
Enter b:0
Can’t divide with zero
outside exception
--------------------------------
We can also use the else statement with the try-except statement
in which, we can place the code which will be executed in the
scenario if no exception occurs in the try block.
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
...
else:
#this code executes if no except block is executed
--------------------
#Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" % c)
# Using Exception with except statement. If we print(Exception) it will return exception class
except Exception:
print("can’t divide by zero")
print(Exception)
else:
print("Hi I am else block")
print("outside exception")
output:
Enter a:5
Enter b:0
can’t divide by zero
<class ’Exception’>
outside exception
------------------------------------
The except statement with no exception
Python provides the flexibility not to specify the name of exception
with the exception statement.
-----------------
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can’t divide by zero")
else:
print("Hi I am else block")
print("outside exception")
output:
Enter a:5
Enter b:0
can’t divide by zero
outside exception
------------------------------
The except statement using with exception variable
We can use the exception variable with the except statement. It is used by using the as
keyword. this object will return the cause of the exception.
------------------------------
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can’t divide by zero")
print(e)
else:
print("Hi I am else block")
print("outside exception")
output:
Enter b:0
can’t divide by zero
division by zero
outside exception
------------------
Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block
may contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement,
which will be executed if no exception is raised in the try block.
4. The statements that don’t throw the exception should be placed inside the else block.
------------------------------
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# multiple exception
except IOError as e1:
print("IO Exception",e1)
except ArithmeticError as e2:
print("Arithmetic Exception", e2)
else:
print("Successfully Done")
print("outside exception")
output:
Enter a:5
Enter b:0
Arithmetic Exception division by zero
outside exception
---------------------------------------------------
Declaring Multiple Exceptions
The Python allows us to declare the multiple exceptions with the
except clause. Declaring multiple exceptions is useful in the
cases where a try block throws multiple exceptions.
The syntax is given below.
Syntax
try:
#block of code
else:
#block of code
-----------------------
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# multiple exception
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
print("outside exception")
output:
Enter a:5
Enter b:0
Arithmetic Exception
outside exception
-----------------------------------
The try...finally block
Python provides the optional finally statement, which is used with the try statement.
It is executed no matter what exception occurs and used to release the external resource.
The finally block provides a guarantee of the execution.
We can use the finally block with the try block in which we can place the necessary code,
which must be executed before the try statement throws an exception.
The syntax to use the finally block is given below.
Syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
-----------------------------
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can’t divide by zero")
print(e)
else:
print("Hi I am else block")
finally:
print("inside finally")
print("outside exception")
output:
Enter a:5
Enter b:0
can’t divide by zero
division by zero
inside finally
outside exception
------------------------------------
Raising exceptions:
An exception can be raised forcefully by using the
raise clause in Python. It is useful in in that
scenario where we need to raise an exception to
stop the execution of the program.
Syntax
raise Exception_class(<value>)
Points to remember
1. To raise an exception, the raise statement is used. The exception class name follows it.
2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which stores the value of
the exception.
4. We can pass the value to an exception to specify the exception type.
-----------------------------
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except Exception:
print("The age is not valid")
print("outside exception")
output:
Enter the age:12
The age is not valid
outside exception
-------------------------
# Raise the exception with message
try:
num = int(input("Enter a positive integer: "))
if(num <= 0):
# we can pass the message in the raise statement
raise ValueError("That is a negative number!")
except Exception as e:
print(e)
output:
Enter a positive integer: -2
That is a negative number!
-----------------------------
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
if b == 0:
raise ArithmeticError("Div with zero...")
else:
print("a/b = ",a/b)
except ArithmeticError as e:
print("The value of b can’t be 0")
print("Error:",e)
output:
Enter a:10
Enter b:0
The value of b can’t be 0
Error: Div with zero...
------------------------------------------------------
Python File Handling
Till now, we were taking the input from the console and
writing it back to the console to interact with the user.
Sometimes, it is not enough to only display the data on
the console. The data to be displayed may be very large,
and only a limited amount of data can be displayed on
the console since the memory is volatile, it is impossible
to recover the programmatically generated data again
and again.
Open a file
Read or write - Performing operation
Close the file
Opening a file
Python provides an open() function that accepts two
arguments, file name and access mode in which the file
is accessed. The function returns a file object which
can be used to perform various operations like reading,
writing, etc.
Syntax:
Syntax
fileobject.close()
--------------
#opens and close the file file.txt in read mode
fileptr = open("D\\DATASET\\sample.txt","r")
if fileptr:
print("file is opened successfully")
#closes the opened file
fileptr.close()
----------------------
After closing the file, we cannot perform any operation
in the file. The file needs to be properly closed. If
any exception occurs while performing some operations
in the file then the program terminates
without closing the file.
--------------
The with statement
The with statement was introduced in python 2.5. The with statement
is useful in the case of manipulating the files. It is used in the
scenario where a pair of statements is to be executed with a block of
code in between.
The syntax to open a file using with the statement is given below.
w: It will overwrite the file if any file exists. The file pointer
is at the beginning of the file.
Example which contains a function readline() that reads the first line
of our file "sample.txt" containing three lines.
----------------
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("C:\\Users\\BAIJU\\Desktop\\kochi.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline()
content1 = fileptr.readline()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
fileptr.close()
------------------
We called the readline() function two times that’s why it read two
lines from the file.
Python provides also the readlines() method which is used for the
reading lines. It returns the list of the lines till the end of
file(EOF) is reached.
----------------------------
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("C:\\Users\\BAIJU\\Desktop\\kochi.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readlines()
w: It creates a new file with the specified name if no such file exists.
It overwrites the existing file.
-----------------------
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("F:\\DATASET\\file2.txt","x")
print(fileptr)
if fileptr:
print("File created successfully")
---------------------
File Pointer positions
Python provides the tell() method which is used to print the byte number
at which the file pointer currently exists.
----------------------------
# open the file file2.txt in read mode
fileptr = open("F:\\DATASET\\file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read()
#after the read operation file pointer modifies. tell() returns the
location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
-----------------
Modifying file pointer position
In real-world applications, sometimes we need to change the file
pointer location externally since we may need to read or write the
content at various locations.
For this purpose, the Python provides us the seek() method which enables
us to modify the file pointer position externally.
Syntax:
<file-ptr>.seek(offset[, from)
---------------------
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved.
If it is set to 0, the beginning of the file is used as the reference position.
If it is set to 1, the current position of the file pointer is used as the
reference position. If it is set to 2, the end of the file pointer is used
as the reference position.
---------------
# open the file file2.txt in read mode
fileptr = open("F:\\DATASET\\file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
rename(current-name, new-name)
The first argument is the current file name and the second argument is
the modified name. We can change the file name bypassing these two arguments.
-----------------------
import os
#rename file2.txt to file3.txt
os.rename("C:\\Users\\BAIJU\\OneDrive\\Desktop\\sample.txt","C:\\Users\\BAIJU\\OneDrive\\Desktop\\koc
hi.txt")
print("renamed")
-----------------
Removing the file
The os module provides the remove() method which is used to remove
the specified file. The syntax to use the remove() method is given below.
syntax:
remove(file-name)
-----------------------
import os
#deleting the file named file3.txt
os.remove("file3.txt")
print("File removed")
------------------------
Creating the new directory
The mkdir() method is used to create the directories in the current
working directory. The syntax to create the new directory is given below.
Syntax:
mkdir(directory name)
-----------------------------
import os
#creating a new directory with the name new
os.mkdir("ktym")
print("folder created")
--------------------------
The getcwd() method
This method returns the current working directory.
Syntax
os.getcwd()
------------
import os
print(os.getcwd())
print("current directory")
---------------
Changing the current working directory
The chdir() method is used to change the current working directory to a
specified directory.
Syntax
chdir("new-directory")
------------------------
import os
print("current working directory")
print(os.getcwd())
# Changing current directory with the new directiory
os.chdir("F:\\")
#It will display the current working directory
print(os.getcwd())
------------------
Deleting directory
The rmdir() method is used to delete the specified directory.
Syntax
os.rmdir(directory name)
-------------------------
import os
#removing the new directory
os.rmdir("C:\\Users\\BAIJU\\OneDrive\\Desktop\\kochi")
print("folder removed")
-------------------------------------------------
Python RegEx
A RegEx, or Regular Expression, is a sequence of characters that forms a
search pattern.
RegEx can be used to check if a string contains the specified search pattern.
RegEx Module
Python has a built-in package called re, which can be used to work with
Regular Expressions.
Import the re module:
import re
--------------------------------
RegEx in Python
When you have imported the re module, you can start using regular expressions:
eg:
Search the string to see if it starts with "The" and ends with "Spain":
-----------------------
RegEx Functions
The re module offers a set of functions that allows us to search a string
for a match:
output:
[’ai’, ’ai’]
--------------------
search:- Returns a Match object if there is a match
anywhere in the string
----------------
import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
output:
The first white-space character is located in position: 3
------------------
split: Returns a list where the string has been split at each match
Split at each white-space character:
----------------------
import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
output:
[’The’, ’rain’, ’in’, ’Spain’]
-------------------
sub: Replaces one or many matches with a string
Replace every white-space character with the number 9:
---------------------
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)
output:
The9rain9in9Spain
-------------------
Metacharacters:
Metacharacters are characters with a special meaning:
[] A set of characters "[a-m]"
----------------
import re
txt = "The rain in Spain"
#Find all lower case characters alphabetically between "a" and "m":
x = re.findall("[a-m]", txt)
print(x)
output:
[’h’, ’e’, ’a’, ’i’, ’i’, ’a’, ’i’]
----------------------------
. Any character (except newline character) "he..o"
--------------------
output:
[’hello’]
-------------------
^ Starts with "^hello"
----------
import re
txt = "hello planet"
#Check if the string starts with ’hello’:
x = re.findall("^hello", txt)
if x:
print("Yes, the string starts with ’hello’")
else:
print("No match")
output:
Yes, the string starts with ’hello’
--------------------------------
$ Ends with "planet$"
-------------
import re
txt = "hello planet"
#Check if the string ends with ’planet’:
x = re.findall("planet$", txt)
if x:
print("Yes, the string ends with ’planet’")
else:
print("No match")
output:
Yes, the string ends with ’planet’
-------------------------------------
* Zero or more occurrences "he.*o"
output:
[’hello’]
-------------------------
+ One or more occurrences "he.+o"
-----------
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed by 1
or more (any) characters, and an "o":
x = re.findall("he.+o", txt)
print(x)
output:
[’hello’]
--------------------------
? Zero or one occurrences "he.?o"
----------
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed by 0 or 1 (any)
character, and an "o":
x = re.findall("he.?o", txt)
print(x)
output:
[]
------------------
#This time we got no match, because there were not zero, not one, but
two characters
between "he" and the "o"
----------------------------
{} Exactly the specified number of occurrences "he.{2}o"
----------
import re
txt = "hello planet"
#Search for a sequence that starts with "he", followed excactly 2 (any)
characters, and an "o":
x = re.findall("he.{2}o", txt)
print(x)
output:
[’hello’]
-------------------------------
| Either or "falls|stays"
-------
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains either "falls" or "stays":
x = re.findall("falls|stays", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
output:
[’falls’]
Yes, there is at least one match!
------------------------------
Sets
A set is a set of characters inside a pair of square brackets []
with a special meaning:
[arn] Returns a match where one of the specified characters (a, r, or n) is present
----------
import re
txt = "The rain in Spain"
#Check if the string has any a, r, or n characters:
x = re.findall("[arn]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
output:
[’r’, ’a’, ’n’, ’n’, ’a’, ’n’]
Yes, there is at least one match!
------------------------------------
[a-n] Returns a match for any lower case character, alphabetically
between a and n
-----------
import re
txt = "The rain in Spain"
#Check if the string has any characters between a and n:
x = re.findall("[a-n]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
output:
[’h’, ’e’, ’a’, ’i’, ’n’, ’i’, ’n’, ’a’, ’i’, ’n’]
Yes, there is at least one match!
----------------------------
[^arn] Returns a match for any character EXCEPT a, r, and n
------------
import re
txt = "The rain in Spain"
#Check if the string has other characters than a, r, or n:
x = re.findall("[^arn]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
output:
[’T’, ’h’, ’e’, ’ ’, ’i’, ’ ’, ’i’, ’ ’, ’S’, ’p’, ’i’]
Yes, there is at least one match!
-----------------------------
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3)
are present
------------
import re
txt = "The rain in Spain"
#Check if the string has any 0, 1, 2, or 3 digits:
x = re.findall("[0123]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
output:
[]
No match
-----------------------
[0-9] Returns a match for any digit between 0 and 9
------
import re
txt = "8 times before 11:45 AM"
#Check if the string has any digits:
x = re.findall("[0-9]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
output:
[’8’, ’1’, ’1’, ’4’, ’5’]
Yes, there is at least one match!
----------------------------
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59
-----------------
import re
txt = "8 times before 11:45 AM"
#Check if the string has any two-digit numbers, from 00 to 59:
x = re.findall("[0-5][0-9]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
output:
[’11’, ’45’]
Yes, there is at least one match!
-------------------------
[a-zA-Z] Returns a match for any character alphabetically between
a and z, lower case OR upper case
-------------
import re
txt = "8 times before 11:45 AM"
#Check if the string has any characters from a to z lower case, and A to Z upper case:
x = re.findall("[a-zA-Z]", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
output:
[’t’, ’i’, ’m’, ’e’, ’s’, ’b’, ’e’, ’f’, ’o’, ’r’, ’e’, ’A’, ’M’]
Yes, there is at least one match!
-------------------------------------------------------
Python OOPs Concepts
Like other general-purpose programming languages,
Python is also an object-oriented language since
its beginning. It allows us to develop applications
using an Object-Oriented approach. In Python, we
can easily create and use Like other general-purpose
programming languages, Python is also an
object-oriented language since its beginning. It
allows us to develop applications using an
Object-Oriented approach. In Python, we can easily
create and use classes and objects.classes and
objects. An object-oriented paradigm is to design
the program using classes and objects. The object
is related to real-word entities such as book,
house, pencil, etc. The oops concept focuses on
writing the reusable code. It is a widespread
technique to solve the problem by creating objects.
----------------
Major principles of object-oriented programming
system are given below.
Class
Object
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation
---------------------
Class
The class can be defined as a collection of objects.
It is a logical entity that has some specific
attributes and methods. For example: if you have
an employee class, then it should contain an
attribute and method, i.e. an email id, name, age,
salary, etc.
Object
The object is an entity that has state and
behavior. It may be any real-world object like
the mouse, keyboard, chair, table, pen, etc.
Method:
The method is a function that is associated with
an object. In Python, a method is not unique to
class instances. Any object type can have methods.
Inheritance:
Inheritance is the most important aspect of
object-oriented programming, which simulates
the real-world concept of inheritance. It
specifies that the child object acquires all
the properties and behaviors of the parent
object.
Encapsulation:
Encapsulation is also an essential aspect of
object-oriented programming. It is used to
restrict access to methods and variables. In
encapsulation, code and data are wrapped together
within a single unit from being modified by
accident.
Data Abstraction
Data abstraction and encapsulation both are often
used as synonyms. Both are nearly synonyms because
data abstraction is achieved through encapsulation.
Syntax:
class ClassName:
#statement_suite
A class contains a statement suite including
fields, constructor, function, etc. definition.
-------------
To create a class Employee which contains two
fields as Employee id, and name. The class also
contains a function display(), which is used to
display the information of the Employee.
class Employee:
id = 10
name = "Devansh"
def display(self):
print(self.id,self.name)
------------------------------
Here, the self is used as a reference variable,
which refers to the current class object. It is
always the first argument in the function
definition. However, using self is optional in
the function call.
The self-parameter
The self-parameter refers to the current instance
of the class and accesses the class variables.
We can use anything instead of self,but it must
be the first parameter of any function which
belongs to the class.
<object-name> = <class-name>(<arguments>)
---------------------------
#Create the instance of the class Employee
class Employee:
id = 10
name = "John"
def display(self):
print("ID: %d \nName: %s"%(self.id,self.name))
output:
ID: 10
Name: John
-------------------------------
we have created the Employee class which has two
attributes named id and name and assigned value
to them. We can observe we have passed the self
as parameter in display function. It is used to
refer to the same class attribute.
We have created a new instance object named emp.
By using it,
we can access the attributes of the class.
--------------------
Delete the Object
We can delete the properties of the object or
object itself by using the del keyword.
---------------------
class Employee:
id = 10
name = "John"
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
# Creating a emp instance of Employee class
emp = Employee()
emp.display()
1. Parameterized Constructor
2. Non-parameterized Constructor
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)
output:
The number of students: 3
-------------------------------
Python Non-Parameterized Constructor
The non-parameterized constructor uses when we do not want to manipulate
the value or the constructor that has only self as an argument.
----------------------
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
output:
This is non parametrized constructor
Hello John
--------------------
Python Parameterized Constructor
The parameterized constructor has multiple parameters along with the self.
------------------------
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
output:
This is parametrized constructor
Hello John
------------------------
Python Default Constructor
When we do not include the constructor in the class or forget to declare it,
then that becomes the default constructor. It does not perform any task but
initializes the objects.
-----------------------
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,self.name)
st = Student()
st.display()
output:
101 Joseph
---------------------
Python built-in class functions
The built-in functions defined in the class are described in the following table.
1. getattr(obj,name) It is used to access the attribute of the object.
2. setattr(obj, name,value) It is used to set a particular value to the specific
attribute of an object.
3. delattr(obj, name) It is used to delete a specific attribute.
4. hasattr(obj, name) It returns true if the object contains some specific
attribute.
-------------------------------
class Student:
def __init__(self, name, id, age):
self.name = name
self.id = id
self.age = age
# creates the object of the class Student
print(hasattr(s, ’id’))
# deletes the attribute age
delattr(s, ’age’)
# this will give an error since the attribute age has been deleted
print(s.age)
-------------------------
Built-in class attributes
Along with the other attributes, a Python class
also contains some built-in class attributes
which provide information about the class.
----------------
1. __dict__ It provides the dictionary containing
the information about the class namespace.
2. __doc__ It contains a string which has the class documentation
3. __name__ It is used to access the class name.
4. __module__ It is used to access the module in which, this class is defined.
5. __bases__ It contains a tuple including all base classes.
-------------------------------
class Student:
"A class about students and their addresses"
def __init__(self,name,id,age):
self.name = name
self.id = id
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d" % (self.name,self.id,self.age))
s = Student("John",101,22)
print("Doc:",s.__doc__)
print("Dict:",s.__dict__)
print("Module:",s.__module__)
print("Name:",Student.__name__)
print("Base:",Student.__bases__)
Output:
Doc: A class about students and their addresses
Dict: {’name’: ’John’, ’id’: 101, ’age’: 22}
Module: __main__
Name: Student
Base: (<class ’object’>,)
-----------------------------
Python Inheritance:
Inheritance is an important aspect of the
object-oriented paradigm. Inheritance provides
code reusability to the program because we can
use an existing class to create a new class instead
of creating it from scratch.
--------------
Single Inheritance
Syntax
class derived-class(base class):
<class-suite>
----------------------------
# Single level inheritance
class Animal:
def speak(self):
print("Animal Speaking")
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.
-----------------------
#multi level inheritance
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
---------------------------
Python Multiple inheritance:
Python provides us the flexibility to inherit multiple base classes
in the child class.
The syntax to perform multiple inheritance is given below.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
class ICICI(Bank):
def getroi(self):
return 8
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",b1.getroi())
print("SBI Rate of interest:",b2.getroi())
print("ICICI Rate of interest:",b3.getroi())
#****************************************************
------------------------------
Database
What is Data?
Data is a collection of a distinct small unit of
information. It can be used in a variety of forms
like text, numbers, media, bytes, etc. it can be
stored in pieces of paper or electronic memory, etc.
What is Database?
A database is an organized collection of data, so
that it can be easily accessed and managed.
You can organize data into tables, rows, columns,
and index it to make it easier to find relevant
information.
Database handlers create a database in such a way
that only one set of software program provides
access of data to all the users.
What is a column/attribute?
A column is a vertical entity in the table which
contains all information associated with a
specific field in a table. For example, "name"
is a column in the above table which contains
all information about a student’s name.
Name
Ajeet
Aryan
Mahesh
Ratan
Vimal
SQL:
SQL is a database computer language designed for
the retrieval and management of data in a
relational database.
SQL- stands for Structured Query Language.
SQL - Overview
SQL is a language to operate databases; it includes
database creation, deletion, fetching rows,
modifying rows, etc.
What is SQL?
SQL is Structured Query Language, which is a
computer language for storing, manipulating and
retrieving data stored in a relational database.
-----------------------
SQL Commands
The standard SQL commands to interact with
relational databases are CREATE, SELECT, INSERT,
UPDATE, DELETE and DROP. These commands can be
classified into the following groups based on
their nature −
2
ALTER
3
DROP
2
INSERT
Creates a record.
3
UPDATE
Modifies records.
4
DELETE
Deletes records.
-----------------
DCL - Data Control Language
Sr.No. Command & Description
1
GRANT
2
REVOKE
What is a table?
The data in an RDBMS is stored in database objects
which are called as tables. This table is
basically a collection of related data entries
and it consists of numerous columns and rows.
a CUSTOMERS table −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
What is a field?
Every table is broken up into smaller entities
called fields. The fields in the CUSTOMERS table
consist of ID, NAME, AGE, ADDRESS and SALARY.
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
What is a column?
A column is a vertical entity in a table that
contains all information associated with a
specific field in a table.
For example, a column in the CUSTOMERS table is
ADDRESS, which represents location description
and would be as shown below −
+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |
+----+------+
What is a NULL value?
A NULL value in a table is a value in a field that
appears to be blank, which means a field with a
NULL value is a field with no value.
SQL Constraints
Constraints are the rules enforced on data columns
on a table. These are used to limit the type of
data that can go into a table. This ensures the
accuracy and reliability of the data in the database.
Numeric
Date and Time
String Types.
Arithmetic operators
Comparison operators
Logical operators
Operators used to negate conditions
-----------
SQL Arithmetic Operators
Assume 'variable a' holds 10 and 'variable b' holds
20, then −
2
AND
3
ANY
4
BETWEEN
5
EXISTS
6
IN
7
LIKE
8
NOT
9
OR
10
IS NULL
11
UNIQUE
Syntax
The basic syntax of this CREATE DATABASE statement
is as follows −
CREATE DATABASE DatabaseName;
Make sure you have the admin privilege before creating any
database. Once a database is created, you can check it in
the list of databases as follows −
Syntax
The basic syntax of DROP DATABASE statement is as
follows −
DROP DATABASE DatabaseName;
If you want to delete an existing database <testDB>,
then
the DROP DATABASE statement would be as shown
below −
Syntax
The basic syntax of the USE statement is as shown below −
USE DatabaseName;
You can check the available databases as shown below −
First create a database named smec
mysql> CREATE DATABASE smec;
for selecting
mysql> use smec;
Database changed
mysql>
-----------------------------
SQL - CHECK Constraint
The CHECK Constraint enables a condition to check the value being entered into
a record. If the condition evaluates to false, the record violates the
constraint and isn't entered the table.
creates a new table called CUSTOMERS and adds five columns. Here, we add a
CHECK with AGE column, so that you cannot have any CUSTOMER who is
below 18 years.
----------------
Add multiple columns in the table
ALTER TABLE table_name
ADD new_column_name column_definition
[ FIRST | AFTER column_name ],
ADD new_column_name column_definition
[ FIRST | AFTER column_name ],
-----------------------
MODIFY column in the table
The MODIFY command is used to change the column
definition of the table.
Syntax:
Syntax-1
There are two basic syntaxes of the INSERT INTO
statement which are shown below.
You can create a record in the CUSTOMERS table by using the second syntax as shown below.
Syntax
The basic syntax of the SELECT statement is as follows −
The following code is an example, which would fetch the ID, Name and Salary fields
of the customers available in CUSTOMERS table.
-------------
If you want to fetch all the fields of the CUSTOMERS
table, then you should use the following query.
Syntax
The basic syntax of the SELECT statement with the WHERE
clause is as shown below.
Fetch the ID, Name and Salary fields from the CUSTOMERS
table, where the salary is greater than 4000 −
mysql> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 4000;
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
| 8 | Amal | 30000.00 |
+----+----------+----------+
The following query is an example, which would fetch the
ID, Name and Salary fields from the CUSTOMERS table for
a customer with the name Hardik.
mysql> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE NAME = 'Hardik';
+----+--------+---------+
| ID | NAME | SALARY |
+----+--------+---------+
| 5 | Hardik | 8500.00 |
+----+--------+---------+
Syntax
The basic syntax of the AND operator with a WHERE clause is as follows −
-----------------
The OR Operator
The OR operator is used to combine multiple conditions
in an SQL statement's WHERE clause.
Syntax
The basic syntax of the OR operator with a WHERE clause
is as follows −
fetch the ID, Name and Salary fields from the CUSTOMERS
table, where the salary is greater than 4000 OR the age
is less than 25 years.
mysql> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY >4000 OR age < 23;
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
mysql>SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY >4000 OR (age < 30 and
age>25);
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
----------------
To clear mysql prompt screen
mysql> \! cls;
-------------------------
NOT Operator
mysql> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE not(SALARY >4000);
+----+---------+---------+
| ID | NAME | SALARY |
+----+---------+---------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
+----+---------+---------+
----------------------
SQL - UPDATE Query
The SQL UPDATE Query is used to modify the existing
records in a table. You can use the WHERE clause
with the UPDATE query to update the selected rows,
otherwise all the rows would be affected.
mysql> select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Syntax
The basic syntax of the UPDATE query with a WHERE clause
is as follows −
You can use the WHERE clause with a DELETE query to delete
the selected rows, otherwise all the records would be
deleted.
Syntax
The basic syntax of the DELETE query with the WHERE clause
is as follows −
Finds any values that start with 2 and are at least 3 characters in length.
mysql> SELECT * FROM CUSTOMERS WHERE SALARY LIKE '2_%_%';
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
-------------------------------------
SQL - TOP, LIMIT or ROWNUM Clause
The SQL TOP clause is used to fetch a TOP N number
or X percent records from a table.
For mysql:
SELECT col1,col2,... FROM table_name LIMIT count;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
mysql>
----------------------
SQL - Distinct Keyword
The SQL DISTINCT keyword is used in conjunction
with the SELECT statement to eliminate all the
duplicate records and fetching only unique records.
Syntax
The basic syntax of DISTINCT keyword to eliminate
the duplicate records is as follows −
First, let us see how the following SELECT query returns the duplicate salary records.
mysql>
-------------------------
SQL - SORTING Results
The SQL ORDER BY clause is used to sort the data
in ascending or descending order, based on one
or more columns. Some databases sort the query
results in an ascending order by default.
Syntax
The basic syntax of the ORDER BY clause which
would be used to sort the result in an ascending
or descending order is as follows −
CUSTOMERS Table
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Syntax
The basic syntax of the INNER JOIN is as follows.
Syntax
The basic syntax of a LEFT JOIN is as follows.
SELECT table1.column1, table2.column2... FROM table1 LEFT JOIN table2
ON table1.common_field = table2.common_field;
mysql> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON
CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
+----+----------+--------+------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 |
| 3 | kaushik | 3000 | 2009-10-08 |
| 3 | kaushik | 1500 | 2009-10-08 |
| 4 | Chaitali | 2060 | 2008-05-20 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
| 8 | Amal | NULL | NULL |
| 9 | Ajith | NULL | NULL |
+----+----------+--------+------------+
----------------------------------------
SQL - RIGHT JOINS
The SQL RIGHT JOIN returns all rows from the right
table, even if there are no matches in the left
table. This means that if the ON clause matches
0 (zero) records in the left table; the join will
still return a row in the result, but with NULL
in each column from the left table.
Syntax
The basic syntax of a RIGHT JOIN is as follow.
mysql> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON
CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
+------+----------+--------+------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+------------+
| 3 | kaushik | 1500 | 2009-10-08 |
| 2 | Khilan | 1560 | 2009-11-20 |
| 3 | kaushik | 3000 | 2009-10-08 |
| 4 | Chaitali | 2060 | 2008-05-20 |
+------+----------+--------+------------+
--------------------------------------------
MySQL CROSS JOIN
The SQL CROSS JOIN combines the results of both
left and right outer joins.
Syntax
The basic syntax of a CROSS JOIN(FULL JOIN) is as
follows −
The CROSS JOIN keyword returns all matching
records from both tables whether the other table
matches or not. So, if there are rows in
"Customers" that do not have matches
in "Orders", or if there are rows in "Orders" that
do not have matches in "Customers", those rows
will be listed as well.
syntax:
SELECT table1.column1, table2.column2... FROM table1 CROSS
JOIN table2 ON table1.common_field = table2.common_field;
mysql> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS CROSS JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
+----+----------+--------+------------+
| ID | NAME | AMOUNT | DATE |
+----+----------+--------+------------+
| 3 | kaushik | 1500 | 2009-10-08 |
| 2 | Khilan | 1560 | 2009-11-20 |
| 3 | kaushik | 3000 | 2009-10-08 |
| 4 | Chaitali | 2060 | 2008-05-20 |
+----+----------+--------+------------+
----------------------------------------------------
MySQL IN Condition
The MySQL IN condition is used to reduce the use
of multiple OR conditions in a SELECT, INSERT,
UPDATE and DELETE statement.
Syntax:
expression IN (value1, value2, .... value_n);
expression: It specifies a value to test.
Make sure you define the name of the database when you create the connection
Create a table named "customers":
------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(30), address VARCHAR(50))")
print("done")
If the above code was executed with no errors, you have now successfully created a table.
-----------------------
Check if Table Exists
You can check if a table exist by listing all tables in your database with the
"SHOW TABLES" statement:
Return a list of your system's databases:
--------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
--------------------------------
Python MySQL Insert Into Table
Insert Into Table
To fill a table in MySQL, use the "INSERT INTO" statement.
Insert a record in the "customers" table:
----------------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
----------------------------------
Important!: Notice the statement: mydb.commit(). It is
required to make the changes, otherwise no changes are
made to the table.
-----------------------
Insert Multiple Rows
To insert multiple rows into a table, use the executemany() method.
The fetchone() method will return the first row of the result:
Fetch only one row:
---------------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
print(myresult)
--------------------------
Python MySQL Where
Select With a Filter
When selecting records from a table, you can filter the selection by using
the "WHERE" statement:
Select record(s) where the address is "Park Lane 38": result:
-----------------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address ='Park Lane 38'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
-------------------
Prevent SQL Injection
When query values are provided by the user, you should escape the values.
This is to prevent SQL injections, which is a common web hacking technique to
destroy or misuse your database.
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
----------------------
Python MySQL Order By
Sort the Result
Use the ORDER BY statement to sort the result in ascending or descending order.
The ORDER BY keyword sorts the result ascending by default. To sort the result
in descending order, use the DESC keyword.
Sort the result alphabetically by name: result:
----------------------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
------------------------------
ORDER BY DESC
Use the DESC keyword to sort the result in a descending order.
Sort the result reverse alphabetically by name:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
---------------------
Python MySQL Delete From By Delete Record
You can delete records from an existing table by using the "DELETE FROM" statement:
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql)
mydb.commit()
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql, adr)
mydb.commit()
--------------------------------
Python MySQL Update Table
Update Table
You can update existing records in a table by using the "UPDATE" statement:
Overwrite the address column from "Valley 345" to "Canyon 123":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
The mysql.connector module uses the placeholder %s to escape values in the delete
statement:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute(sql, val)
mydb.commit()
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchall()
for x in myresult:
print(x)
------------------------
Start From Another Position
If you want to return five records, starting from the third record, you can use the
"OFFSET" keyword:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
myresult = mycursor.fetchall()
for x in myresult:
print(x)
----------------------------------------
Python MySQL Join:
users:
mysql>create table users (id int, name varchar(30),fav int);
products:
mysql>create table products(id int , name varchar(30));
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT \
users.name , \
products.name \
FROM users \
INNER JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
---------------------------
LEFT JOIN
In the example above, Hannah, and Michael were excluded from the result,
that is because INNER JOIN only shows the records where there is a match.
If you want to show all users, even if they do not have a favorite product,
use the LEFT JOIN statement:
----------------------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT \
users.name , \
products.name \
FROM users \
LEFT JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
--------------------------------
RIGHT JOIN
If you want to return all products, and the users who have them as their favorite,
even if no user have them as their favorite, use the RIGHT JOIN statement:
------------------------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT \
users.name , \
products.name \
FROM users \
RIGHT JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
--------------
Python MySQL Drop Table:
Delete a Table
You can delete an existing table by using the "DROP TABLE" statement:
Delete the table "abc":
---------------------------------
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DROP TABLE abc"
mycursor.execute(sql)