Python NOTES
Python NOTES
Prakash Chandrayan
1|P a g e
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.
The following table lists some of the most useful shortcuts to learn:
Shortcut Action
Shortcut Action
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
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
Python3
importkeyword
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
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.
Python
11|P a g e
# or (returns True)
print(TrueorFalse)
print(FalseandTrue)
print(notTrue)
12|P a g e
if'a'in'any name':
else:
print("\r")
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
Python3
fori inrange(10):
ifi ==6:
15|P a g e
break
print()
# loop from 1 to 10
i =0
whilei <10:
# If i is equals to 6,
# without printing
0ifi ==6:
i+=1
16|P a g e
continue
else:
# of i
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“
Python3
17|P a g e
i =20
if(i ==10):
print("i is 10")
elif(i ==20):
print("i is 20")
else:
Output
i is 20
def
def keyword is used to declare user defined functions.
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.
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.
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):
# Driver code
# Object instantiation
23|P a g e
Rodger =Dog()
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.
Python3
24|P a g e
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.
Python3
n =10
fori inrange(n):
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.
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.
Python3
# initializing number
a =4
b =0
try:
print(k)
28|P a g e
exceptZeroDivisionError:
finally:
# assert Keyword
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.
Python3
my_variable1 =20
my_variable2 =“adfsfsfd"
print(my_variable1)
print(my_variable2)
delmy_variable1
delmy_variable2
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.
# global variable
a =15
b =10
defadd():
c =a +b
print(c)
# calling a function
32|P a g e
add()
# nonlocal keyword
deffun():
var1 =10
defgun():
# in fun on line 2
nonlocal var1
33|P a g e
print(var1)
gun()
fun()
Output
25
20
PYHTON MODULE 3 : PYTHON VARIABLES & DATA TYPE
b = “craw” c=71.6758
2 variable name not allow space character Exam- a b c = 20 (wrong) , absd= 20( right)
34|P a g e
Note : Use Only alphyanumric value and under scorevalue Examp- A _Z( Right), a_z(right), 1-100(right), a123b(right), _ab=10(right)
underscore( _)
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.
2 String (str)
4 Booleans ( T or F)
7 Range
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.
MODULE 04 :- OPERATORS
What is operators ?
Types of operators
3 Comparison operators
Arithmetic Operators
print(500 + 200)
RESULT
700
print(500 - 200)
RESULT
300
print(500 * 200)
RESULT
100000
print(500 / 200)
37|P a g e
RESULT
2.5
print(500 // 200)
RESULT
2
print(500 % 200)
RESULT
100
print(500 ** 2)
RESULT
250000
print(+500 + 200)
RESULT
700
print(-500 + 200)
RESULT
-300
Comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation.
print(1==1)
print(1==2)
RESULT
True
False
print(1!=1)
print(1!=2)
RESULT
False
True
print(1>2)
print(2>1)
RESULT
False
True
40|P a g e
print(1<2)
print(2<1)
RESULT
True
False
print(1>=1)
print(1>=2)
RESULT
True
False
print(1<=1)
print(2<=1)
RESULT
True
False
41|P a g e
Logical Operators
print(1==1and2==2)
print(1==1and1==2)
RESULT
True
False
print(1==1or1==2)
print(1==2or3==4)
RESULT
True
False
print(notTrue)
print(notFalse)
42|P a g e
print(not(1==1))
print(not(1==3))
RESULT
False
True
False
True
Assignment Operators
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
a = a**a a=2
a =2**4 a **= 4
a = 16 print(a)
RESULT
16
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
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.
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.
print(500 | 200)
RESULT
508
47|P a g e
^ (cap)
print(500 ^ 200)
RESULT
316
print(500&200)
RESULT
192
RESULT
125
print(~500)
RESULT
-501
| __or__(self, other)
^ __xor__(self, other)
~ __invert__(self)
5.1 Introduction
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
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)
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
Stop Required. An integer number specifying at which position to stop (not included).
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
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)
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
Type :- Type function is used to find the data type of given variable in python.
Type(a) = class<int>
Print(a) Print(a)
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)
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
print(fractions.Fraction(1.1))
# As string
print(fractions.Fraction('1.1'))
This data type supports all basic operations. Here are a few examples.
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))
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)
print("This is {} {} {} {}"
.format("one", "two", "three", "four"))
Python String format_map() method is an inbuilt function in Python, which is used to return a dictionary key’s value.
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)
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
istitle() is an inbuilt string function that returns True if all the words in the string are title cased otherwise returns False.
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
Python String lower() method converts all uppercase characters in a string into lowercase characters and returns it
Python String lstrip() method returns a copy of the string with leading characters removed
Escape Characters
\\ Backslash
67|P a g e
\n New Line
a = "Hello\nWorld"
print(a)
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
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]
List Indexing
Ex:- A = [1,23,”ram’’,34.56]
Print(a[0]) = 1
Print(a[2]) = vegetable
List function
sort and reverse (ascending order and descending order change it)
a = [1,23,2,4,7,2]
a.reverse()
print(a) output=[23,7,4,2,1]
list Slicing
a.append(any number)
print(a)
a = []
a.append[23]
a.append[34]
a.append[12]
print(a) = [23,34,12]
print(a)
remove function
a.remove(any number)
70|P a g e
print(a)
a.pop() or a.pop(<index>)
print(a)
Clear Function
a.clear()
print()
Deleting Elements
Del a[index]
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))
Ex- tp = (1,2,3,4)
Print(tp)
A = (2,) print(a)
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
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
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.
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”}}
add on b
b[“Akash ”] = “Biryani”
print(b)
del b[“Akash ”]
Method Description
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.
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.
a.clear()
print(a.copy())
print(a.update())
print(a.popitem())
print(a.values())
print(a.keys())
76|P a g e
#use updation
print("Original Dictionary:")
print(a)
a.update(b)
a.update(d)
a.update(c)
a= {}
for x in range(8):
a[x] = x*x
print(a)
Odd squares
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.
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
intersection_update() Updates the set with the intersection of itself and another
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_update() Updates a set with the symmetric difference of itself and another
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
# intersecation
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
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.-
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.
Arrays
Example
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?
An array can hold many values under a single name, and you can access the values by referring to an index number.
Example
x = cars[0]
Example
cars[0] = "Toyota"
Use the len() method to return the length of an array (the number of elements in an array).
Example
x = len(cars)
Note: The length of an array is always one more than the highest array index.
86|P a g e
You can use the for in loop to loop through all the elements of an array.
Example
for x in cars:
print(x)
Example
cars.append("Honda")
You can use the pop() method to remove an element from the array.
Example
cars.pop(1)
You can also use the remove() method to remove an element from the array.
Example
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
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
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
What is TimeTuple?
Many of the Python's time functions handle time as a tuple of 9 numbers, as shown below −
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
For Example −
Live Demo
import time
print(time.localtime());
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
6 tm_wday 0 to 6 (0 is Monday)
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)
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
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
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.
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.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 −
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
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
Operator Description
abs(timedelta) Returns the +(timedelta) if timedelta.days > 1=0 else returns -(timedelta)
repr(timedelta) Returns the string representation in the form of the constructor call
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
defprintcalendar(year):
# printing calendar
print(calendar.calendar(year))
year =2019
printcalendar(year)
importcalendar
a = calendar.month(500 ,1 )
print ("Here is the calendar:")
print (a)
importcalendar
year = 30003
print(calendar.calendar(year))
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.
"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
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
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
import os
os.remove("demofile.txt")
To avoid getting an error, you might want to check if the file exists before you try to delete it:
Example
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
Example
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.py
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:
Threading Modules
The threading module is a high-level implementation of multithreading used to deploy an application in Python
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:
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.
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:
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.
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.
Threading.py
Output:
importsmtplib
112|P a g e
s =smtplib.SMTP('smtp.gmail.com', 587)
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
s.quit()
# to multiple users
importsmtplib
114|P a g e
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.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
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
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.
Creating a Database
Example
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
If the above code was executed with no errors, you have successfully created a database.
You can check if a database exist by listing all databases in your system by using the "SHOW DATABASES" statement:
Example
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
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)