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

Python NOTES

Uploaded by

motichain2000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python NOTES

Uploaded by

motichain2000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 119

PYTHON NOTES

Prakash Chandrayan
1|P a g e

MODULE 01 : PYTHON – AN INTRODUCTION

1.1 What is Python ?


Python is a simple and easy to understand lanuage . This Pseudo Code nature of python makes it easy to learn and
understable by beginners .
Python is a genral purpose , high level , object oriented , interprted, programming language.
It is created by GUIDO VAN ROSSUM in Feb 20 ,1991.
Python for used

1For scripting

2 web development.
3 ML and AI.
4 Software Development.
5 Internet of Things (IOT)
6 Desktop Application.
7 Mobile Development.

APPLICATION OF PYTHON
HOW TO DOWNLOAD PYTHON
VERSION OF PYTHON
1.5 Scriptive and Intractive
PIP ;-Pip is the package manager for python you can use pip to install a module on your system.

1.7 Feature of python (ADVANTAGE)


1 Simple to easy to learn
2 Open source(all content are free of cost)
3 Interpted (translate to line by line)
4 Dynamically language
5 Supporting GUI (Graphical Usear Interface)
2|P a g e

6Support object Oriented programming


7Large Library
1.8 Disadvantage :-
1 slow:Compare to java and C++
2 large :- Memory consume

The following table lists some of the most useful shortcuts to learn:

Shortcut Action

Double Shift Search Everywhere

Quickly find any file, action, class, symbol, tool


window, or setting in PyCharm, in your project,
and in the current Git repository.

Ctrl+Shift+A Find Action

Find a command and execute it, open a tool


window, or search for a setting.

Alt+Enter Show Context Actions

Quick-fixes for highlighted errors and warnings,


intention actions for improving and optimizing
your code.

F2 Navigate between code issues


Shift+F2
Jump to the next or previous highlighted error.
3|P a g e

Shortcut Action

Ctrl+E View recent files

Select a recently opened file from the list.

Ctrl+W Extend or shrink selection


Ctrl+Shift+W
Increase or decrease the scope of selection
according to specific code constructs.

Ctrl+/ Add/remove line or block comment


Ctrl+Shift+/
Comment out a line or block of code.

Alt+F7 Find Usages


Show all places where a code element is used
across your project.

Alt+Shift+F10 Access to the RUN and Debug without mouse

Ctrl+Q(view a quick documention) ,Ctrl+P(,Parameter Info)


Ctrl+B(Negative Declartion)
4|P a g e

MODULE 2 : COMPARISONS OF PYTHON WITH OTHER LANGUAGE

python code

a = 12
b = 123
print(a+b)

135
Java code
public class Addition {
public static void main(String[] args) {
int a = 12; // First number
int b = 10; // Second number
int c = a + b; // Sum of a and b
System.out.println("The sum of " + a + " and " + b + " is: " + c);
}
}
script kiddies coder

Elit coder

C code

#include <stdio.h>
int main() {
int a = 10;
5|P a g e

int b = 2;
int c;
c = a + b;
printf("The value of c is: %d\n", c);
return 0;
}

12

What is key words ?

Python keywords are special reserved words that have specific meaning and purposes. It is reserved words in python. It is not use
making for variable.

Import keyword
Print(keyword.kwlist)
6|P a g e

Types of keywords:-
Value Keywords: True, False, None.
Operator Keywords: and, or, not, in, is.
Control Flow Keywords: if, elif, else.
Iteration Keywords: for, while, break, continue, else.
Structure Keywords: def, class, with, as, pass, lambda.
Returning Keywords: return, yield.
Import Keywords: import, from, as

Keywords in Python are reserved words that cannot be used as a variable name, function name, or any other identifier.
7|P a g e

Example: Python Keywords List

 Python3

# Python code to demonstrate working of iskeyword()

# importing "keyword" for keyword operations

importkeyword

# printing all keywords at once using "kwlist()"

print("The list of keywords is : ")

print(keyword.kwlist)

Output:
The list of keywords is :
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’,
‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

Let’s discuss each keyword in detail with the help of good examples.
8|P a g e

True, False, None


 True: This keyword is used to represent a Boolean true. If a statement is true, “True” is printed.
 False: This keyword is used to represent a Boolean false. If a statement is false, “False” is printed.

Example: True, False, and None Keyword

 Python3

print(False==0)

print(True==1)

print(True+True+True)

print(True+False+False)

print(None==0)

print(None==[])

Output
9|P a g e

True
True
3
1
False
False
and, or, not, in, is
 and: This a logical operator in python. “and” Return the first false value. If not found return last. The truth table for “and” is
depicted below.

3 and 0 returns 0
3 and 10 returns 10
10 or 20 or 30 or 10 or 70 returns 10
10|P a g e

 or: This a logical operator in python. “or” Return the first True value.if not found return last. The truth table for “or” is depicted
below.

.
3 or 0 returns 3
3 or 10 returns 3
0 or 0 or 3 or 10 or 0 returns 3
 not: This logical operator inverts the truth value. The truth table for “not” is depicted below.
 in: This keyword is used to check if a container contains a value. This keyword is also used to loop through the container.
 is: This keyword is used to test object identity, i.e to check if both the objects take the same memory location or not.

Example: and, or, not, is and in keyword

 Python
11|P a g e

# showing logical operation

# or (returns True)

print(TrueorFalse)

# showing logical operation

# and (returns False)

print(FalseandTrue)

# showing logical operation

# not (returns False)

print(notTrue)
12|P a g e

# using "in" to check

if'a'in'any name':

print("a is part of any name")

else:

print("a is not part of any name")

# using "in" to loop through

fori in'any name':

print(i, end=" ")

print("\r")

# using is to check object identity


13|P a g e

# string is immutable( cannot be changed once allocated)

# hence occupy same memory location

print(' 'is' ')

# using is to check object identity

# dictionary is mutable( can be changed once allocated)

# hence occupy different memory location

print({} is{})

Output:
True
False
False
a is part of any name
any name
True
False
Iteration Keywords – for, while, break, and continue
14|P a g e

 for: This keyword is used to control flow and for looping.


 while: Has a similar working like “for”, used to control flow and for looping.
 break: “break” is used to control the flow of the loop. The statement is used to break out of the loop and passes the control to
the statement following immediately after loop.
 continue: “continue” is also used to control the flow of code. The keyword skips the current iteration of the loop but does not
end the loop.

Example: For, while, break, continue keyword

 Python3

# Using for loop

fori inrange(10):

print(i, end =" ")

# break the loop as soon it sees 6

ifi ==6:
15|P a g e

break

print()

# loop from 1 to 10

i =0

whilei <10:

# If i is equals to 6,

# continue to next iteration

# without printing

0ifi ==6:

i+=1
16|P a g e

continue

else:

# otherwise print the value

# of i

print(i, end =" ")

i +=1

Output
0123456
012345789
Conditional keywords – if, else, elif
 if : It is a control statement for decision making. Truth expression forces control to go in “if” statement block.
 else : It is a control statement for decision making. False expression forces control to go in “else” statement block.
 elif : It is a control statement for decision making. It is short for “else if“

Example: if, else, and elif keyword

 Python3
17|P a g e

# Python program to illustrate if-elif-else ladder

i =20

if(i ==10):

print("i is 10")

elif(i ==20):

print("i is 20")

else:

print("i is not present")

Output
i is 20
def
def keyword is used to declare user defined functions.

Example: def keyword

 Python3
18|P a g e

# def keyword

deffun():

print("Inside Function")

fun()

Output
Inside Function
Return Keywords – Return, Yield
 return : This keyword is used to return from the function.
 yield : This keyword is used like return statement but is used to return a generator.

Example: Return and Yield Keyword

 What is Return keywords?

 A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the
return keyword) to the caller.

 The Python return statement instructs Python to continue executing a main program. You can use the return statement to send a
value back to the main program, such as a string or a list.
19|P a g e

# Return keyword

defadd():
return 3+23+23+23
print(add())

or

defadd(a,b,c):
return a+b+c
d = add(129,2,3)
print(d)

or

defadd(x, y):
return x + y
a = add(123, 34)
print(f'theadd of (123, 34) function is {a}')

# Yield Keyword
20|P a g e

deffun():

S =0

fori inrange(10):

S +=i

yieldS

fori infun():

print(i)

Output
45
0
1
3
6
10
21|P a g e

15
21
28
36
45
class
class keyword is used to declare user defined classes.

Example: Class Keyword

 Python3

# Python3 program to

# demonstrate instantiating

# a class

classDog:
22|P a g e

# A simple class

# attribute

attr1 ="mammal"

attr2 ="dog"

# A sample method

deffun(self):

print("I'm a", self.attr1)

print("I'm a", self.attr2)

# Driver code

# Object instantiation
23|P a g e

Rodger =Dog()

# Accessing class attributes

# and method through objects

print(Rodger.attr1)

Rodger.fun()

Output
mammal
I'm a mammal
I'm a dog
With
with keyword is used to wrap the execution of block of code within methods defined by context manager. This keyword is not used
much in day to day programming.

Example: With Keyword

 Python3
24|P a g e

# using with statement

with open('file_path', 'w') as file:

file.write('hello world !')

as
as keyword is used to create the alias for the module imported. i.e giving a new name to the imported module. E.g import math as
mymath.

Example: as Keyword

 Python3

importmath as gfg

print(gfg.factorial(5))

Output
120
pass
25|P a g e

pass is the null statement in python. Nothing happens when this is encountered. This is used to prevent indentation errors and use d
as a placeholder.

Example: Pass Keyword

 Python3

n =10

fori inrange(n):

# pass can be used as placeholder

# when code is to added later

Pass

Lambda
Lambda keyword is used to make inline returning functions with no statements allowed internally.
Import, From
 import : This statement is used to include a particular module into current program.
 from : Generally used with import, from is used to import particular functionality from the module imported.

Example: Import, From Keyword


26|P a g e

 Python3

# import keyword

importmath

print(math.factorial(10))

# from keyword

frommath importfactorial

print(factorial(10))

Output
3628800
3628800
Exception Handling Keywords – try, except, raise, finally, and assert
 try : This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in “try”
block is checked, if there is any type of error, except block is executed.
 except : As explained above, this works together with “try” to catch exceptions.
 finally : No matter what is result of the “try” block, block termed “finally” is always executed.
 raise: We can raise an exception explicitly with the raise keyword
27|P a g e

 assert: This function is used for debugging purposes. Usually used to check the correctness of code. If a statement is evaluated to
be true, nothing happens, but when it is false, “AssertionError” is raised. One can also print a message with the error, separated
by a comma.

Example: try, except, raise, finally, and assert Keywords

 Python3

# initializing number

a =4

b =0

# No exception Exception raised in try block

try:

k =a//b # raises divide by zero exception.

print(k)
28|P a g e

# handles zerodivision exception

exceptZeroDivisionError:

print("Can't divide by zero")

finally:

# this block is always executed

# regardless of exception generation.

print('This is always executed')

# assert Keyword

# using assert to check for 0

print("The value of a / b is : ")

assertb !=0, "Divide by 0 error"


29|P a g e

print(a /b)

Output
Can't divide by zero
This is always executed
The value of a / b is :
AssertionError: Divide by 0 error

del
del is used to delete a reference to an object. Any variable or list value can be deleted using del.

Example: del Keyword

 Python3

my_variable1 =20

my_variable2 =“adfsfsfd"

# check if my_variable1 and my_variable2 exists


30|P a g e

print(my_variable1)

print(my_variable2)

# delete both the variables

delmy_variable1

delmy_variable2

# check if my_variable1 and my_variable2 exists

print(my_variable1)

print(my_variable2)

Output
20
asdssasddf
NameError: name 'my_variable1' is not defined
Global, Nonlocal
 global: This keyword is used to define a variable inside the function to be of a global scope.
31|P a g e

 non-local : This keyword works similar to the global, but rather than global, this keyword declares a variable to point to variable
of outside enclosing function, in case of nested functions.

Example: Global and nonlocal keywords

# global variable

a =15

b =10

# function to perform addition

defadd():

c =a +b

print(c)

# calling a function
32|P a g e

add()

# nonlocal keyword

deffun():

var1 =10

defgun():

# tell python explicitly that it

# has to access var1 initialized

# in fun on line 2

# using the keyword nonlocal

nonlocal var1
33|P a g e

var1 =var1 +10

print(var1)

gun()

fun()

Output
25
20
PYHTON MODULE 3 : PYTHON VARIABLES & DATA TYPE

A Variable is the name given to a memory location in a program .

Variable is container.(value store)

Variable is a store reserved any location for a value.

a = 30 where a=variables= container to store a value 30

b = “craw” c=71.6758

2.2 Rule of define variable;=

1 Not start with digits 1 = 10 ( wrong) ,a =10 (right)

2 variable name not allow space character Exam- a b c = 20 (wrong) , absd= 20( right)
34|P a g e

3 Not allow special character

Note : Use Only alphyanumric value and under scorevalue Examp- A _Z( Right), a_z(right), 1-100(right), a123b(right), _ab=10(right)
underscore( _)

4 variable name should not key words name

2.3 Practical of variable(

2.4 keywords lab

2.5 Print Function

Data type ;-Data type are used to creat variable ,and variable are used to hold values. Data type is a techinc and concept that is used
to reserved memory in raw.

Types of data type (normaly)

1 Number ( intege0r 1,2,3…) , floating number (1.23,23.44,233.9….)

2 String (str)

3 None (none type)

4 Booleans ( T or F)

5 List and Tuples

6Set and Dictonary

7 Range

6 Escape e.t.c how to check type of data type (lab)


35|P a g e

MODULES;- AMODULES isa files containing code written by somebody else(usually) whichcan be imported and used in our programs.
It is SIMPLY FILES WITH THE .” Py” extension containing python code that can be imported inside another python program.

Two types of modules

1Built – In Modules (www.docs.python.org)

2 External Modules in Python ( FLASK , PANDA ,Tensarflow, tk ,guishow,turtle,pillow e.t.c)

MODULE 04 :- OPERATORS

What is operators ?

a = 5+6 where 5,6 say that orends and + is operators

Types of operators

1 Mathmatical or Arithmetic operators (+,-,*,/ ,//,%, **)

2 Logical operators (and or in to)

3 Comparison operators

Arithmetic Operators

Operator Name Operation Result Example


36|P a g e

+ Addition x+y Sum of x and y

print(500 + 200)
RESULT
700

- Subtraction x–y Difference of x and y

print(500 - 200)
RESULT
300

* x*y Product of x and y


Multiplication

print(500 * 200)
RESULT
100000

/ Division x/y Quotient of x and y

print(500 / 200)
37|P a g e

RESULT
2.5

// Floor Division x // y Floored quotient of x and y

print(500 // 200)
RESULT
2

% Modulus x%y Remainder of x / y

print(500 % 200)
RESULT
100

** Exponent x ** y x to the power y

print(500 ** 2)
RESULT
250000

Unary Operations for + and -


38|P a g e

A unary operation is an operation with one operand.

Operator Meaning Operation Result Example

+ Unary positive +x x unchanged

print(+500 + 200)
RESULT
700

- Unary negative -x x negated

print(-500 + 200)
RESULT
-300

Comparison (Relational) Operators

Comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation.

Operator Meaning Operation Result Example


39|P a g e

== Equal to x == y True if x is exactly equal to y.


Otherwise False.

print(1==1)
print(1==2)
RESULT
True
False

!= Not equal to x != y True if x is not equal to y.


Otherwise False.

print(1!=1)
print(1!=2)
RESULT
False
True

> Greater than x>y True if x is greater than y.


Otherwise False.

print(1>2)
print(2>1)
RESULT
False
True
40|P a g e

< Less than x<y True if x is less than y.


Otherwise False.

print(1<2)
print(2<1)
RESULT
True
False

>= Greater than x >= y True if x is greater than or


or equal to equal to y. Otherwise False.

print(1>=1)
print(1>=2)
RESULT
True
False

<= Less than or x <= y True if x is less than or equal


equal to to y. Otherwise False.

print(1<=1)
print(2<=1)
RESULT
True
False
41|P a g e

Logical Operators

Operator Operation Result Example

And x and y True if both x and y are True.


Otherwise False.

print(1==1and2==2)
print(1==1and1==2)
RESULT
True
False

Or x or y True if either x or y are True.


Otherwise False.

print(1==1or1==2)
print(1==2or3==4)
RESULT
True
False

Not not x == y or not(x If x is True then return False.


== y)

print(notTrue)
print(notFalse)
42|P a g e

print(not(1==1))
print(not(1==3))
RESULT
False
True
False

True

Assignment Operators

Operator Operation Result Example

= z=x+y Assigns the value of its right operand/s to its


left operand.

a=1+2
print(a)
RESULT
3

+= x += y Same as x = x + y.

a=1
a += 2
print(a)
43|P a g e

RESULT
3

-= x -= y Same as x = x - y.

a=1
a -= 2
print(a)
RESULT
-1

*= x *= y Same as x = x * y.

a=2
a *= 3
print(a)
RESULT
6

/= x /= y Same as x = x / y.

a=6
a /= 2
print(a)
44|P a g e

RESULT
3.0

%= x %= y Same as x = x % y.

a=6
a %= 4
print(a)
RESULT
2

**= x **= y Same as x = x ** y.

a = a**a a=2
a =2**4 a **= 4
a = 16 print(a)
RESULT
16

//= x //= y Same as x = x // y.

a = 25
a //= 4
print(a)
45|P a g e

RESULT
6

Bitwise Operators

The following bitwise operations can be performed on integers. These are sorted in ascending priority.

1.AND Operator

Python bitwise and operator returns 1 if both the bits are 1, otherwise 0.

2. OR Operator

Python bitwise or operator returns 1 if any of the bits is 1. If both the bits are 0, then it returns 0.

3. XOR Operator

Python bitwise XOR operator returns 1 if one of the bits is 0 and the other bit is 1. If both the bits are 0 or 1, then it returns 0

F xor T =T
F xor F = F
T xor T = F
T xor F = T
46|P a g e

4. Bitwise Ones’ Complement Operator

Python Ones’ complement of a number ‘A’ is equal to -(A+1)

5. Bitwise Left Shift Operator

Python bitwise left shift operator shifts the left operand bits towards the left side for the given number of times in the right operand. In
simple terms, the binary number is appended with 0s at the end.

6. Bitwise Right Shift Operator

Python right shift operator is exactly the opposite of the left shift operator. Then left side operand bits are moved towards the right side
for the given number of times. In simple terms, the right side bits are removed.

Operator Operation Result Example

|(pipe) x|y Bitwise or of x and y


Or

print(500 | 200)
RESULT
508
47|P a g e

^xor x^y Bitwise exclusive of x and y

^ (cap)

print(500 ^ 200)
RESULT
316

& x&y Bitwise exclusive of x and y


And

print(500&200)
RESULT
192

<< x << n x shifted left by n bits


ex – 10<<2
left shift 10 = 1010
Increase two bit then
101000 print(500<<2)
= 40 RESULT
2000

>> x >> n x shifted right by n bits


Right 10>>2
Shift. Decrease two bit then
10
Ans = 2 print(500>>2)
48|P a g e

RESULT
125

~ (tilde) ~x The bits of x inverted


-(x + 1)

print(~500)
RESULT
-501

Bitwise Operator Method to Implement

& __and__(self, other)

| __or__(self, other)

^ __xor__(self, other)

~ __invert__(self)

<< __lshift__(self, other)


49|P a g e

>> __rshift__(self, other)

MODULES 05 :- Python Conditional Statements

5.1 Introduction

To apply condition ,we use conditional statement.

(1) If (2) else (3) elif


Lab

MODULE 06: PYTHON LOOPING CONCEPT(repating again and again)

6.1 Introduction
In computer programming, a loops is a sequence of instructions that is cotinually repeated until a certain condition is rached.
50|P a g e

Loops makes it easy for a programmer to tell the computer.


6.2 Process of loops :-
1starting indxing
2 checking condition
3 Run set of statement
4 Increment (Successor) ++a ,a++i+=1 or i=i+1

5 Decrement (predecessor) - -a,a--


6.3 Types of loops
A while loop
B for loop
6.4 while Loop :- In while loops, the condition is checked first. If it evaluates to true , the body of the loop is executed.
Practical
6.5 For loop :- A for loop is used to iterated through a sequence like , table or string.
The sytax of a for loop like this;
i [1,2,3,4]
for item in i:
print(item) 1,2,3,4

6.7 Python range() Function


The range function in python is used to generate a scquence of numbers we can also specify the start,stop and step-size a.
Syntex :-range (start,stop,step-size)

Rule of Range
1. All argument must be integers,wheather its positive or negative .
2. you can not pass string or float numberor any type in a start,stop and stopsize.
3. The stepsize value should not be zero.
51|P a g e

Example

Create a sequence of numbers from 0 to 5, and print each item in the sequence:

x = range(6)
for n in x:
print(n)

Definition and Usage

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a
specified number.

Syntax
range(start, stop, step size)
Parameter Values

Parameter Description
52|P a g e

Start Optional. An integer number specifying at which position to start. Default is 0

Stop Required. An integer number specifying at which position to stop (not included).

Step Optional. An integer number specifying the incrimination. Default is 1

More Examples
Example

Create a sequence of numbers from 3 to 5, and print each item in the sequence:

x = range(3, 6)
for n in x:
print(n)
Example

Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:

x = range(3, 20, 2)
for n in x:
print(n)

or
x = range(10,4,-2)
53|P a g e

for n in X:
print(n)

Module 07:- Control Statements


7.1 Types of control Statement :-
1 Break Statement
2 Continue Statement
3 Pass Statement

1 Break Statement :- Break is used to come out of the loop when encountered it instructs the program to exit the loop now.

2 Continue Statement :- Continue is used to stop the current iteration of the loop and continue with the next one it istructs the
program to skip this iteration

3 Pass statement ;- Pass is a null statement in python.

Module 08 :- Data type Casting

Type :- Type function is used to find the data type of given variable in python.

Ex;- a=23 , b =”ram” Type(b) class<str>

Type(a) = class<int>

Typecasting:- Typecasting is a way to convert one data type to anther type.

A = int(120) = 120 A = float(120) = 120.0

Print(a) Print(a)

A = str(123) Print(a) = 123

Module09 :- Python Number


54|P a g e

a= 12 (int)
b=45.2 (float)
c= 5+34J (complex number) x is the real part and y is the imaginary part.X + yj
Print(a,b,c)

a = 234 + 23j
b = 1223
c=a+b
print(c)

Binary Number Prefix


Number System

Binary '0b' or '0B'

Octal '0o' or '0O'

Hexadecimal '0x' or '0X'

7DE is a hex number


7DE = (7 * 162) + (13 * 161) + (14 * 160)
7DE = (7 * 256) + (13 * 16) + (14 * 1)
7DE = 1792 + 208 + 14
7DE = 2014 (in decimal number)
55|P a g e
56|P a g e
57|P a g e

print(0b11010111)
print(0xFB + 0b101)
print(0o151)

print(bin(10))
ob1010
Decimal

importdecimal
print(0.33)
print(decimal.Decimal(0.23))

Fractions

A fraction has a numerator and a denominator, both of which are integers. This module has support for rational number arithmetic.

import fractions

print(fractions.Fraction(1.512))
print(fractions.Fraction(51))
print(fractions.Fraction(1,32))
58|P a g e

While creating Fraction from float, we might get some unusual results. This is due to the imperfect binary floating point number

representation as discussed in the previous section.


importfractions
# As float

print(fractions.Fraction(1.1))
# As string
print(fractions.Fraction('1.1'))

This data type supports all basic operations. Here are a few examples.

from fractions import Fraction as F

print(F(1, 3) + F(1, 3))

print(1 / F(5, 6))

print(F(-3, 10) >0)

print(F(-3, 10) <0)

Python Mathematics

Python offers modules like math and random to carry out different mathematics like trigonometry, logarithms, probability and

statistics, etc.
import math
59|P a g e

print(math.pi)
print(math.cos(math.pi))
print(math.exp(10))
print(math.log10(1000))
print(math.sinh(1))
print(math.factorial(6))

9.4 Input()Function
This function allows the user to take input from the keyboard as a string.
A= input(“Enter your name :- ”)
Print(a)
Print(type(a))

Module 10 :- Python String


It is a collection or sequence of charaters
Ex- a = welcome
Single quoted String a =’craw’
Double quoted String b =”Ram is a good boy.”
Triple quoted String C =’’’ ram is a good boy .kkddf;dk klfdkfkfsdiwerid’’’

String Slicing A

0 1 2 3 4 5 6 7 8 9 10 11 12
R A M A N D S I T A .
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
60|P a g e

In Python, the capitalize() method returns a copy of the original string and converts the first character of the string to a
capital (uppercase) letter while making all other characters in the string lowercase letters.
print(a.capitalizer()) print(a.uppercase()) print(a.lowercase()) a = ‘ram’

Python String casefold() method is used to implement caseless string matching. It is similar to lower() string method but case removes
all the case distinctions present in a string. i.e ignore cases when comparing.

Python String count() function is an inbuilt function in python programming language that returns the number of occurrences of a
substring in the given string.

Python String endswith(),startswith()method returns True if a string ends with the given suffix otherwise returns False.

python in its library has “expandtabs()” which specifies the amount of space to be substituted with the “\t” symbol in the string.

Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found
then it returns -1.
Python format() function has been introduced for handling complex string formatting more efficiently. This method of the built-in
string class provides functionality for complex variable substitutions and value formatting. This new formatting technique is regarded
as more elegant. The general syntax of format() method is string.format(var1, var2,…)
Using a Single Formatter
Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and
calling the str.format(). The value we wish to put into the placeholders and concatenate with the string passed as parameters into the
format function.
Syntax : { } .format(value)

# thestr.format() method # using format option in a simple string


print("{}, A computer science portal for security."
.format("security"))
# using format option for a value stored in a variable
a= "This article is written in {}"
print(a.format("Python"))
61|P a g e

# formatting a string using a numeric constant


print("Hello, I am {} years old !".format(18))

print("This is {} {} {} {}"
.format("one", "two", "three", "four"))

differentdatatypes can be used in formatting


print("Hi ! My name is {} and I am {} years old"
.format("RAM",18 ))

Python String format_map() method is an inbuilt function in Python, which is used to return a dictionary key’s value.

a = {'r': 'ram', 's': 'sita'}

# Use of format_map() function


print("{r}'s last name is {s}".format_map(a))

a = {'A':'ankit','K':'komal' ,'AA': 'aakash','rr':"RRRR"}


print("'{A} {AA} {rr} is a classmate of {K}".format_map(a))
a = {'A':'ankit raj','K':'komal'}
print("{A} {K}".format_map(a))

Python offers this using a function index(), which returns the position of the first occurrence of a substring in a string.
Syntax:
a.index(b, begp, endp)

# initializing target string


a = "ram is a good boy"
# initializing argument string
62|P a g e

b = "boy"
#c = a.index(b, Starting index,ending index) #This is a syntax

c = a.index(b,2,120)
# where 2 is beg
print("The first position of boy after 2nd index : ", end="")
print(c)

Python String isalnum() method checks whether all the characters in a given string are alphanumeric or not. Alphanumeric means a
character that is either a letter or a number.

a = 'asdcf 123344'
print(a.isalnum())

Python String isalpha() method is a built-in method used for string handling. The isalpha() methods returns “True” if all characters in
the string are alphabets, Otherwise, It returns “False”. This function is used to check if the argument includes only alphabet
characters (mentioned below).

a = 'komal'
print(a.isalpha())

isdecimal()-It is a function in Python that returns true if all characters in a string are decimal. If all characters are not decimal the n it
returns false.

a = '12345699 '
print(a.isdecimal())
63|P a g e

Python String isdigit() method is a built-in method used for string handling. The isdigit() method returns “True” if all characters in the
string are digits, Otherwise, It returns “False”. This function is used to check if the argument contains digits such as 0123456789

b = '1234wedwydwgdj577'
print(b.isdigit())

Python String isidentifier() method is used to check whether a string is a valid identifier or not. The method returns True if the string
is a valid identifier else returns False. The method does not take any parameters.

Python String islower() method checks if all characters in the string are lowercase. This method returns True if all alphabets in a string
are lowercase alphabets. If the string contains at least one uppercase alphabet, it returns False

a = "CYBER SECURITY"
print(a.lower())

a = "craw security"
b = "Craw security"
# checking which string is completely lower
print("Is cyber security in use lower words ? : " + str(a.islower()))
print("Is Cyber securitu in use lower words ? : " + str(b.islower()))

Python String isnumeric() method is a built-in method used for string handling. The isnumeric() method returns “True” if all
characters in the string are numeric characters, Otherwise, It returns “False”.

a = '1234567wertyh63738'
print(a.isnumeric())
64|P a g e

b = '12345678'
print(b.isnumeric())

The isprintable() method returns “True” if all characters in the string are printable or the string is empty, Otherwise, It returns
“False”.

 Digits ( 0123456789 )
 Uppercase letters ( ABCDEFGHIJKLMNOPQRSTUVWXYZ )
 Lowercase letters ( abcdefghijklmnopqrstuvwxyz )
 Punctuation characters ( !”#$%&'()*+, -./:;?@[\]^_`{ | }~ )
 Space ( )

a = 'Ankit Raj'
print(a.isprintable())
# checking if \n is a printable character
a = 'Ankit\n Raj'
print(a.isprintable())

a = ''
print(a.isprintable())
a = "1234567ggjjgh4777"
a = 1234566
print(a.isprintable())

The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”.

 ‘ ‘ – Space
65|P a g e

 ‘\t’ – Horizontal tab


 ‘\n’ – Newline
 ‘\v’ – Vertical tab
 ‘\f’ – Feed
 ‘\r’ – Carriage return

istitle() is an inbuilt string function that returns True if all the words in the string are title cased otherwise returns False.

a = 'Ram And Sita'


print(a.istitle())

Python String isupper() method returns whether or not all characters in a string are uppercased or not.

a = 'RAM'
print(a.isupper())

join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This fu nction joins
elements of a sequence and makes it a string. In use set list tuple and Disctonary

a = ['1', '2', '3', '4']


b = "@#@#@#@ "
b = b.join(a)
print(b)
e ='SECURITY'
e1 = '____-'.join(e)
print(e1)
66|P a g e

Python String lower() method converts all uppercase characters in a string into lowercase characters and returns it

a = 'HHi how are you'


print(a.lower())

Python String lstrip() method returns a copy of the string with leading characters removed

a = '++++++ .... hi ram'


print(a.lstrip('+.123 '))
replace()

a ='ram is a good boy.'


print(a.replace('is','are'))
removeprefix()

a ='ram is a good boy.'


print(a.removeprefix('r'))

Escape Characters

To insert characters that are illegal in a string, use an escape character

\' Single Quote

a = 'hi\'how are you.'


print(a)

\\ Backslash
67|P a g e

a = "This will be one \\ (backslash)."


print(a

\n New Line

a = "Hello\nWorld"
print(a)

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\000 Octal value

\xhh Hex value

Module 11 :- Python List

list are the containers to store a set of values of any data type.List are mutable so we can modify its element.

A list is created by placing elements inside square brackets [], separated by commas.

A =list(input(“Enter elements”))

a = list(“Happy”)
68|P a g e

Print(a) [‘H’,’a’,’p’,’p’,y]

Or a = [“akash”,”apple’’,23,12.34,flase]

Print(a) and print(a[3])

List Indexing

A list can be indexed just like a string.

Ex:- A = [1,23,”ram’’,34.56]

Print(a[0]) = 1

Print(a[3]) = ram and Print(a[12]) = error

Ex:- Grocery =[“dove”,’’vimbar’’,’’vegetable’’]

Print(a[2]) = vegetable

List function

sort and reverse (ascending order and descending order change it)

a = [1,23,2,4,7,2]

a.sort()print(a) output =[1,2,4,7,23]

a.reverse()

print(a) output=[23,7,4,2,1]

list Slicing

print(a[:5]) or print(a[: : -1]) or Print(a[:]) or print(a[2:4])


69|P a g e

List Minimum and Maixmum function

Print(min(a)) and print(max(a))

List append function (add in end)

a.append(any number)

print(a)

ex :- a.append(5) adds 5 at the end of the list

only cheek append no

a = []

a.append[23]

a.append[34]

a.append[12]

print(a) = [23,34,12]

list Insert function

a.insert(2,3) this will be add 3 at 2 index

print(a)

remove function

a.remove(any number)
70|P a g e

print(a)

Erase last element

a.pop() or a.pop(<index>)

print(a)

Clear Function

a.clear()

print()

Deleting Elements

Del a[index]

Del a[1:2] deletes sliceof1:2

Del a deletes all list

Count function

a = ['ram','gita','sita','rita']
print(a.count('ram'))
Extend function

a =[1,2,3,4,5]

b = [123,456,677]

a.extend(b)
71|P a g e

print(a)

Sum function

A = [122,344,4]

Print(sum(a))

Module 12 :- Python Tuple ()

A tuple is immutable date type in python.

Note :- list are made by square brackets.[]

Tuple are made by curved bracket.()

Ex- tp = (1,2,3,4)

Print(tp)

tp(2) = 34 print(tp) = tuple is immutable

a=() Empty tuple

a = (2,) Tuple with only one element needs a comma.

A = (2,) print(a)

How to enter change value

a=1
72|P a g e

b =3

Temp =a

a=b b = temp print(a,b) out put 3 1 this is tradinol mathod to enterchange value

a,b =b,a

Print(a,b) 3 1

Gooogle list of python

1 Lists are mutable Tuples are immutable

2 Implication of iterations is Time-consuming The implication of iterations is comparatively Faster

3 Lists consume more memory Tuple consume less memory as compared to the list

4 Lists have several built-in methods Tuple does not have many built-in methods.

5 The unexpected changes and errors are more likely to occur In tuple, it is hard to take place.
73|P a g e

Module 13 :-Dictionary & Sets

1Dictionary is a collection of Key and value (key:value) pairs. Dictionary are mutable so we can modify it’s item,without changing their
identity. Dictionary is not a sequence, it’s unordered set of elements.

Its used curly bracket {}.

Syntex:- a = {} ,print(type(a))

An item has a key and a corresponding value that is expressed as a pair (key: value).

b ={“Ram” : ”Fruit”, “Bishal” : “Fish”,”Sita” : “Roti” ,“Shubham”:{“B” : “maggie”, “L”: “kadu” , “D” : “chicken”}}

print(b[“Shubham”] 2nd step [“B”]

add on b

b[“Akash ”] = “Biryani”

print(b)

del b[“Akash ”]

a = {'name': 'Facebook', 'ESTD': 2004}


print(a['name'])
print(a.get('ESTD'))
# Trying to access keys which doesn't exist throws error
print(a.get('address'))
# KeyError
print(a['address'])
74|P a g e

Method Description

clear() Removes all items from the dictionary.

copy() Returns a shallow copy of the dictionary.

fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).

get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).

items() Return a new object of the dictionary's items in (key, value) format.

keys() Returns a new object of the dictionary's keys.

Removes the item with the key and returns its value or d if key is not found. If d is not
pop(key[,d])
provided and the key is not found, it raises KeyError.
75|P a g e

Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is
popitem()
empty.

Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a
setdefault(key[,d])
value of d and returns d (defaults to None).

update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.

values() Returns a new object of the dictionary's values

a= {1: 1, 2: 4, 3: 9, 4: 16, 5: 25,6:36,7:49,8:64,9:81,10:100}


# remove a particular item, returns its value
print(a.pop(4))
print(a)
print(a.popitem())
print(a)
# remove all items

a.clear()
print(a.copy())
print(a.update())
print(a.popitem())
print(a.values())
print(a.keys())
76|P a g e

fruits= ["Apple", "Mango", "orange", "Banana"]


fruit_dictionary= dict.fromkeys(fruits, "sweet")
print(fruit_dictionary)

#use updation

a = {'A': 'mango', 'B': 'banana', }


b = {'B': 'bingo'}
c = {'c': 13*126}
d ={'d':'cow'}

print("Original Dictionary:")
print(a)
a.update(b)
a.update(d)
a.update(c)

print("Dictionary after updation:")


print(a)

a= {1: 1, 2: 4, 3: 9, 4: 16, 5: 25,6:36,7:49,8:64,9:81,10:100}


# remove a particular item, returns its value
print(a.pop(4))
print(a)
print(a.popitem())
print(a)
# remove all items
a.clear()
Squares()
77|P a g e

a = {x: x*x for x in range(8)}


print(a)
or

a= {}
for x in range(8):
a[x] = x*x
print(a)

Odd squares

# Dictionary Comprehension with if conditional


a = {x: x*x for x in range(45) if x % 2 == 1}
print(a)

# Iterating through a Dictionary


a = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81, 10:100}
for i in a:
print(a[i])

Dictionary Built-in Functions

Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform different tasks.

Function Description
78|P a g e

all() Return True if all keys of the dictionary are True (or if the dictionary is empty).

any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.

len() Return the length (the number of items) in the dictionary.

sorted() Return a new sorted list of keys in the dictionary.

# Dictionary Built-in Functions


a = {0: 0, 1: 1,03: 9, 5: 25, 7: 49, 9: 81}
print(all(a))
print(any(a))
print(len(a))
print(sorted(a))
b = {}
print(any(b))

SET :- Sets are used to store multiple items in a single variable. A set is an unordered collection of items. Every set element is unique and
must be immutable.

a = set()
print(type(a))
79|P a g e

Method Description

add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

difference() Returns the difference of two or more sets as a new set

difference_update() Removes all elements of another set from this set

Removes an element from the set if it is a member. (Do nothing if the


discard()
element is not in set)

intersection() Returns the intersection of two sets as a new set

intersection_update() Updates the set with the intersection of itself and another

isdisjoint() Returns True if two sets have a null intersection


80|P a g e

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element. Raises KeyError if the set is
pop()
empty

Removes an element from the set. If the element is not a member, raises a
remove()
KeyError

symmetric_difference() Returns the symmetric difference of two sets as a new set

symmetric_difference_update() Updates a set with the symmetric difference of itself and another

union() Returns the union of sets in a new set

update() Updates the set with the union of itself and others

Set Operations

Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this
with operators or methods.
81|P a g e

# Dictionary Built-in Functions


a = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(all(a))
print(any(a))
print(len(a))
print(sorted(a))
Method Operator
a.intersection(b) a&b
a.union(b) a|b
a.difference(b) a-b
a.symmetric_difference(b) a ^ b
a.issubset(b) a <= b
a.issuperset(b) a >= b

# Set union method


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B)

# intersecation
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A &B)

# Difference of two sets


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A - B)
82|P a g e

# Symmetric difference of two sets


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A ^ B)

A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
print(A.issubset(B))

A = {1, 2, 3, 4, 5}
B = {1, 2, 3}
C = {1, 2, 3}
print(A.issuperset(B))
print(B.issuperset(A))
print(C.issuperset(B))
83|P a g e

Module 14 :- Python Array

Array is an object that provide a mechanium for sveral data items with only one identitfier . Array is beneficial if you need to store
group of elements of same datatype . Array can increase or decrease thire size dynamically.-

Group of Ants :- Colony Group of Dogs :- Mute Group of Employees :- Team

Array can store only one type of data. Array size is not fixed . Array and list are not same. Array uses less memory than List.

Why we need Array?


84|P a g e

Arrays

Arrays are used to store multiple values in one single variable:

Example

Create an array containing car names:

cars = ["Ford", "Volvo", "BMW"]

What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!


85|P a g e

An array can hold many values under a single name, and you can access the values by referring to an index number.

Access the Elements of an Array

You refer to an array element by referring to the index number.

Example

Get the value of the first array item:

x = cars[0]
Example

Modify the value of the first array item:

cars[0] = "Toyota"

The Length of an Array

Use the len() method to return the length of an array (the number of elements in an array).

Example

Return the number of elements in the cars array:

x = len(cars)

Note: The length of an array is always one more than the highest array index.
86|P a g e

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.

Example

Print each item in the cars array:

for x in cars:
print(x)

Adding Array Elements

You can use the append() method to add an element to an array.

Example

Add one more element to the cars array:

cars.append("Honda")

Removing Array Elements

You can use the pop() method to remove an element from the array.

Example

Delete the second element of the cars array:


87|P a g e

cars.pop(1)

You can also use the remove() method to remove an element from the array.

Example

Delete the element that has the value "Volvo":

cars.remove("Volvo")

Note: The list's remove() method only removes the first occurrence of the specified value.

Array Methods

Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list


88|P a g e

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list


89|P a g e

sort() Sorts the list

Module 15 :- Python Date & Time

A Python program can handle date and time in several ways. Converting between date formats is a common chore for computers.
Python's time and calendar modules help track dates and times.

What is Tick?

Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 12:00am, January
1, 1970(epoch).
There is a popular time module available in Python which provides functions for working with times, and for converting between
representations. The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970(epoch)..
90|P a g e

Example

import time;# This is required to include time module.


ticks=time.time()
print("Number of ticks since 12:00am, January 1, 1970:", ticks)

This would produce a result something as follows −


Number of ticks since 12:00am, January 1, 1970: 1455508609.34375
Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in this form. Dates in the far future also
cannot be represented this way - the cut-off point is sometime in 2038 for UNIX and Windows.

What is TimeTuple?

Many of the Python's time functions handle time as a tuple of 9 numbers, as shown below −

Index Field Values

0 4-digit year 2016

1 Month 1 to 12

2 Day 1 to 31
91|P a g e

3 Hour 0 to 23

4 Minute 0 to 59

5 Second 0 to 61 (60 or 61 are leap-seconds)

6 Day of Week 0 to 6 (0 is Monday)

7 Day of year 1 to 366 (Julian day)

8 Daylight savings -1, 0, 1, -1 means library determines DST

For Example −

Live Demo
import time

print(time.localtime());

This would produce a result as follows −


time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, tm_hour = 9,
tm_min = 29, tm_sec = 2, tm_wday = 0, tm_yday = 46, tm_isdst = 0)
The above tuple is equivalent to struct_time structure. This structure has following attributes −
92|P a g e

Index Attributes Values

0 tm_year 2016

1 tm_mon 1 to 12

2 tm_mday 1 to 31

3 tm_hour 0 to 23

4 tm_min 0 to 59

5 tm_sec 0 to 61 (60 or 61 are leap-seconds)

6 tm_wday 0 to 6 (0 is Monday)

7 tm_yday 1 to 366 (Julian day)

8 tm_isdst -1, 0, 1, -1 means library determines DST

Getting current time


93|P a g e

To translate a time instant from seconds since the epoch floating-point value into a timetuple, pass the floating-point value to a function
(e.g., localtime) that returns a time-tuple with all valid nine items.

import time

localtime=time.localtime(time.time())
print("Local current time :",localtime)

This would produce the following result, which could be formatted in any other presentable form −
Local current time :time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15,
tm_hour = 9, tm_min = 29, tm_sec = 2, tm_wday = 0, tm_yday = 46, tm_isdst = 0)

Getting formatted time

You can format any time as per your requirement, but a simple method to get time in a readable format is asctime() −

import time

localtime=time.asctime(time.localtime(time.time()))
print("Local current time :",localtime)
This would produce the following result −
Local current time : Mon Feb 15 09:34:03 2016

Getting calendar for a month

The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given
month ( Jan 2008 ) −

import calendar

cal=calendar.month(2016,2)
94|P a g e

print("Here is the calendar:")


print(cal)
This would produce the following result −
Here is the calendar:
February 2016
Mo Tu We ThFrSa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29

The time Module

There is a popular time module available in Python, which provides functions for working with times and for converting between
representations. Here is the list of all available methods.

Sr.No. Function & Description

time.altzone

1 The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if
the local DST timezone is east of UTC (as in Western Europe, including the UK). Use this if the
daylight is nonzero.

time.asctime([tupletime])
2 Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14
2008'.
95|P a g e

time.clock( )
3 Returns the current CPU time as a floating-point number of seconds. To measure computational
costs of different approaches, the value of time.clock is smore useful than that of time.time().

time.ctime([secs])
4
Like asctime(localtime(secs)) and without arguments is like asctime( )

time.gmtime([secs])
5 Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC
time. Note − t.tm_isdst is always 0

time.localtime([secs])
6 Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local
time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant secs by local rules).

time.mktime(tupletime)
7 Accepts an instant expressed as a time-tuple in local time and returns a floating-point value with
the instant expressed in seconds since the epoch.

time.sleep(secs)
8
Suspends the calling thread for secs seconds.

time.strftime(fmt[,tupletime])
9 Accepts an instant expressed as a time-tuple in local time and returns a string representing the
instant as specified by string fmt.
96|P a g e

time.strptime(str,fmt = '%a %b %d %H:%M:%S %Y')


10
Parses str according to format string fmt and returns the instant in time-tuple format.

time.time( )
11
Returns the current time instant, a floating-point number of seconds since the epoch.

time.tzset()
12 Resets the time conversion rules used by the library routines. The environment variable TZ
specifies how this is done.

There are two important attributes available with time module. They are −

Sr.No. Attribute & Description

time.timezone
1
Attribute time.timezone is the offset in seconds of the local time zone (without DST) from UTC (>0
in the Americas; <=0 in most of Europe, Asia, Africa).

time.tzname
2 Attribute time.tzname is a pair of locale-dependent strings, which are the names of the local time
zone without and with DST, respectively.
97|P a g e

Operator Description

Addition (+) Adds and returns two timedelta objects

Subtraction (-) Subtracts and returns two timedelta objects

Multiplication (*) Multiplies timedelta object with float or int

Division (/) Divides the timedelta object with float or int

Floor division (//) Divides the timedelta object with float or int and return the int of floor value of the output

Modulo (%) Divides two timedelta object and returns the remainder

+(timedelta) Returns the same timedelta object

-(timedelta) Returns the resultant of -1*timedelta


98|P a g e

Operator Description

abs(timedelta) Returns the +(timedelta) if timedelta.days > 1=0 else returns -(timedelta)

str(timedelta) Returns a string in the form (+/-) day[s], HH:MM:SS.UUUUUU

repr(timedelta) Returns the string representation in the form of the constructor call

pip3 install pytz

The calendar Module

The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year.
By default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call
the calendar.setfirstweekday() function.
# Python program to print calendar for given year

# importing calendar library


importcalendar

defprintcalendar(year):

# printing calendar
print(calendar.calendar(year))

# driver program to test above function


99|P a g e

year =2019
printcalendar(year)

importcalendar
a = calendar.month(500 ,1 )
print ("Here is the calendar:")
print (a)
importcalendar
year = 30003
print(calendar.calendar(year))

Module 16:- File Handling (Input/ Output)

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.


100|P a g e

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images

f = open("demofile.txt", "r")
for x in f:
print(x)
a = open('C:\\Users\DEEPAK\Desktop\python.txt','r')
print(a.readline())
a.close()

a = open('cyber1.txt',mode='w')
a.write('Hello\n')
a.write('cyber security\n')
a.write('hi ankit and faisal\n')
a.write('create each day\n')
a.close()
print('writing success')
open
a = open('cyber.txt',mode='r')
101|P a g e

print(a)

a = open('craw.txt')
a.close()

a = open('cyber.txt',mode='w')
print('File Name :',a.name)
print('file mode ;-',a.mode)
print('file readable :',a.readable())
print('file writable:-',a.writable())
print('file closed ;',a.close())

Close Files

It is a good practice to always close the file when you are done with it.

Example

Close the file when you are finish with it:

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Note: You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.

Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:
102|P a g e

Example

Remove the file "demofile.txt":

import os
os.remove("demofile.txt")

Check if File exist:

To avoid getting an error, you might want to check if the file exists before you try to delete it:

Example

Check if file exists, then delete it:

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

Delete Folder

To delete an entire folder, use the os.rmdir() method:

Example

Remove the folder "myfolder":


103|P a g e

import os
os.rmdir("myfolder")

Module 17 : Multithreading

Multithreading is a threading technique in Python programming to run multiple threads concurrently by rapidly switching between
threads with a CPU

There are two main modules of multithreading used to handle threads in Python

.
1. The thread module
2. The threading module

Thread modules

It is started with Python 3, designated as obsolete, and can only be accessed with _thread that supports backward compatibility.

Syntax:

thread.start_new_thread ( function_name, args[, kwargs] )

1. thread.start_new_thread ( function_name, args[, kwargs] )


104|P a g e

Thread.py

1. import thread # import the thread module


2. import time # import time module
3.
4. def cal_sqre(num): # define the cal_sqre function
5. print(" Calculate the square root of the given number")
6. for n in num:
7. time.sleep(0.3) # at each iteration it waits for 0.3 time
8. print(' Square is : ', n * n)
9.
10. def cal_cube(num): # define the cal_cube() function
11. print(" Calculate the cube of the given number")
12. for n in num:
13. time.sleep(0.3) # at each iteration it waits for 0.3 time
14. print(" Cube is : ", n * n *n)
15.
16. arr = [4, 5, 6, 7, 2] # given array
105|P a g e

17.
18. t1 = time.time() # get total time to execute the functions
19. cal_sqre(arr) # call cal_sqre() function
20. cal_cube(arr) # call cal_cube() function
21.
22. print(" Total time taken by threads is :", time.time() - t1) # print the total time

Output:

Calculate the square root of the given number


Square is: 16
Square is: 25
Square is: 36
Square is: 49
Square is: 4
Calculate the cube of the given number
Cube is: 64
Cube is: 125
Cube is: 216
Cube is: 343
Cube is: 8
Total time taken by threads is: 3.005793809890747

Threading Modules

The threading module is a high-level implementation of multithreading used to deploy an application in Python

. To use multithreading, we need to import the threading module in Python Program


.
106|P a g e

Thread Class Methods

Methods Description

start() A start() method is used to initiate the activity of a thread. And it calls only once for each thread so that the
execution of the thread can begin.

run() A run() method is used to define a thread's activity and can be overridden by a class that extends the threads
class.

join() A join() method is used to block the execution of another code until the thread terminates.

Follow the given below steps to implement the threading module in Python Multithreading:

1. Import the threading module

Create a new thread by importing the threading module, as shown.

Syntax:

1. import threading

A threading module is made up of a Thread class, which is instantiated to create a Python thread.
107|P a g e

2. Declaration of the thread parameters: It contains the target function, argument, and kwargs as the parameter in
the Thread() class.

o Target: It defines the function name that is executed by the thread.


o Args: It defines the arguments that are passed to the target function name.

For example:

import threading

1. def print_hello(n):
2. print("Hello, how old are you ", n)
3. t1 = threading.Thread( target = print_hello, args =(18, ))

In the above code, we invoked the print_hello() function as the target parameter. The print_hello() contains one
parameter n, which passed to the args parameter.

3. Start a new thread: To start a thread in Python multithreading, call the thread class's object. The start() method can be
called once for each thread object; otherwise, it throws an exception error.

Syntax:

t1.start()
1. t2.start()

4. Join method: It is a join() method used in the thread class to halt the main thread's execution and waits till the complete
execution of the thread object. When the thread object is completed, it starts the execution of the main thread in Python.
108|P a g e

Joinmethod.py

1. import threading
2. def print_hello(n):
3. Print("Hello, how old are you? ", n)
4. T1 = threading.Thread( target = print_hello, args = (20, ))
5. T1.start()
6. T1.join()
7. Print("Thank you")

Output:

Hello, how old are you? 20


Thank you

When the above program is executed, the join() method halts the execution of the main thread and waits until the thread t1
is completely executed. Once the t1 is successfully executed, the main thread starts its execution.

5. Synchronizing Threads in Python

It is a thread synchronization mechanism that ensures no two threads can simultaneously execute a particular segment inside
the program to access the shared resources. The situation may be termed as critical sections. We use a race condition to avoid
the critical section condition, in which two threads do not access resources at the same time.

Let's write a program to use the threading module in Python Multithreading.


109|P a g e

Threading.py

1. import time # import time module


2. import threading
3. from threading import *
4. def cal_sqre(num): # define a square calculating function
5. print(" Calculate the square root of the given number")
6. for n in num: # Use for loop
7. time.sleep(0.3) # at each iteration it waits for 0.3 time
8. print(' Square is : ', n * n)
9.
10. def cal_cube(num): # define a cube calculating function
11. print(" Calculate the cube of the given number")
12. for n in num: # for loop
13. time.sleep(0.3) # at each iteration it waits for 0.3 time
14. print(" Cube is : ", n * n *n)
15.
16. ar = [4, 5, 6, 7, 2] # given array
17.
18. t = time.time() # get total time to execute the functions
19. #cal_cube(ar)
20. #cal_sqre(ar)
21. th1 = threading.Thread(target=cal_sqre, args=(ar, ))
110|P a g e

22. th2 = threading.Thread(target=cal_cube, args=(ar, ))


23. th1.start()
24. th2.start()
25. th1.join()
26. th2.join()
27. print(" Total time taking by threads is :", time.time() - t) # print the total time
28. print(" Again executing the main thread")
29. print(" Thread 1 and Thread 2 have finished their execution.")

Output:

Calculate the square root of the given number


Calculate the cube of the given number
Square is: 16
Cube is: 64
Square is: 25
Cube is: 125
Square is: 36
Cube is: 216
Square is: 49
Cube is: 343
Square is: 4
Cube is: 8
Total time taken by threads is: 1.5140972137451172
Again executing the main thread
Thread 1 and Thread 2 have finished their execution.
111|P a g e

Module 18: Python Mail Sending Porgram


SMTP :-The Simple Mail Transfer Protocal is an internet standard communication protocol for is an internet standard communication
protocol for electronic mail transmission . Mail servers and other message transmission .
Steps to send mail from Gmail account:
1. First of all, “smtplib” library needs to be imported.
2. After that, to create a session, we will be using its instance SMTP to encapsulate an SMTP connection.
s = smtplib.SMTP('smtp.gmail.com', 587)
In this, you need to pass the first parameter of the server location and the second parameter of the port to use. For Gmail, we use
port number 587.
3. For security reasons, now put the SMTP connection in the TLS mode. TLS (Transport Layer Security) encrypts all the SMTP
commands. After that, for security and authentication, you need to pass your Gmail account credentials in the login instance. The
compiler will show an authentication error if you enter invalid email id or password.
4. Store the message you need to send in a variable say, message. Using the sendmail() instance, send your message. sendmail()
uses three parameters: sender_email_id, receiver_email_id and message_to_be_sent. The parameters need to be in the same
sequence.
This will send the email from your account. After you have completed your task, terminate the SMTP session by using quit().

# Python code to illustrate Sending mail from

# your Gmail account

importsmtplib
112|P a g e

# creates SMTP session

s =smtplib.SMTP('smtp.gmail.com', 587)

# start TLS for security

s.starttls()

# Authentication

s.login("sender_email_id", "sender_email_id_password")

# message to be sent

message ="Message_you_need_to_send"
113|P a g e

# sending the mail

s.sendmail("sender_email_id", "receiver_email_id", message)

# terminating the session

s.quit()

Sending same message to multiple people


If you need to send the same message to different people. You can use for loop for that.
For example, you have a list of email ids to which you need to send the same mail. To do so, insert a “for” loop between the
initialization and termination of the SMTP session. Loop will initialize turn by turn and after sending the email, SMTP session will be
terminated.

# Python code to illustrate Sending mail

# to multiple users

# from your Gmail account

importsmtplib
114|P a g e

# list of email_id to send the mail

li =["[email protected]", "[email protected]"]

fordest inli:

s =smtplib.SMTP('smtp.gmail.com', 587)

s.starttls()

s.login("sender_email_id", "sender_email_id_password")

message ="Message_you_need_to_send"

s.sendmail("sender_email_id", dest, message)

s.quit()

Important Points:
 This code can send simple mail which doesn’t have any attachment or any subject.
 One of the most amazing things about this code is that we can send any number of emails using this and Gmail mostly put your
mail in the primary section. Sent mails would not be detected as Spam generally.
 File handling can also be used to fetch email id from a file and further used for sending the emails.
115|P a g e

Python MySQL

Python can be used in database applications.

One of the most popular databases is MySQL.

Download and install "MySQL Connector":

C:\Users\prakash\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install mysql-connector-python

Now you have downloaded and installed a MySQL driver.

To test if the installation was successful, or if you already have "MySQL Connector" installed, create a Python page with the following
content:

demo_mysql_test.py:

import mysql.connector

If the above code was executed with no errors, "MySQL Connector" is installed and ready to be used.

Create Connection
116|P a g e

Start by creating a connection to the database.

Use the username and password from your MySQL database:

demo_mysql_connection.py:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

print(mydb)

Now you can start querying the database using SQL statements.

Python MySQL Create Database

Creating a Database

To create a database in MySQL, use the "CREATE DATABASE" statement:

Example

create a database named "mydatabase":


117|P a g e

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

If the above code was executed with no errors, you have successfully created a database.

Check if Database Exists

You can check if a database exist by listing all databases in your system by using the "SHOW DATABASES" statement:

Example

Return a list of your system's databases:

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
118|P a g e

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
print(x)

Or you can try to access the database when making the connection:

Example

Try connecting to the database "mydatabase":

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

If the database does not exist, you will get an error.

You might also like