SlideShare a Scribd company logo
1 of 172
PYTHON PROGRAMMING
1. Built-in Language Features: Variables, Data types, Basic
Mathematical operations, Operator Precedence, String
Operations, Functions, Conditional Statements, Classes and
Objects, Collections: Arrays, Sets, Tuples, Lists,
Dictionaries, Loops, File Operations, Exceptions.
2. Standard Library: Numpy, SciPy, Pandas, Scikit-learn,
Matplotlib, NLTK, TensorFlow, Keras, and PyTorch.
3. How to write code in Google Colab, Jupyter Notebook,
Pycharm & IDLE, and Scripting way.
4. To clear in the console :
>>> import os
>>> os.system(“cls”) – for windows
>>> "Ctrl + L“ – for Linux or macOS 1
 Who developed Python Programming is Guido Van
Rossum, Netherlands, 1980s, successor of ABC
programming.
 Python can be executed in two ways i) IDLE - Integration
Development Learning Environment. ii)Scripting way.
 Python datatypes are integer, string, float, double, etc.
 Python collections are Arrays, Lists, Sets, Tuples, and
Dictionaries.
 Python supports mathematical operations are addition,
subtraction, multiplication, division, and modulo division.
2
Python has single line comment is #, multiple line
comment is """ ...."""
Python supports loop statements are for, while etc.
Python is a case-sensitive programming language
Python is a popular language because it is having a
rich number of libraries or packages or
API(Application Programming Interface)
Python latest software version is 3.11.4
3
Python keywords can not be used as identifier or
variable name.
Python must start with a letter or an underscore
Python must contain only letters, digits or
underscores
Data types are two types i.e. 1) Mutable
2) Immutable, Mutable(Changeable) examples are
list, set, dictionary, ByteAarray, Immutable(Not
Changeable) examples are integer, float, byte,
string, tuples, frozenset. 4
5
Fig: Why Python
 Features of Python Programming
 Easy to learn and readable language
 Interpreted language
 Dynamically typed language
 Open source and free
 Large standard library
 Large community support
 Platform independent
 Graphical User Interface(GUI)
7
 Python Keywords:
1. Value Keywords: True, False, None.
2. Operator Keywords: and, or, not, in, is.
3. Control Flow Keywords: if, elif, else.
4. Iteration Keywords: for, while, break, continue, else.
5. Structure Keywords: def, class, with, as, pass, lambda.
6. Returning Keywords: return, yield.
7. Import Keywords: import, from, as.
 Python is a popular high-level programming language that
is widely used for developing a wide range of
applications, from web development to scientific
computing.
 Here is an example of a simple Python program that prints
"Hello, world!" to the console:
>>>print("Hello, world!")
>>>name=input("What is your name:”)
>>>print(("Hello,” + name + "!")
# create a dictionary
>>>person={"name": "John", "age": 30,"city": "New York"}
#retrieve values from the dictionary
>>>print(person["name"])) #output: John
>>>print(person["age"]) #output: 30
>>>print(person["city"]) #output: New York
9
Python has two membership operators: "in" and "not
in".
These operators are used to test if a value is a member
of a sequence or collection, such as a list, tuple, or set.
The "in" operator returns True if the left operand is a
member of the right operand, and False otherwise.
For example:
>>> my_list = [1, 2, 3, 4]
>>> 3 in my_list
True
>>> 5 in my_list
False 10
The "not in" operator returns True if the left
operand is not a member of the right operand, and
False otherwise.
For example:
>>> my_tuple = ('apple', 'banana', 'orange’)
>>> 'banana' not in my_tuple
False
>>> 'grape' not in my_tuple
True
11
Python has two identity operators: "is" and "is not".
These operators are used to compare the memory
locations of two objects to check whether they refer to
the same object or not.
The "is" operator returns True if the two operands
refer to the same object, and False otherwise.
For example:
>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> z = x
>>> x is y
False
>>> x is z
True 12
The "is not" operator returns True if the two
operands do not refer to the same object, and False
otherwise.
For example:
>>> a = 'hello’
>>> b = 'world’
>>> a is not b
True
>>> c = a
>>> a is not c
False
13
Operator Precedence: The order of execution of
mathematical operations in Python is similar to the
order used in conventional mathematics.
In maths there are three general operator
precedence priority levels
1. Exponents and roots
2. Multiplication, division and modulus
3. Addition and subtraction
The short form of Operator Precedence is
BODMAS - B-Brackets, O-Orders D-Division, M-
Multiplication, A-Addition, S-Subtraction. 14
15
BODMAS
16
Fig: Python Variables
17
Fig: Python Data Types
18
19
20
 Python Basic Operations: Here are some basic Python operations
that you can run either in a Python shell (Interactive mode) or a new
Python file (Script mode). >>>print("Hello, World!")
 Arithmetic operations:
# Addition
print(5 + 3) # Output: 8
# Subtraction
print(10 - 2) # Output: 8
# Multiplication
print(3 * 3) # Output: 9
# Division
print(9 / 2) # Output: 4.5
# Floor division
print(9 // 2) # Output: 4
# Modulus
print(9 % 2) # Output: 1
# Exponentiation
print(2 ** 3) # Output: 8 21
 String operations:
# String concatenation
print("Hello, " + "World!") # Output: Hello, World!
# String repetition
print("Python " * 3) # Output: Python Python Python
# String length
print(len("Python")) # Output: 6
22
List operations:
# Creating a list
my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]
# Accessing elements
print(my_list[0]) # Output: 1
# Updating elements
my_list[1] = 20
print(my_list) # Output: [1, 20, 3, 4, 5]
# Adding elements
my_list.append(6)
print(my_list) # Output: [1, 20, 3, 4, 5, 6] 23
List comprehensions: A feature of Python that allows you
to create lists in a very concise way.
>>>numbers = [1, 2, 3, 4, 5]
>>>squares = [n**2 for n in numbers]
# This will generate a new list of squares
print(squares) # Output: [1, 4, 9, 16, 25]
24
 Working with Dictionaries: Python Dictionary is an unordered
collection of items. Each item of a dictionary has a key/value pair.
# Creating a dictionary
my_dict = {"name": "Alice", "age": 25}
# Accessing elements
print(my_dict["name"]) # Output: Alice
# Updating elements
my_dict["age"] = 26
print(my_dict) # Output: {'name': 'Alice', 'age': 26}
# Adding elements
my_dict["city"] = "London"
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'London'}
25
 If-Else statements: An if statement is a conditional
statement that runs or skips code based on whether a
condition is true or false.
>>>x = 10
>>>if x > 5:
print("x is greater than 5") #Output: x is greater than 5
>>>else:
print("x is not greater than 5")
26
 Loops: In Python, for and while loops are typically used
when you want something to repeat a certain number of
times.
# Using a for loop with a range function
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4 each on a new line
# While loop
i = 0
while i < 5:
print(i)
i += 1 # Output: 0, 1, 2, 3, 4 each on a new line
27
 Functions: Functions in Python are blocks of reusable
code that perform a specific task.
# Defining a function
>>>def greet(name):
print(f"Hello, {name}!")
# Calling a function
>>>greet("Alice") # Output: Hello, Alice!
 Lambda functions: Also known as anonymous
functions, these are small, one-line functions defined with
the lambda keyword.
>>>double = lambda x: x * 2
>>>print(double(5)) # Output: 10 28
 Using Built-in functions like map, filter, reduce:
# map applies a function to all items in an input list
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
# filter creates a list of elements for which a function returns true
numbers = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # Output: [2, 4]
# reduce applies a rolling computation to sequential pairs of values in a list
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce((lambda x, y: x * y), numbers)
print(product) # Output: 120
29
 Exception Handling: You can handle exceptions using
try/except blocks in Python.
>>>try:
print(5 / 0) # This will cause a ZeroDivisionError
>>>except ZeroDivisionError:
print("You can't divide by zero!") # Output: You can't divide by zero!
30
 File handling: Python provides basic functions and
methods necessary to manipulate files.
# Writing to a file (NOTE: This will overwrite any existing file content)
>>>with open('test.txt', 'w') as file:
file.write('Hello, World!')
# Reading from a file
>>>with open('test.txt', 'r') as file:
print(file.read()) # Output: Hello, World!
31
 Imports: Python has a wide array of built-in modules that
you can import into your script.
>>>import math
>>>print(math.sqrt(16)) # Output: 4.0
32
 Classes and Objects: Python is an object-oriented
programming language.
 You can define classes and create instances of those
classes (objects).
>>>class MyClass:
def greet(self):
print("Hello, World!")
>>>obj = MyClass() # Creating an object
>>>obj.greet() # Output: Hello, World!
33
34
Fig: Python Cheat Sheet
Python Basics
35
Fig: Write a python program to perform arithmetic
operations using static input
36
Fig: Write a python program to perform arithmetic
operations using dynamic input
37
38
# Python program to perform all arithmetic operations
>>>a=int(input("Enter value of a:"))
>>>b=int(input("Enter value of b:"))
>>>c=a+b
>>>d=a-b
>>>e=a*b
>>>f=a/b
>>>g=a%b
>>>print("Addition",c)
>>>print("Subtraction",d)
>>>print("Multiplication", e)
>>>print("Division",f)
>>>print("Modulo Division",g)
39
#Write a python program to swap two numbers
using a third variable using static input
>>>a=3
>>>b=4
>>>t=a
>>>a=b
>>>b=t
>>>print("After swapping:", a, b)
40
#Write a python program to swap two numbers
without using third variable & using static
input
>>>a=3
>>>b=4
>>>a=a+b
>>>b=a-b
>>>a=a-b
>>>print("After swapping:", a, b)
41
1) Write a python program to Swapping of Two Numbers:
Example : x, y = 30, 40
print(x, y)
x, y = y, x
print(x, y)
Output :
30 40
40 30
2) Write a Python program to print string N times :
Example : n = 5
a= "python"
print(a * n)
Output :
pythonpythonpythonpythonpython
# Write a python program to print arrays
people=["Dr Asadi", "Jos", "Jenkins"]
print(people)
print(people[0])
print(people[1])
print(people[2])
#Write a python program to print lists
thislist=["Class", "Date", "Time"]
print(thislist)
43
#Write a python program to print tuples
thistuple=("Blue","Red","Green")
print(thistuple)
#Write a python program to print sets
thisset={"apple","potato","candy"}
print(thisset)
#Write a python program to print a dictionaries
thisdict={"name":"Charles","name":"Jackson","name":"Dr Asadi"}
print(thisdict)
44
# Write a python program to perform swapping using third variable
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
t=a
a=b
b=t
print("After swapping:", a, b)
# Write a python program to perform swapping without using third variable
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
a=a+b
b=a-b
a=a-b
print("After swapping:", a, b)
45
# Write a python program to perform Armstrong number: Armstrong number is a
number that is the sum of its own digits each raised to the power of the number of
digits.
def is_armstrong(num):
sum = 0
temp = num
num_length = len(str(num))
while temp > 0:
digit = temp % 10
sum += digit ** num_length
temp //= 10
if num == sum:
return True
else:
return False
num = int(input("Enter a number: "))
if is_armstrong(num):
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
46
# Write a Python program that generates prime numbers from 1 to n, where n is
an input provided by the user
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
num = int(input("Generate prime numbers up to: "))
print("Prime numbers up to", num, "are:")
for i in range(1, num+1):
if is_prime(i):
print(i) 47
C:UsersSARAVATHI>python primegen.py
Generate prime numbers up to: 100
Prime numbers up to 100 are: 2, 3, 5, 7, 11, 13,
17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97
 Python Loops: Python has two primitive loop
commands:
1. while loop
2. for loop
a) while: With the while loop we can execute a set of
statements as long as a condition is true.
#Write a python program to demo "while " loop
i = 1
while i < 6:
print(i)
i += 1
48
49
Fig: Python Conditional Statements
 for loop: A for loop is used for iterating over a sequence
(that is either a list, a tuple, a dictionary, a set, or a string).
 for is an iterator method as found in other object-
orientated programming languages.
 With the for loop we can execute a set of statements, once
for each item in a list, tuple, set etc.
 # Write a Python program demo for "for loop"
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
50
51
Fig: Python Looping Statements
# Write a python program to find the oldest
person inside the ages dictionary
ages={"java":36,"python":98,"devops":24}
oldest_person=None
current_biggest_age = 0
for name in ages:
age=ages[name]
if age>current_biggest_age:
oldest_person=name
current_biggest_age=age
print(oldest_person)
52
# To perform student details using class concept
class stud():
def details(marks,mark1,mark2,mark3,name):
marks.m1=mark1
marks.m2=mark2
marks.m3=mark3
marks.n=name
def _print(marks):
print("Enter the mark1: ",marks.m1)
print("Enter the mark2: ",marks.m2)
print("Enter the mark3: ",marks.m3)
print("Enter the name: ",marks.n)
s=stud()
s.details(70,80,90,"navya")
s._print() 53
 Python Collections are Arrays, Lists, Sets, Tuples and
Dictionaries
 1)Arrays : Arrays are used to store multiple values in one
single variable using square brackets.
 #Example : Create an array containing car names
>>> cars = ["Ford", "Volvo", "BMW"]
54
55
 2) Lists : Lists are used to store multiple items in a single
variable using square brackets.
 List items are ordered, changeable, and allow duplicate
values.
 List items are indexed, the first item has index [0], the
second item has index [1] etc.
 Example : Create a List:
>>> thislist = ["apple", "banana", "cherry"]
>>> print(thislist)
56
57
 3) Sets: Sets are used to store multiple items in a single
variable with curly brackets or flower braces.
 A set is a collection that is unordered, unchangeable*,
and unindexed and does not allow duplicate values.
 Example : Create a Set:
>>> thisset = {"apple", "banana", "cherry"}
>>> print(thisset)
58
59
 4) Tuples: Tuples are used to store multiple items in a
single variable with round brackets or parenthesis.
 A tuple is a collection which is ordered and unchangeable.
 Tuple items are indexed, the first item has index [0], the
second item has index [1] etc.
 Example : Create a Tuple:
>>> thistuple = ("apple", "banana", "cherry”)
>>> print(thistuple)
60
61
 5) Dictionaries: Dictionaries are used to store data values
in key : value pairs are written with curly brackets.
 A dictionary is a collection which is ordered*, changeable
and do not allow duplicates.
 Example : Create and print a dictionary:
>>>thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
>>>print(thisdict)
62
63
 Concepts of Python Programming
1. Arrays: It is containers which are able to store more than
one item at the same time.
2. Strings : In python, Strings contain alphanumeric values
that are usually enclosed in single or double quotation
marks.
3. Lists : It is used to store or organize data in a sequential
order. This data can be string, numbers, or iterables like a
list.
4. Sets: Sets are used to store multiple items in a single
variable with curly brackets or flower braces.
5. Tuples : A tuple is another data collection type in python. It
is also used to store and organize data in the form of a list.
6. Dictionaries : A dictionary is a python collection that stores
data as key-value pairs.
7. Python functions: A function is a block of code that only
runs when it is called. You can pass data, known as
parameters, into a function.
8. Python Class: Python is an object, with its properties and
methods. A Class is like an object constructor, or a "blueprint"
for creating objects.
9. Python exceptions: An exception is an event, which occurs
during the execution of a program that disrupts the
normal flow of the program's instructions.
10. Python files: Python treats files differently as text or binary
and this is important. Text files are simple text whereas
binary files contain binary data which is only readable by
computer.
 Python Arrays: An array is a container that can hold a fixed
number of items and these items should be of the same type.
 Most of the data structures make use of arrays to implement
their algorithms.
 The related terminology of arrays is
a) Element: Each item stored in an array is called an element.
b) Index: Each location of an element in an array has a
numerical index, which is used to identify the element.
 Array operations are
 Traverse: Print all the array elements one by one.
 Insertion: Adds an element at the given index.
 Deletion: Deletes an element at the given index.
 Search: Searches an element using the given index or value.
 Update: Updates an element at the given index. 66
#Write a python program to add two matrices 3X3
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
67
68
# Write a python program to perform Matrix multiplication of 3X3
x=[[1,2,3],[4,5,6],[7,8,9]]
y=[[9,8,7],[6,5,4],[3,2,1]]
result=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(x)):
for j in range(len(x[0])):
result[i][j]=x[i][j]*y[i][j]
for r in result:
print(r)
# Program to add two matrices using nested loop of 3X3
X = [[3,3,3],
[3 ,3,3],
[3 ,3,3]]
Y = [[3,3,3],
[3,3,3],
[3,3,3]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
69
# Program to transpose a matrix using a nested loop
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)
70
# Program to multiply two matrices using nested loops of 3X3
X = [[3,3,3], # 3x3 matrix
[3 ,3,3],
[3 ,3,3]]
Y = [[3,3,3,3], # 3x4 matrix
[3,3,3,3],
[3,3,3,3]]
result = [[0,0,0,0], # result is 3x4
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
for k in range(len(Y)): # iterate through rows of Y
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r) 71
Python Strings: A string is a sequence of
characters.
A character is simply a symbol.
For example, the English language has 26
characters.
Words and sentences are collections of characters,
and so are Python strings.
The most common functions used from the library
are:
1. strlen("name of string") – it is for string length
2. strcpy( dest, source) – it is for copy string
3. strcmp( string1, string2 ) – it is for comparison
4. strrev(dest, source) – it is for string reverse 72
73
The nine most commonly used functions in the string
library are: strcat( ) - concatenate two strings.
strchr( ) - string scanning operation.
strcmp( ) - compare two strings.
# Defining strings in Python
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
74
# Python String Operations
str1 = 'Hello'
str2 ='World!'
# using ‘+’
print('str1 + str2 = ', str1 + str2)
# using ‘*’
print('str1 * 3 =', str1 * 3)
# Iterating through a string
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found') 75
76
Fig: Write a Python program to perform iterating through a string
# Write a python program to check the given string is Palindrome or not
str1="MADAM"
j=-1
flag=0
for i in str1:
if i!=str1[j]:
flag=1
break
j=j-1
if flag==1:
print("It is not Palindrome")
else:
print("It is Palindrome")
77
 Python Functions: A function is a block of organized, reusable code
that is used to perform a single, related action.
 Python gives you many built-in functions like print(), abs() etc. but
you can also create your own functions, these functions are
called user-defined functions.
 Rules to define a function in Python.
1. Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) )
2. Any input parameters or arguments should be placed within these
parentheses.
3. The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
4. The code block within every function starts with a colon (:) and is
indented.
5. The statement return [expression] exits a function, optionally passing
back an expression to the caller.
 Syntax: def my_function():
print("Hello from a function") 78
79
Fig: Python Functions
The following are the different types of Python Functions
1. Python Built-in Functions
2. Python Recursion Functions
3. Python Lambda Functions
4. Python User-defined Functions
#Write a python program to perform factorial of a given number
n=int(input("Enter value of n:"))
fact=1
for i in range(1,n+1):
fact=fact*i
print("Factorial=",i,"=", fact)
C:UsersDr. Asadi>python fact.py
Enter value of n:5
Factorial= 1 = 1
Factorial= 2 = 2
Factorial= 3 = 6
Factorial= 4 = 24
Factorial= 5 = 120
80
#Write a python program to perform Functions Demo
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
C:UsersDr Asadi Srinivasulu>python funs.py
Emil Refsnes
Tobias Refsnes
Linus Refsnes
81
#Write a python program to print prime numbers from 1 to 100
for n in range(1,100):
count=0
for i in range(1,n+1):
if(n%i==0):
count=count+1
if(count==2):
print(n)
82
#Write a python program to find gcd of two numbers
def gcd_fun (num1, num2):
if (num2 == 0):
return num1
else:
return gcd_fun (num2, num1 % num2)
num1 =int (input ("Enter first number: "))
num2 =int (input ("Enter second number: "))
result = gcd_fun(num1,num2)
print("GCD of two number is: ")
print(result)
83
# Write a python program to find factorial of a number using
recursion
n=int(input("Enter a number: "))
def factorial(n):
while n!=0:
if n==1:
return 1
else:
return n*factorial(n-1)
print(factorial(n))
84
Python Classes
 Class is a collection of objects.
 Object is a Physical entity or Real time entity
 A class is a user-defined blueprint or prototype from which
objects are created.
 Classes provide a means of bundling data and functionality
together.
 Syntax: class ClassName:
# Statement
obj = ClassName()
print(obj.atrr)
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the
dot (.) operator. Eg.: Myclass.Myattribute 85
# Demo for class declaration in Python
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# Output: 10
print(Person.age)
# Output: <function Person.greet>
print(Person.greet)
# Output: "This is a person class"
print(Person.__doc__)
86
# Create a Car class with operations and print methods information
class Car:
# class attribute
wheels = 4
# initializer / instance attributes
def __init__(self, color, style):
self.color = color
self.style = style
# method 1
def showDescription(self):
print("This car is a", self.color, self.style)
# method 2
def changeColor(self, color):
self.color = color
c = Car('Black', 'Sedan')
# call method 1
c.showDescription()
# Prints This car is a Black Sedan
# call method 2 and set color
c.changeColor('White')
c.showDescription()
# Prints This car is a White Sedan
87
#Write a python program for the class concept
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("bark bark!")
def doginfo(self):
print(self.name + " is " + str(self.age) + " year(s) old.")
ozzy = Dog("Ozzy", 2)
skippy = Dog("Skippy", 12)
filou = Dog("Filou", 8)
ozzy.doginfo()
skippy.doginfo()
filou.doginfo()
88
C:UsersDr. Asadi>python clas.py
Ozzy is 2 year(s) old.
Skippy is 12 year(s) old.
Filou is 8 year(s) old.
"""Write a Python program to find the oldest person inside the
ages dictionary. """
ages={ "John":34,
"Matt":23,
"Natasha":27,
"Gabriella":33
}
oldest_person=None
current_biggest_age=0
for name in ages:
age=ages[name]
if age>current_biggest_age:
oldest_person=name
current_biggest_age=age
print(oldest_person)
89
 Python Exceptions: Exception handling is a mechanism
in computer programming for handling errors or
exceptional conditions that may arise during the execution
of a program.
 When an error occurs, or exception as we call it, Python
will normally stop and generate an error message.
 These exceptions can be handled using the try and except
statement
 Example: The try block will generate an exception,
because x is not defined:
x=5
try:
print(x)
except:
print("An exception occurred") 90
# Write a python program that demonstrates how to use
exception handling in Python
try:
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result = num1 / num2
print(f"Result: {result}")
except ValueError:
print("Invalid input: Please enter a valid number.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
91
92
# Write a python program that demonstrates how to
handle divide by zero exceptions in Python
while True:
try:
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result = num1 / num2
print(f"Result: {result}")
break
except ZeroDivisionError:
print("Division by zero is not allowed.")
93
94
Python File Operations
95
 A file is a container in computer storage devices used for
storing data.
 When we want to read from or write to a file, we need to
open it first. When we are done, it needs to be closed so
that the resources that are tied with the file are freed.
 Hence, in Python, a file operation takes place in the
following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file
 #Write a python program to create a file with content
 file=open("C:UsersDrAsadi Srinivasulubluecrest.txt","r")
 read_content=file.read()
 print(read_content)
96
 Reading Files in Python: After we open a file, we use
the read() method to read its contents. For example
 # Write a Python program to read a file with content
 file1 = open("C:UsersDr Asadi Srinivasulutest.txt", "r")
 # read the file
 read_content = file1.read()
 print(read_content)
97
Anonymous Functions (Lambda)
 A lambda function is a small anonymous function.
 A lambda function can take any number of arguments, but
can only have one expression.
 Syntax: lambda arguments: expression
 #1) Aim: write a python program to add 10 to argument a,
and return the result:
>>> x = lambda a : a + 10
>>> print(x(5))
>>>
98
#2)Write a Python program for lambda function
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(2))
#3) Write a Python program for lambda function
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(2))
print(mytripler(3))
99
TOP 10 PYTHON LIBRARIES
 Top 10 Python libraries for data science and cyber security:
1. NumPy: A library for numerical computing that provides support for
multi-dimensional arrays and matrices, along with a range of
mathematical operations.
2. Pandas: A library for data manipulation and analysis that provides
easy-to-use data structures and data analysis tools for working with
structured data.
3. Matplotlib: A library for data visualization that provides a wide range
of plotting functions and tools for creating high-quality charts and
graphs.
4. Scikit-learn: A library for machine learning that provides a wide
range of tools and algorithms for data preprocessing, feature
engineering, model selection, and evaluation.
5. TensorFlow: A library for machine learning that provides a range of
tools for building and training neural networks and other machine
learning models.
6. Keras: A high-level neural networks API that runs on top of
TensorFlow, making it easy to build and train deep learning
models.
7. Seaborn: A library for data visualization that provides high-
level interfaces for creating informative and attractive
statistical graphics.
8. SciPy: A library for scientific computing that provides a wide
range of tools and algorithms for numerical integration,
optimization, signal processing, linear algebra, and more.
9. Statsmodels: A library for statistical modeling that provides a
wide range of tools for regression analysis, time series
analysis, and other statistical modeling tasks.
10.NLTK: A library for natural language processing that provides
a wide range of tools and algorithms for text processing,
classification, and language modeling.
102
1. NumPy
 NumPy is a popular Python library that is used for performing
mathematical operations on large multi-dimensional arrays and
matrices.
 It provides high-performance, optimized mathematical functions that
are particularly useful for scientific computing, data analysis, and
machine learning applications.
 NumPy is a powerful library for scientific computing in Python, and
its efficient array operations and mathematical functions make it an
essential tool for many data scientists, researchers, and engineers.
 Here are some common use cases of NumPy in Python programming
1. Array creation
2. Array indexing and slicing
3. Mathematical operations
4. Broadcasting
5. Integration with other libraries
104
105
2. SciPy
 SciPy is an open-source scientific computing library for Python that
is built on top of NumPy.
 It provides a wide range of tools and algorithms for scientific
computing, including numerical integration, optimization, signal
processing, linear algebra, and more.
 SciPy is designed to be easy to use and provides a consistent API for
working with a wide range of scientific computing problems.
 SciPy is widely used in industry and academia for scientific
computing tasks.
 It is particularly popular among data scientists, researchers, and
engineers who work with scientific data and need to perform
complex computations.
 SciPy provides a powerful and flexible scientific computing
environment that allows users to solve a wide range of scientific
computing problems with ease.
 Some of the key features of SciPy include:
1. Numerical integration: SciPy provides a wide range of tools for
numerical integration, including integration of ordinary differential
equations (ODEs), partial differential equations (PDEs), and
quadrature.
2. Optimization: SciPy provides a wide range of optimization
algorithms for unconstrained and constrained optimization problems,
including nonlinear optimization and global optimization.
3. Signal processing: SciPy provides a wide range of tools for signal
processing, including filtering, spectral analysis, and wavelet
transforms.
4. Linear algebra: SciPy provides a wide range of tools for linear
algebra, including matrix factorization, eigensystem analysis, and
sparse matrix operations.
5. Statistical functions: SciPy provides a wide range of statistical
functions, including probability distributions, hypothesis testing, and
regression analysis.
108
3. Pandas
 Pandas is an open-source Python library for data manipulation and
analysis.
 It provides easy-to-use data structures and data analysis tools for
working with structured data, including data in CSV, Excel, SQL
databases, and other formats.
 Pandas is built on top of NumPy, another popular Python library for
numerical computing, and provides a powerful and flexible data
analysis environment for data scientists, analysts, and developers.
 Pandas is widely used in industry and academia for data analysis
and manipulation tasks.
 It is particularly popular among data scientists, analysts, and
developers who work with structured data.
 Pandas provides a powerful and flexible data analysis environment
that allows users to perform a wide range of data manipulation and
analysis tasks with ease.
 Some of the key features of Pandas include:
1. Data structures: Pandas provides two main data structures, Series
and DataFrame, that allow users to work with one-dimensional and
two-dimensional arrays of data, respectively.
2. Data manipulation: Pandas provides a wide range of data
manipulation tools for filtering, selecting, merging, and reshaping
data.
3. Data analysis: Pandas provides tools for descriptive statistics, data
visualization, time series analysis, and more.
4. Integration with other Python libraries: Pandas integrates seamlessly
with other popular Python libraries, such as NumPy, Matplotlib, and
Scikit-learn.
5. Performance: Pandas is optimized for performance and can handle
large datasets efficiently.
111
112
4. Scikit-learn
 Scikit-learn is an open-source Python library for machine learning.
 It provides a wide range of tools and algorithms for data
preprocessing, feature engineering, model selection, and evaluation.
 Scikit-learn is designed to be easy to use and provides a consistent
API for working with a wide range of machine learning models.
 Scikit-learn is widely used in industry and academia for a wide range
of machine learning applications, including classification, regression,
clustering, and dimensionality reduction.
 It is particularly popular among data scientists and machine learning
practitioners who are new to machine learning, as it provides a user-
friendly interface and comprehensive documentation.
 Some of the key features of scikit-learn include:
1. Wide range of machine learning algorithms: Scikit-learn provides a
wide range of machine learning algorithms, including linear models,
decision trees, random forests, support vector machines, and neural
networks.
2. Consistent API: Scikit-learn provides a consistent API for working
with a wide range of machine learning models, making it easy to
switch between different models.
3. Data preprocessing and feature engineering: Scikit-learn provides a
wide range of tools for data preprocessing and feature engineering,
including scaling, normalization, imputation, and feature selection.
4. Model selection and evaluation: Scikit-learn provides tools for model
selection and evaluation, including cross-validation, grid search, and
performance metrics.
5. Integration with other Python libraries: Scikit-learn integrates
seamlessly with other popular Python libraries, such as NumPy,
Pandas, and Matplotlib.
115
5. Theano
 Theano is a Python library for efficient numerical computation,
primarily used for deep learning applications.
 It was developed by the Montreal Institute for Learning Algorithms
(MILA) at the University of Montreal and released in 2007.
 Theano was designed to enable the creation and deployment of
complex mathematical models for machine learning, including deep
neural networks, convolutional neural networks, and recurrent
neural networks.
 Theano provides a high-level interface for building and training
deep learning models, making it easy to create complex neural
network architectures.
 It is built around a symbolic expression compiler that generates
optimized C code for numerical computation.
 This enables Theano to perform calculations on both CPUs and
GPUs, providing fast and efficient execution.
 Theano is widely used in industry and academia for building and
deploying deep learning models. However, since the library is no longer
being actively developed, many users have transitioned to newer libraries
such as TensorFlow or PyTorch.
 Some of the key features of Theano include:
1. Symbolic expression compiler: Theano's symbolic expression compiler
generates optimized C code for numerical computation, making it fast and
efficient.
2. Support for both CPUs and GPUs: Theano can perform calculations on
both CPUs and GPUs, providing fast and efficient execution.
3. Integration with NumPy: Theano integrates seamlessly with NumPy, a
popular numerical computing library for Python, making it easy to work
with multi-dimensional arrays.
4. Automatic differentiation: Theano includes a powerful automatic
differentiation engine that makes it easy to compute gradients for
backpropagation during training.
5. Extensible and customizable: Theano is highly extensible and
customizable, allowing users to add new functionality and customize the
library to their needs.
118
6. TensorFlow
 TensorFlow is an open-source machine learning framework
developed by Google that enables developers to build and deploy
deep learning models.
 It is designed to be a scalable and flexible platform for building a
wide range of machine learning applications.
 TensorFlow also includes several high-level APIs, such as Keras,
which make it easy to build and train deep learning models with just
a few lines of code.
 TensorFlow can be used to build a wide range of machine learning
applications, including computer vision, natural language
processing, and speech recognition.
 TensorFlow is widely used in industry and academia for building
and deploying machine learning models.
 It is supported by a large and active community of developers and
researchers who contribute to its ongoing development and
improvement.
 TensorFlow provides a wide range of tools and libraries for building
deep learning models, including:
1. Tensors: TensorFlow provides a powerful tensor library that allows
developers to perform efficient computation on multi-dimensional
arrays. Tensors are the basic building blocks for building deep
learning models in TensorFlow.
2. Neural network modules: TensorFlow includes a variety of pre-built
neural network modules, such as convolutional layers, recurrent
layers, and linear layers, that can be easily combined to create
complex models.
3. Optimizers: TensorFlow includes several built-in optimization
algorithms, such as stochastic gradient descent (SGD) and Adam,
that can be used to train deep learning models.
4. Data loaders: TensorFlow provides utilities for loading and
preprocessing data, including built-in support for popular data
formats like CSV and JSON.
5. Visualization tools: TensorFlow includes several visualization tools,
such as TensorBoard, that make it easy to monitor and debug models
121
122
123
7. Keras
 Keras is a high-level neural network API that is written in Python
and runs on top of several lower-level deep learning frameworks,
including TensorFlow, Theano, and CNTK.
 It was developed with the goal of providing a user-friendly interface
for building and training deep neural networks.
 Keras provides a simple and intuitive interface for building deep
learning models, making it accessible to both beginners and experts.
 It offers a wide range of pre-built layers and models that can be
easily combined to create complex architectures. Keras also includes
utilities for data loading, preprocessing, and evaluation.
 Keras is widely used in industry and academia for building and
training deep learning models for a wide range of applications,
including computer vision, natural language processing, and speech
recognition.
 Some of the key features of Keras include:
1. User-friendly API: Keras provides a simple and intuitive
interface for building deep learning models, making it easy for
users to get started with deep learning.
2. Modular architecture: Keras models are built using a modular
architecture, which allows users to easily add, remove, or
modify layers in their models.
3. Multi-backend support: Keras can run on top of several
different deep learning backends, including TensorFlow,
Theano, and CNTK, allowing users to choose the backend that
best suits their needs.
4. Built-in support for data augmentation: Keras includes utilities
for data augmentation, which can be used to increase the size of
training data and improve the generalization of models.
5. Easy model evaluation: Keras provides utilities for evaluating
the performance of trained models, including accuracy,
precision, recall, and F1 score.
126
8. PyTorch
 PyTorch is an open-source machine learning framework developed
by Facebook's artificial intelligence research group.
 It is designed to be a flexible, efficient, and easy-to-use platform for
building deep learning models.
 PyTorch is built around a dynamic computation graph, which allows
developers to easily create and modify models on the fly.
 It also includes a powerful autograd engine that enables automatic
differentiation, which makes it easy to compute gradients for
backpropagation during training.
 PyTorch is widely used in academia and industry for building deep
learning models for a wide range of applications, including
computer vision, natural language processing, and robotics.
 PyTorch includes a wide range of tools and utilities for building and
training deep learning models, including:
1. Tensors: PyTorch provides a powerful tensor library that enables
efficient computation on multi-dimensional arrays. Tensors are the
basic building blocks for building deep learning models in PyTorch.
2. Neural network modules: PyTorch includes a variety of pre-built
neural network modules, such as convolutional layers, recurrent
layers, and linear layers, that can be easily combined to create
complex models.
3. Optimizers: PyTorch includes several built-in optimization
algorithms, such as stochastic gradient descent (SGD) and Adam,
that can be used to train deep learning models.
4. Data loaders: PyTorch provides utilities for loading and
preprocessing data, including built-in support for popular data
formats like CSV and JSON.
5. Visualization tools: PyTorch includes several visualization tools,
such as TensorBoard, that make it easy to monitor and debug models
during training.
129
SEABORN
CHEATSHEET
9. Seaborn
 Seaborn is a Python data visualization library based on
Matplotlib. It provides a high-level interface for creating
informative and attractive statistical graphics.
 Seaborn makes it easy to create complex visualizations
with simple code.
 Seaborn offers a variety of visualization types, including
1. Scatter plots
2. Line plots
3. Bar plots
4. Histograms
5. Box plots
6. Heatmaps
7. Violin plots
8. Joint plots
9. Pair plots
10. Facet grids
 In addition to these basic types, Seaborn also provides
several built-in color palettes and styles to help you
customize your visualizations.
 Seaborn is designed to work well with Pandas data frames,
making it easy to create visualizations from your data.
 Seaborn is widely used in data science and machine
learning projects, as it provides an intuitive and
aesthetically pleasing way to visualize data.
132
Fig: Seaborn
133
Fig: Seaborn
134
Fig: Seaborn
135
SEABORN
CHEETSHEET
10. Matplotlib
 Matplotlib is a Python library for creating static, animated, and
interactive visualizations in Python.
 It is one of the most widely used visualization libraries in the data
science community and is known for its flexibility and customization
options.
 Matplotlib provides a variety of plotting functions and styles,
allowing users to create a wide range of visualizations, including line
plots, scatter plots, bar plots, histograms, and many others.
 It also provides functionality for adding annotations, legends, and
other design elements to visualizations.
 Matplotlib can be used in conjunction with other data science
libraries in the Python ecosystem, such as NumPy, Pandas, and
SciPy, making it a powerful tool for data analysis and visualization.
 Some key features of Matplotlib include:
1. Highly customizable: Matplotlib provides many options for
customizing visualizations, including colors, fonts, and styles.
2. Variety of plot types: Matplotlib provides functions for creating
many different types of plots, including line plots, scatter plots, bar
plots, histograms, and more.
3. Integration with other libraries: Matplotlib can be used in
conjunction with other popular data science libraries in the Python
ecosystem, such as NumPy, Pandas, and SciPy.
4. Interactive capabilities: Matplotlib can be used to create interactive
visualizations, allowing users to zoom, pan, and interact with their
data.
5. Large user community: Matplotlib has a large and active user
community, with many resources available online for learning and
troubleshooting.
138
11. Statsmodels
 Statsmodels is an open-source Python library for statistical modeling,
estimation, and inference.
 It provides a wide range of tools and algorithms for regression
analysis, time series analysis, hypothesis testing, and more.
Statsmodels is designed to be easy to use and provides a consistent
API for working with a wide range of statistical modeling problems.
 Statsmodels is widely used in industry and academia for statistical
modeling and analysis tasks.
 It is particularly popular among data scientists, statisticians, and
researchers who work with statistical data and need to perform
complex analyses.
 Statsmodels provides a powerful and flexible statistical modeling
environment that allows users to solve a wide range of statistical
modeling problems with ease.
 Some of the key features of Statsmodels include:
1. Regression analysis: Statsmodels provides a wide range of tools for
regression analysis, including linear regression, generalized linear
models, mixed-effects models, and more.
2. Time series analysis: Statsmodels provides a wide range of tools for
time series analysis, including autoregressive integrated moving
average (ARIMA) models, vector autoregression (VAR) models,
and more.
3. Hypothesis testing: Statsmodels provides a wide range of tools for
hypothesis testing, including t-tests, F-tests, and chi-square tests.
4. Visualization: Statsmodels provides tools for visualizing statistical
models and results, including plots of residuals, fitted values, and
more.
5. Integration with other Python libraries: Statsmodels integrates
seamlessly with other popular Python libraries, such as Pandas,
NumPy, and Matplotlib.
141
PYTHON BASICS
CHEETSHEET
12. NLTK
 NLTK (Natural Language Toolkit) is a popular open-source Python
library for natural language processing (NLP).
 It provides a wide range of tools and algorithms for text processing,
classification, and language modeling.
 NLTK is designed to be easy to use and provides a consistent API
for working with a wide range of NLP problems.
 NLTK is widely used in industry and academia for NLP tasks.
 It is particularly popular among data scientists, researchers, and
developers who work with text data and need to perform complex
NLP tasks.
 NLTK provides a powerful and flexible NLP environment that
allows users to solve a wide range of NLP problems with ease.
 Some of the key features of NLTK include
1. Text processing: NLTK provides a wide range of tools for text
processing, including tokenization, stemming, and part-of-speech
tagging.
2. Classification: NLTK provides tools for building and evaluating
classifiers, including naive Bayes classifiers, decision tree
classifiers, and maximum entropy classifiers.
3. Language modeling: NLTK provides tools for building and
evaluating language models, including n-gram models and
probabilistic context-free grammars (PCFGs).
4. Sentiment analysis: NLTK provides tools for sentiment analysis,
including tools for identifying positive and negative sentiments in
text.
5. Integration with other Python libraries: NLTK integrates seamlessly
with other popular Python libraries, such as Pandas, NumPy, and
Matplotlib.
144
Fig: NLTK
Cheetsheet
145
Python
Packages
# Write a python program to perform encryption and decryption
of given message using DES algorithm
from cryptography.fernet import Fernet
message = “Data Science"
key = Fernet.generate_key()
fernet = Fernet(key)
encMessage = fernet.encrypt(message.encode())
print("original string: ", message)
print("encrypted string: ", encMessage)
decMessage = fernet.decrypt(encMessage).decode()
print("decrypted string: ", decMessage)
146
# Write a python program to perform encryption and decryption
of given message using AES algorithm
from cryptography.fernet import Fernet
message = “cyberforensics"
key = Fernet.generate_key()
fernet = Fernet(key)
encMessage = fernet.encrypt(message.encode())
print("original string: ", message)
print("encrypted string: ", encMessage)
decMessage = fernet.decrypt(encMessage).decode()
print("decrypted string: ", decMessage)
147
# Write a python program to perform encryption and decryption
of given message using RSA algorithm
import rsa
publicKey, privateKey= rsa.newkeys(512)
message= "cybershiksha"
encMessage=rsa.encrypt(message.encode(),publicKey)
print("original string: ", message)
print("encrypted string: ", encMessage)
decMessage=rsa.decrypt(encMessage,privateKey).decode()
print("decrypted string: ", decMessage)
148
 Tools in Python programming
1. PyCharm IDE [Best Python IDE by a mile]
2. Python Anywhere [Best tool to run Python code online]
3. IDLE : It is Python's Integrated Development and Learning
Environment. It is a default editor that comes with Python.
4. Sublime Text : It is one of the most popular code editors for
programmers, supporting almost all platforms.
5. Atom : It is a tool that is a free and open-source text and source
code editor.
6. Jupyter Notebook : It is an open-sourced web-based application
which allows you to create and share documents containing live
code, equations, visualisations, and narrative text.
7. Spyder : It is an open-source, powerful scientific environment
written in python, built especially for data science.
8. Pip Package [Best Tool to Install Python packages]
9. Scikit-Learn [Best Python library for Data Science]
 Technologies used in Python Programming
1. Artificial intelligence (AI)
2. Machine Learning(ML)
3. Deep Learning
4. Cyber Security
5. Big Data
6. IoT
7. Web Development: Django, Pyramid, Bottle, Tornado, Flask, web2py
8. GUI Development: tkInter, PyGObject, PyQt, PySide, Kivy, wxPython
9. Scientific and Numeric: SciPy, Pandas, IPython.
10. Software Development: Buildbot, Trac, Roundup.
11. System Administration: Ansible, Salt, OpenStack, xonsh.
1) What is Python used for?
Ans) Python is a high-level, interpreted
programming language that is used for a wide
range of purposes, including web development,
scientific computing, data analysis, artificial
intelligence, and more.
2) What are some of the benefits of using
Python?
Ans) Python has a number of benefits, including its
ease of use, large and supportive community, vast
libraries and frameworks, and versatility.
151
3) What is a Python module?
Ans) A Python module is a collection of Python
code that can be reused in other programs.
4) What is the difference between a tuple and a
list in Python?
Ans) In Python, a tuple is an immutable data
structure, while a list is a mutable data structure.
This means that once a tuple is created, its values
cannot be changed, while values in a list can be
changed, added, or removed. Tuples use
parentheses, while lists use square brackets.
152
 5) What is a dictionary in Python?
 Ans) A dictionary in Python is an unordered collection of
key-value pairs, where each key is unique. Dictionaries are
used to store data that is accessed using keys, rather than
index numbers. They are defined using curly braces ({})
and can store a variety of data types.
 6) What is a function in Python and how is it defined?
 Ans) A function in Python is a block of code that performs
a specific task and can be called from other parts of the
program. Functions are defined using the "def" keyword,
followed by the function name and a set of parentheses that
may contain parameters. The code inside the function is
indented and runs whenever the function is called.
153
 7) What is an exception in Python and how is it handled?
 Ans) An exception in Python is an error that occurs during the
execution of a program. When an exception is raised, the
normal flow of execution is interrupted, and the program jumps
to the nearest exception handler. Exception handling in Python
is accomplished using the "try" and "except" keywords, where
the code that may raise an exception is placed inside the "try"
block, and the exception handling code is placed inside the
"except" block.
 8) Explain the concept of inheritance in Python.
 Ans) Inheritance is a mechanism where one class acquires the
properties and behavior of another class. The class that inherits
properties is called the derived class, and the class from which
it inherits properties is called the base class.
154
 9) What is the difference between 'is' and '==' in Python?
 Ans) 'is' is used to check if two variables refer to the same
object, whereas '==' is used to check if two variables have the
same value.
 10) What is a decorator in Python?
 Ans) A decorator is a function that takes another function as
input, adds some functionality to it, and returns it as output. It
is a way to modify the behavior of a function or class without
changing its source code.
 11) What are lambda functions in Python?
 Ans) Lambda functions are anonymous functions in Python that
are defined without a name. They are usually used as a one-
liner to perform simple operations and are created using the
'lambda' keyword.
155
 12) Explain the concept of generators in Python.
 Ans) Generators are functions that return an iterator, which
can be iterated over using the 'next()' function. Unlike lists,
generators do not store all the values in memory at once,
making them more memory-efficient.
 13) What is the difference between 'append' and
'extend' methods in Python?
 Ans) 'append' method adds a single element to the end of a
list, whereas 'extend' method can add multiple elements to
the end of a list, as it takes an iterable as input.
156
MCQS OF INTRODUCTION TO PYTHON
1. What is Python?
a) A programming language
b) A type of snake
c) A type of database
d) A type of operating system
Answer: a) A programming language
157
MCQS OF INTRODUCTION TO PYTHON
2. Which of the following is an example of a Python data
type?
a) string
b) int
c) list
d) all of the above
Answer: d) all of the above
158
MCQS OF INTRODUCTION TO PYTHON
3. What is the output of the following Python code?
print("Hello, World!")
a) Hello
b) World
c) Hello, World!
d) Nothing
Answer: c) Hello, World!
159
MCQS OF INTRODUCTION TO PYTHON
4. Which of the following is the correct way to declare a
variable in Python?
a) variable = value
b) value = variable
c) var = value
d) val = var
Answer: a) variable = value
160
MCQS OF INTRODUCTION TO PYTHON
5. Which of the following is used to end a line of code in
Python?
a) ;
b) :
c) .
d) None of the above
Answer: d) None of the above (Python uses line breaks to
separate lines of code)
161
MCQS OF INTRODUCTION TO PYTHON
6. Which of the following is a conditional statement in
Python?
a) for loop
b) while loop
c) if statement
d) function definition
Answer: c) if statement
162
MCQS OF INTRODUCTION TO PYTHON
7. What is the output of the following Python code?
x = 5
y = 2
print(x + y)
a) 3
b) 7
c) 10
d) Error
Answer: b) 7
163
MCQS OF INTRODUCTION TO PYTHON
8. What is the output of the following Python code?
my_list = [1, 2, 3, 4, 5]
print(my_list[2])
a) 1
b) 2
c) 3
d) 4
Answer: c) 3 (Python uses zero-based indexing, so the third
element in the list is at index 2)
164
MCQS OF INTRODUCTION TO PYTHON
9. Which of the following is a built-in Python function?
a) input()
b) print()
c) len()
d) all of the above
Answer: d) all of the above
165
MCQS OF INTRODUCTION TO PYTHON
10. What is the purpose of a function in Python?
a) To store data
b) To perform a specific task
c) To declare variables
d) None of the above
Answer: b) To perform a specific task
166
5 Big Reasons Python is Useful in Cybersecurity
1. Cybersecurity professionals can get up to speed
quickly
2. Cybersecurity teams can form quickly.
3. Python’s extensive library means cybersecurity tools
are already available.
4. Python can be used for nearly anything in
cybersecurity.
5. Scripts in Python can be developed quickly 167
168
169
5 Big Reasons Python is Useful in Data Science
1. Data Science professionals can get up to speed
quickly
2. Data Science teams can form quickly.
3. Python’s extensive library means Data Science tools
are already available.
4. Python can be used for nearly anything in Data
Science.
5. Scripts in Python can be developed quickly 170
171
Fig: Building Secure Python Application
172
https://www.youtube.com/@DrAsadiSrinivas

More Related Content

Similar to Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be willing to go firstpptx

Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Simplilearn
 
Pres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdfPres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdfRamziFeghali
 
Notes1
Notes1Notes1
Notes1hccit
 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLVijaySharma802
 
Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3FabMinds
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python ProgrammingDozie Agbo
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha BaliAkanksha Bali
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python ProgrammingVijaySharma802
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts Pavan Babu .G
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2sadhana312471
 

Similar to Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be willing to go firstpptx (20)

Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
Pres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdfPres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdf
 
Python Scipy Numpy
Python Scipy NumpyPython Scipy Numpy
Python Scipy Numpy
 
Python
PythonPython
Python
 
Notes1
Notes1Notes1
Notes1
 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIML
 
Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
 
Python
PythonPython
Python
 
Python basics
Python basicsPython basics
Python basics
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
Python programming
Python  programmingPython  programming
Python programming
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 

Recently uploaded

Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxPurva Nikam
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 

Recently uploaded (20)

POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
An introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptxAn introduction to Semiconductor and its types.pptx
An introduction to Semiconductor and its types.pptx
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be willing to go firstpptx

  • 1. PYTHON PROGRAMMING 1. Built-in Language Features: Variables, Data types, Basic Mathematical operations, Operator Precedence, String Operations, Functions, Conditional Statements, Classes and Objects, Collections: Arrays, Sets, Tuples, Lists, Dictionaries, Loops, File Operations, Exceptions. 2. Standard Library: Numpy, SciPy, Pandas, Scikit-learn, Matplotlib, NLTK, TensorFlow, Keras, and PyTorch. 3. How to write code in Google Colab, Jupyter Notebook, Pycharm & IDLE, and Scripting way. 4. To clear in the console : >>> import os >>> os.system(“cls”) – for windows >>> "Ctrl + L“ – for Linux or macOS 1
  • 2.  Who developed Python Programming is Guido Van Rossum, Netherlands, 1980s, successor of ABC programming.  Python can be executed in two ways i) IDLE - Integration Development Learning Environment. ii)Scripting way.  Python datatypes are integer, string, float, double, etc.  Python collections are Arrays, Lists, Sets, Tuples, and Dictionaries.  Python supports mathematical operations are addition, subtraction, multiplication, division, and modulo division. 2
  • 3. Python has single line comment is #, multiple line comment is """ ....""" Python supports loop statements are for, while etc. Python is a case-sensitive programming language Python is a popular language because it is having a rich number of libraries or packages or API(Application Programming Interface) Python latest software version is 3.11.4 3
  • 4. Python keywords can not be used as identifier or variable name. Python must start with a letter or an underscore Python must contain only letters, digits or underscores Data types are two types i.e. 1) Mutable 2) Immutable, Mutable(Changeable) examples are list, set, dictionary, ByteAarray, Immutable(Not Changeable) examples are integer, float, byte, string, tuples, frozenset. 4
  • 6.  Features of Python Programming  Easy to learn and readable language  Interpreted language  Dynamically typed language  Open source and free  Large standard library  Large community support  Platform independent  Graphical User Interface(GUI)
  • 7. 7  Python Keywords: 1. Value Keywords: True, False, None. 2. Operator Keywords: and, or, not, in, is. 3. Control Flow Keywords: if, elif, else. 4. Iteration Keywords: for, while, break, continue, else. 5. Structure Keywords: def, class, with, as, pass, lambda. 6. Returning Keywords: return, yield. 7. Import Keywords: import, from, as.
  • 8.  Python is a popular high-level programming language that is widely used for developing a wide range of applications, from web development to scientific computing.  Here is an example of a simple Python program that prints "Hello, world!" to the console: >>>print("Hello, world!") >>>name=input("What is your name:”) >>>print(("Hello,” + name + "!") # create a dictionary >>>person={"name": "John", "age": 30,"city": "New York"} #retrieve values from the dictionary >>>print(person["name"])) #output: John >>>print(person["age"]) #output: 30 >>>print(person["city"]) #output: New York
  • 9. 9
  • 10. Python has two membership operators: "in" and "not in". These operators are used to test if a value is a member of a sequence or collection, such as a list, tuple, or set. The "in" operator returns True if the left operand is a member of the right operand, and False otherwise. For example: >>> my_list = [1, 2, 3, 4] >>> 3 in my_list True >>> 5 in my_list False 10
  • 11. The "not in" operator returns True if the left operand is not a member of the right operand, and False otherwise. For example: >>> my_tuple = ('apple', 'banana', 'orange’) >>> 'banana' not in my_tuple False >>> 'grape' not in my_tuple True 11
  • 12. Python has two identity operators: "is" and "is not". These operators are used to compare the memory locations of two objects to check whether they refer to the same object or not. The "is" operator returns True if the two operands refer to the same object, and False otherwise. For example: >>> x = [1, 2, 3] >>> y = [1, 2, 3] >>> z = x >>> x is y False >>> x is z True 12
  • 13. The "is not" operator returns True if the two operands do not refer to the same object, and False otherwise. For example: >>> a = 'hello’ >>> b = 'world’ >>> a is not b True >>> c = a >>> a is not c False 13
  • 14. Operator Precedence: The order of execution of mathematical operations in Python is similar to the order used in conventional mathematics. In maths there are three general operator precedence priority levels 1. Exponents and roots 2. Multiplication, division and modulus 3. Addition and subtraction The short form of Operator Precedence is BODMAS - B-Brackets, O-Orders D-Division, M- Multiplication, A-Addition, S-Subtraction. 14
  • 18. 18
  • 19. 19
  • 20. 20
  • 21.  Python Basic Operations: Here are some basic Python operations that you can run either in a Python shell (Interactive mode) or a new Python file (Script mode). >>>print("Hello, World!")  Arithmetic operations: # Addition print(5 + 3) # Output: 8 # Subtraction print(10 - 2) # Output: 8 # Multiplication print(3 * 3) # Output: 9 # Division print(9 / 2) # Output: 4.5 # Floor division print(9 // 2) # Output: 4 # Modulus print(9 % 2) # Output: 1 # Exponentiation print(2 ** 3) # Output: 8 21
  • 22.  String operations: # String concatenation print("Hello, " + "World!") # Output: Hello, World! # String repetition print("Python " * 3) # Output: Python Python Python # String length print(len("Python")) # Output: 6 22
  • 23. List operations: # Creating a list my_list = [1, 2, 3, 4, 5] print(my_list) # Output: [1, 2, 3, 4, 5] # Accessing elements print(my_list[0]) # Output: 1 # Updating elements my_list[1] = 20 print(my_list) # Output: [1, 20, 3, 4, 5] # Adding elements my_list.append(6) print(my_list) # Output: [1, 20, 3, 4, 5, 6] 23
  • 24. List comprehensions: A feature of Python that allows you to create lists in a very concise way. >>>numbers = [1, 2, 3, 4, 5] >>>squares = [n**2 for n in numbers] # This will generate a new list of squares print(squares) # Output: [1, 4, 9, 16, 25] 24
  • 25.  Working with Dictionaries: Python Dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair. # Creating a dictionary my_dict = {"name": "Alice", "age": 25} # Accessing elements print(my_dict["name"]) # Output: Alice # Updating elements my_dict["age"] = 26 print(my_dict) # Output: {'name': 'Alice', 'age': 26} # Adding elements my_dict["city"] = "London" print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'London'} 25
  • 26.  If-Else statements: An if statement is a conditional statement that runs or skips code based on whether a condition is true or false. >>>x = 10 >>>if x > 5: print("x is greater than 5") #Output: x is greater than 5 >>>else: print("x is not greater than 5") 26
  • 27.  Loops: In Python, for and while loops are typically used when you want something to repeat a certain number of times. # Using a for loop with a range function for i in range(5): print(i) # Output: 0, 1, 2, 3, 4 each on a new line # While loop i = 0 while i < 5: print(i) i += 1 # Output: 0, 1, 2, 3, 4 each on a new line 27
  • 28.  Functions: Functions in Python are blocks of reusable code that perform a specific task. # Defining a function >>>def greet(name): print(f"Hello, {name}!") # Calling a function >>>greet("Alice") # Output: Hello, Alice!  Lambda functions: Also known as anonymous functions, these are small, one-line functions defined with the lambda keyword. >>>double = lambda x: x * 2 >>>print(double(5)) # Output: 10 28
  • 29.  Using Built-in functions like map, filter, reduce: # map applies a function to all items in an input list numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) # Output: [1, 4, 9, 16, 25] # filter creates a list of elements for which a function returns true numbers = [1, 2, 3, 4, 5] even = list(filter(lambda x: x % 2 == 0, numbers)) print(even) # Output: [2, 4] # reduce applies a rolling computation to sequential pairs of values in a list from functools import reduce numbers = [1, 2, 3, 4, 5] product = reduce((lambda x, y: x * y), numbers) print(product) # Output: 120 29
  • 30.  Exception Handling: You can handle exceptions using try/except blocks in Python. >>>try: print(5 / 0) # This will cause a ZeroDivisionError >>>except ZeroDivisionError: print("You can't divide by zero!") # Output: You can't divide by zero! 30
  • 31.  File handling: Python provides basic functions and methods necessary to manipulate files. # Writing to a file (NOTE: This will overwrite any existing file content) >>>with open('test.txt', 'w') as file: file.write('Hello, World!') # Reading from a file >>>with open('test.txt', 'r') as file: print(file.read()) # Output: Hello, World! 31
  • 32.  Imports: Python has a wide array of built-in modules that you can import into your script. >>>import math >>>print(math.sqrt(16)) # Output: 4.0 32
  • 33.  Classes and Objects: Python is an object-oriented programming language.  You can define classes and create instances of those classes (objects). >>>class MyClass: def greet(self): print("Hello, World!") >>>obj = MyClass() # Creating an object >>>obj.greet() # Output: Hello, World! 33
  • 34. 34 Fig: Python Cheat Sheet Python Basics
  • 35. 35 Fig: Write a python program to perform arithmetic operations using static input
  • 36. 36 Fig: Write a python program to perform arithmetic operations using dynamic input
  • 37. 37
  • 38. 38
  • 39. # Python program to perform all arithmetic operations >>>a=int(input("Enter value of a:")) >>>b=int(input("Enter value of b:")) >>>c=a+b >>>d=a-b >>>e=a*b >>>f=a/b >>>g=a%b >>>print("Addition",c) >>>print("Subtraction",d) >>>print("Multiplication", e) >>>print("Division",f) >>>print("Modulo Division",g) 39
  • 40. #Write a python program to swap two numbers using a third variable using static input >>>a=3 >>>b=4 >>>t=a >>>a=b >>>b=t >>>print("After swapping:", a, b) 40
  • 41. #Write a python program to swap two numbers without using third variable & using static input >>>a=3 >>>b=4 >>>a=a+b >>>b=a-b >>>a=a-b >>>print("After swapping:", a, b) 41
  • 42. 1) Write a python program to Swapping of Two Numbers: Example : x, y = 30, 40 print(x, y) x, y = y, x print(x, y) Output : 30 40 40 30 2) Write a Python program to print string N times : Example : n = 5 a= "python" print(a * n) Output : pythonpythonpythonpythonpython
  • 43. # Write a python program to print arrays people=["Dr Asadi", "Jos", "Jenkins"] print(people) print(people[0]) print(people[1]) print(people[2]) #Write a python program to print lists thislist=["Class", "Date", "Time"] print(thislist) 43
  • 44. #Write a python program to print tuples thistuple=("Blue","Red","Green") print(thistuple) #Write a python program to print sets thisset={"apple","potato","candy"} print(thisset) #Write a python program to print a dictionaries thisdict={"name":"Charles","name":"Jackson","name":"Dr Asadi"} print(thisdict) 44
  • 45. # Write a python program to perform swapping using third variable a=int(input("Enter a value:")) b=int(input("Enter b value:")) t=a a=b b=t print("After swapping:", a, b) # Write a python program to perform swapping without using third variable a=int(input("Enter a value:")) b=int(input("Enter b value:")) a=a+b b=a-b a=a-b print("After swapping:", a, b) 45
  • 46. # Write a python program to perform Armstrong number: Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits. def is_armstrong(num): sum = 0 temp = num num_length = len(str(num)) while temp > 0: digit = temp % 10 sum += digit ** num_length temp //= 10 if num == sum: return True else: return False num = int(input("Enter a number: ")) if is_armstrong(num): print(num, "is an Armstrong number") else: print(num, "is not an Armstrong number") 46
  • 47. # Write a Python program that generates prime numbers from 1 to n, where n is an input provided by the user def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True num = int(input("Generate prime numbers up to: ")) print("Prime numbers up to", num, "are:") for i in range(1, num+1): if is_prime(i): print(i) 47 C:UsersSARAVATHI>python primegen.py Generate prime numbers up to: 100 Prime numbers up to 100 are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
  • 48.  Python Loops: Python has two primitive loop commands: 1. while loop 2. for loop a) while: With the while loop we can execute a set of statements as long as a condition is true. #Write a python program to demo "while " loop i = 1 while i < 6: print(i) i += 1 48
  • 50.  for loop: A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).  for is an iterator method as found in other object- orientated programming languages.  With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.  # Write a Python program demo for "for loop" fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) 50
  • 52. # Write a python program to find the oldest person inside the ages dictionary ages={"java":36,"python":98,"devops":24} oldest_person=None current_biggest_age = 0 for name in ages: age=ages[name] if age>current_biggest_age: oldest_person=name current_biggest_age=age print(oldest_person) 52
  • 53. # To perform student details using class concept class stud(): def details(marks,mark1,mark2,mark3,name): marks.m1=mark1 marks.m2=mark2 marks.m3=mark3 marks.n=name def _print(marks): print("Enter the mark1: ",marks.m1) print("Enter the mark2: ",marks.m2) print("Enter the mark3: ",marks.m3) print("Enter the name: ",marks.n) s=stud() s.details(70,80,90,"navya") s._print() 53
  • 54.  Python Collections are Arrays, Lists, Sets, Tuples and Dictionaries  1)Arrays : Arrays are used to store multiple values in one single variable using square brackets.  #Example : Create an array containing car names >>> cars = ["Ford", "Volvo", "BMW"] 54
  • 55. 55
  • 56.  2) Lists : Lists are used to store multiple items in a single variable using square brackets.  List items are ordered, changeable, and allow duplicate values.  List items are indexed, the first item has index [0], the second item has index [1] etc.  Example : Create a List: >>> thislist = ["apple", "banana", "cherry"] >>> print(thislist) 56
  • 57. 57
  • 58.  3) Sets: Sets are used to store multiple items in a single variable with curly brackets or flower braces.  A set is a collection that is unordered, unchangeable*, and unindexed and does not allow duplicate values.  Example : Create a Set: >>> thisset = {"apple", "banana", "cherry"} >>> print(thisset) 58
  • 59. 59
  • 60.  4) Tuples: Tuples are used to store multiple items in a single variable with round brackets or parenthesis.  A tuple is a collection which is ordered and unchangeable.  Tuple items are indexed, the first item has index [0], the second item has index [1] etc.  Example : Create a Tuple: >>> thistuple = ("apple", "banana", "cherry”) >>> print(thistuple) 60
  • 61. 61
  • 62.  5) Dictionaries: Dictionaries are used to store data values in key : value pairs are written with curly brackets.  A dictionary is a collection which is ordered*, changeable and do not allow duplicates.  Example : Create and print a dictionary: >>>thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } >>>print(thisdict) 62
  • 63. 63
  • 64.  Concepts of Python Programming 1. Arrays: It is containers which are able to store more than one item at the same time. 2. Strings : In python, Strings contain alphanumeric values that are usually enclosed in single or double quotation marks. 3. Lists : It is used to store or organize data in a sequential order. This data can be string, numbers, or iterables like a list. 4. Sets: Sets are used to store multiple items in a single variable with curly brackets or flower braces. 5. Tuples : A tuple is another data collection type in python. It is also used to store and organize data in the form of a list. 6. Dictionaries : A dictionary is a python collection that stores data as key-value pairs.
  • 65. 7. Python functions: A function is a block of code that only runs when it is called. You can pass data, known as parameters, into a function. 8. Python Class: Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. 9. Python exceptions: An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. 10. Python files: Python treats files differently as text or binary and this is important. Text files are simple text whereas binary files contain binary data which is only readable by computer.
  • 66.  Python Arrays: An array is a container that can hold a fixed number of items and these items should be of the same type.  Most of the data structures make use of arrays to implement their algorithms.  The related terminology of arrays is a) Element: Each item stored in an array is called an element. b) Index: Each location of an element in an array has a numerical index, which is used to identify the element.  Array operations are  Traverse: Print all the array elements one by one.  Insertion: Adds an element at the given index.  Deletion: Deletes an element at the given index.  Search: Searches an element using the given index or value.  Update: Updates an element at the given index. 66
  • 67. #Write a python program to add two matrices 3X3 X = [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] result = [[0,0,0], [0,0,0], [0,0,0]] for i in range(len(X)): for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r) 67
  • 68. 68 # Write a python program to perform Matrix multiplication of 3X3 x=[[1,2,3],[4,5,6],[7,8,9]] y=[[9,8,7],[6,5,4],[3,2,1]] result=[[0,0,0],[0,0,0],[0,0,0]] for i in range(len(x)): for j in range(len(x[0])): result[i][j]=x[i][j]*y[i][j] for r in result: print(r)
  • 69. # Program to add two matrices using nested loop of 3X3 X = [[3,3,3], [3 ,3,3], [3 ,3,3]] Y = [[3,3,3], [3,3,3], [3,3,3]] result = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r) 69
  • 70. # Program to transpose a matrix using a nested loop X = [[12,7], [4 ,5], [3 ,8]] result = [[0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) 70
  • 71. # Program to multiply two matrices using nested loops of 3X3 X = [[3,3,3], # 3x3 matrix [3 ,3,3], [3 ,3,3]] Y = [[3,3,3,3], # 3x4 matrix [3,3,3,3], [3,3,3,3]] result = [[0,0,0,0], # result is 3x4 [0,0,0,0], [0,0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): for k in range(len(Y)): # iterate through rows of Y result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) 71
  • 72. Python Strings: A string is a sequence of characters. A character is simply a symbol. For example, the English language has 26 characters. Words and sentences are collections of characters, and so are Python strings. The most common functions used from the library are: 1. strlen("name of string") – it is for string length 2. strcpy( dest, source) – it is for copy string 3. strcmp( string1, string2 ) – it is for comparison 4. strrev(dest, source) – it is for string reverse 72
  • 73. 73 The nine most commonly used functions in the string library are: strcat( ) - concatenate two strings. strchr( ) - string scanning operation. strcmp( ) - compare two strings.
  • 74. # Defining strings in Python my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple lines my_string = """Hello, welcome to the world of Python""" print(my_string) 74
  • 75. # Python String Operations str1 = 'Hello' str2 ='World!' # using ‘+’ print('str1 + str2 = ', str1 + str2) # using ‘*’ print('str1 * 3 =', str1 * 3) # Iterating through a string count = 0 for letter in 'Hello World': if(letter == 'l'): count += 1 print(count,'letters found') 75
  • 76. 76 Fig: Write a Python program to perform iterating through a string
  • 77. # Write a python program to check the given string is Palindrome or not str1="MADAM" j=-1 flag=0 for i in str1: if i!=str1[j]: flag=1 break j=j-1 if flag==1: print("It is not Palindrome") else: print("It is Palindrome") 77
  • 78.  Python Functions: A function is a block of organized, reusable code that is used to perform a single, related action.  Python gives you many built-in functions like print(), abs() etc. but you can also create your own functions, these functions are called user-defined functions.  Rules to define a function in Python. 1. Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ) 2. Any input parameters or arguments should be placed within these parentheses. 3. The first statement of a function can be an optional statement - the documentation string of the function or docstring. 4. The code block within every function starts with a colon (:) and is indented. 5. The statement return [expression] exits a function, optionally passing back an expression to the caller.  Syntax: def my_function(): print("Hello from a function") 78
  • 79. 79 Fig: Python Functions The following are the different types of Python Functions 1. Python Built-in Functions 2. Python Recursion Functions 3. Python Lambda Functions 4. Python User-defined Functions
  • 80. #Write a python program to perform factorial of a given number n=int(input("Enter value of n:")) fact=1 for i in range(1,n+1): fact=fact*i print("Factorial=",i,"=", fact) C:UsersDr. Asadi>python fact.py Enter value of n:5 Factorial= 1 = 1 Factorial= 2 = 2 Factorial= 3 = 6 Factorial= 4 = 24 Factorial= 5 = 120 80
  • 81. #Write a python program to perform Functions Demo def my_function(fname): print(fname + " Refsnes") my_function("Emil") my_function("Tobias") my_function("Linus") C:UsersDr Asadi Srinivasulu>python funs.py Emil Refsnes Tobias Refsnes Linus Refsnes 81
  • 82. #Write a python program to print prime numbers from 1 to 100 for n in range(1,100): count=0 for i in range(1,n+1): if(n%i==0): count=count+1 if(count==2): print(n) 82
  • 83. #Write a python program to find gcd of two numbers def gcd_fun (num1, num2): if (num2 == 0): return num1 else: return gcd_fun (num2, num1 % num2) num1 =int (input ("Enter first number: ")) num2 =int (input ("Enter second number: ")) result = gcd_fun(num1,num2) print("GCD of two number is: ") print(result) 83
  • 84. # Write a python program to find factorial of a number using recursion n=int(input("Enter a number: ")) def factorial(n): while n!=0: if n==1: return 1 else: return n*factorial(n-1) print(factorial(n)) 84
  • 85. Python Classes  Class is a collection of objects.  Object is a Physical entity or Real time entity  A class is a user-defined blueprint or prototype from which objects are created.  Classes provide a means of bundling data and functionality together.  Syntax: class ClassName: # Statement obj = ClassName() print(obj.atrr)  Classes are created by keyword class.  Attributes are the variables that belong to a class.  Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute 85
  • 86. # Demo for class declaration in Python class Person: "This is a person class" age = 10 def greet(self): print('Hello') # Output: 10 print(Person.age) # Output: <function Person.greet> print(Person.greet) # Output: "This is a person class" print(Person.__doc__) 86
  • 87. # Create a Car class with operations and print methods information class Car: # class attribute wheels = 4 # initializer / instance attributes def __init__(self, color, style): self.color = color self.style = style # method 1 def showDescription(self): print("This car is a", self.color, self.style) # method 2 def changeColor(self, color): self.color = color c = Car('Black', 'Sedan') # call method 1 c.showDescription() # Prints This car is a Black Sedan # call method 2 and set color c.changeColor('White') c.showDescription() # Prints This car is a White Sedan 87
  • 88. #Write a python program for the class concept class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print("bark bark!") def doginfo(self): print(self.name + " is " + str(self.age) + " year(s) old.") ozzy = Dog("Ozzy", 2) skippy = Dog("Skippy", 12) filou = Dog("Filou", 8) ozzy.doginfo() skippy.doginfo() filou.doginfo() 88 C:UsersDr. Asadi>python clas.py Ozzy is 2 year(s) old. Skippy is 12 year(s) old. Filou is 8 year(s) old.
  • 89. """Write a Python program to find the oldest person inside the ages dictionary. """ ages={ "John":34, "Matt":23, "Natasha":27, "Gabriella":33 } oldest_person=None current_biggest_age=0 for name in ages: age=ages[name] if age>current_biggest_age: oldest_person=name current_biggest_age=age print(oldest_person) 89
  • 90.  Python Exceptions: Exception handling is a mechanism in computer programming for handling errors or exceptional conditions that may arise during the execution of a program.  When an error occurs, or exception as we call it, Python will normally stop and generate an error message.  These exceptions can be handled using the try and except statement  Example: The try block will generate an exception, because x is not defined: x=5 try: print(x) except: print("An exception occurred") 90
  • 91. # Write a python program that demonstrates how to use exception handling in Python try: num1 = float(input("Enter a number: ")) num2 = float(input("Enter another number: ")) result = num1 / num2 print(f"Result: {result}") except ValueError: print("Invalid input: Please enter a valid number.") except ZeroDivisionError: print("Division by zero is not allowed.") 91
  • 92. 92
  • 93. # Write a python program that demonstrates how to handle divide by zero exceptions in Python while True: try: num1 = float(input("Enter a number: ")) num2 = float(input("Enter another number: ")) result = num1 / num2 print(f"Result: {result}") break except ZeroDivisionError: print("Division by zero is not allowed.") 93
  • 94. 94
  • 95. Python File Operations 95  A file is a container in computer storage devices used for storing data.  When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so that the resources that are tied with the file are freed.  Hence, in Python, a file operation takes place in the following order: 1. Open a file 2. Read or write (perform operation) 3. Close the file
  • 96.  #Write a python program to create a file with content  file=open("C:UsersDrAsadi Srinivasulubluecrest.txt","r")  read_content=file.read()  print(read_content) 96
  • 97.  Reading Files in Python: After we open a file, we use the read() method to read its contents. For example  # Write a Python program to read a file with content  file1 = open("C:UsersDr Asadi Srinivasulutest.txt", "r")  # read the file  read_content = file1.read()  print(read_content) 97
  • 98. Anonymous Functions (Lambda)  A lambda function is a small anonymous function.  A lambda function can take any number of arguments, but can only have one expression.  Syntax: lambda arguments: expression  #1) Aim: write a python program to add 10 to argument a, and return the result: >>> x = lambda a : a + 10 >>> print(x(5)) >>> 98
  • 99. #2)Write a Python program for lambda function def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(2)) #3) Write a Python program for lambda function def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) mytripler = myfunc(3) print(mydoubler(2)) print(mytripler(3)) 99
  • 100. TOP 10 PYTHON LIBRARIES  Top 10 Python libraries for data science and cyber security: 1. NumPy: A library for numerical computing that provides support for multi-dimensional arrays and matrices, along with a range of mathematical operations. 2. Pandas: A library for data manipulation and analysis that provides easy-to-use data structures and data analysis tools for working with structured data. 3. Matplotlib: A library for data visualization that provides a wide range of plotting functions and tools for creating high-quality charts and graphs. 4. Scikit-learn: A library for machine learning that provides a wide range of tools and algorithms for data preprocessing, feature engineering, model selection, and evaluation. 5. TensorFlow: A library for machine learning that provides a range of tools for building and training neural networks and other machine learning models.
  • 101. 6. Keras: A high-level neural networks API that runs on top of TensorFlow, making it easy to build and train deep learning models. 7. Seaborn: A library for data visualization that provides high- level interfaces for creating informative and attractive statistical graphics. 8. SciPy: A library for scientific computing that provides a wide range of tools and algorithms for numerical integration, optimization, signal processing, linear algebra, and more. 9. Statsmodels: A library for statistical modeling that provides a wide range of tools for regression analysis, time series analysis, and other statistical modeling tasks. 10.NLTK: A library for natural language processing that provides a wide range of tools and algorithms for text processing, classification, and language modeling.
  • 102. 102
  • 103. 1. NumPy  NumPy is a popular Python library that is used for performing mathematical operations on large multi-dimensional arrays and matrices.  It provides high-performance, optimized mathematical functions that are particularly useful for scientific computing, data analysis, and machine learning applications.  NumPy is a powerful library for scientific computing in Python, and its efficient array operations and mathematical functions make it an essential tool for many data scientists, researchers, and engineers.  Here are some common use cases of NumPy in Python programming 1. Array creation 2. Array indexing and slicing 3. Mathematical operations 4. Broadcasting 5. Integration with other libraries
  • 104. 104
  • 105. 105
  • 106. 2. SciPy  SciPy is an open-source scientific computing library for Python that is built on top of NumPy.  It provides a wide range of tools and algorithms for scientific computing, including numerical integration, optimization, signal processing, linear algebra, and more.  SciPy is designed to be easy to use and provides a consistent API for working with a wide range of scientific computing problems.  SciPy is widely used in industry and academia for scientific computing tasks.  It is particularly popular among data scientists, researchers, and engineers who work with scientific data and need to perform complex computations.  SciPy provides a powerful and flexible scientific computing environment that allows users to solve a wide range of scientific computing problems with ease.
  • 107.  Some of the key features of SciPy include: 1. Numerical integration: SciPy provides a wide range of tools for numerical integration, including integration of ordinary differential equations (ODEs), partial differential equations (PDEs), and quadrature. 2. Optimization: SciPy provides a wide range of optimization algorithms for unconstrained and constrained optimization problems, including nonlinear optimization and global optimization. 3. Signal processing: SciPy provides a wide range of tools for signal processing, including filtering, spectral analysis, and wavelet transforms. 4. Linear algebra: SciPy provides a wide range of tools for linear algebra, including matrix factorization, eigensystem analysis, and sparse matrix operations. 5. Statistical functions: SciPy provides a wide range of statistical functions, including probability distributions, hypothesis testing, and regression analysis.
  • 108. 108
  • 109. 3. Pandas  Pandas is an open-source Python library for data manipulation and analysis.  It provides easy-to-use data structures and data analysis tools for working with structured data, including data in CSV, Excel, SQL databases, and other formats.  Pandas is built on top of NumPy, another popular Python library for numerical computing, and provides a powerful and flexible data analysis environment for data scientists, analysts, and developers.  Pandas is widely used in industry and academia for data analysis and manipulation tasks.  It is particularly popular among data scientists, analysts, and developers who work with structured data.  Pandas provides a powerful and flexible data analysis environment that allows users to perform a wide range of data manipulation and analysis tasks with ease.
  • 110.  Some of the key features of Pandas include: 1. Data structures: Pandas provides two main data structures, Series and DataFrame, that allow users to work with one-dimensional and two-dimensional arrays of data, respectively. 2. Data manipulation: Pandas provides a wide range of data manipulation tools for filtering, selecting, merging, and reshaping data. 3. Data analysis: Pandas provides tools for descriptive statistics, data visualization, time series analysis, and more. 4. Integration with other Python libraries: Pandas integrates seamlessly with other popular Python libraries, such as NumPy, Matplotlib, and Scikit-learn. 5. Performance: Pandas is optimized for performance and can handle large datasets efficiently.
  • 111. 111
  • 112. 112
  • 113. 4. Scikit-learn  Scikit-learn is an open-source Python library for machine learning.  It provides a wide range of tools and algorithms for data preprocessing, feature engineering, model selection, and evaluation.  Scikit-learn is designed to be easy to use and provides a consistent API for working with a wide range of machine learning models.  Scikit-learn is widely used in industry and academia for a wide range of machine learning applications, including classification, regression, clustering, and dimensionality reduction.  It is particularly popular among data scientists and machine learning practitioners who are new to machine learning, as it provides a user- friendly interface and comprehensive documentation.
  • 114.  Some of the key features of scikit-learn include: 1. Wide range of machine learning algorithms: Scikit-learn provides a wide range of machine learning algorithms, including linear models, decision trees, random forests, support vector machines, and neural networks. 2. Consistent API: Scikit-learn provides a consistent API for working with a wide range of machine learning models, making it easy to switch between different models. 3. Data preprocessing and feature engineering: Scikit-learn provides a wide range of tools for data preprocessing and feature engineering, including scaling, normalization, imputation, and feature selection. 4. Model selection and evaluation: Scikit-learn provides tools for model selection and evaluation, including cross-validation, grid search, and performance metrics. 5. Integration with other Python libraries: Scikit-learn integrates seamlessly with other popular Python libraries, such as NumPy, Pandas, and Matplotlib.
  • 115. 115
  • 116. 5. Theano  Theano is a Python library for efficient numerical computation, primarily used for deep learning applications.  It was developed by the Montreal Institute for Learning Algorithms (MILA) at the University of Montreal and released in 2007.  Theano was designed to enable the creation and deployment of complex mathematical models for machine learning, including deep neural networks, convolutional neural networks, and recurrent neural networks.  Theano provides a high-level interface for building and training deep learning models, making it easy to create complex neural network architectures.  It is built around a symbolic expression compiler that generates optimized C code for numerical computation.  This enables Theano to perform calculations on both CPUs and GPUs, providing fast and efficient execution.
  • 117.  Theano is widely used in industry and academia for building and deploying deep learning models. However, since the library is no longer being actively developed, many users have transitioned to newer libraries such as TensorFlow or PyTorch.  Some of the key features of Theano include: 1. Symbolic expression compiler: Theano's symbolic expression compiler generates optimized C code for numerical computation, making it fast and efficient. 2. Support for both CPUs and GPUs: Theano can perform calculations on both CPUs and GPUs, providing fast and efficient execution. 3. Integration with NumPy: Theano integrates seamlessly with NumPy, a popular numerical computing library for Python, making it easy to work with multi-dimensional arrays. 4. Automatic differentiation: Theano includes a powerful automatic differentiation engine that makes it easy to compute gradients for backpropagation during training. 5. Extensible and customizable: Theano is highly extensible and customizable, allowing users to add new functionality and customize the library to their needs.
  • 118. 118
  • 119. 6. TensorFlow  TensorFlow is an open-source machine learning framework developed by Google that enables developers to build and deploy deep learning models.  It is designed to be a scalable and flexible platform for building a wide range of machine learning applications.  TensorFlow also includes several high-level APIs, such as Keras, which make it easy to build and train deep learning models with just a few lines of code.  TensorFlow can be used to build a wide range of machine learning applications, including computer vision, natural language processing, and speech recognition.  TensorFlow is widely used in industry and academia for building and deploying machine learning models.  It is supported by a large and active community of developers and researchers who contribute to its ongoing development and improvement.
  • 120.  TensorFlow provides a wide range of tools and libraries for building deep learning models, including: 1. Tensors: TensorFlow provides a powerful tensor library that allows developers to perform efficient computation on multi-dimensional arrays. Tensors are the basic building blocks for building deep learning models in TensorFlow. 2. Neural network modules: TensorFlow includes a variety of pre-built neural network modules, such as convolutional layers, recurrent layers, and linear layers, that can be easily combined to create complex models. 3. Optimizers: TensorFlow includes several built-in optimization algorithms, such as stochastic gradient descent (SGD) and Adam, that can be used to train deep learning models. 4. Data loaders: TensorFlow provides utilities for loading and preprocessing data, including built-in support for popular data formats like CSV and JSON. 5. Visualization tools: TensorFlow includes several visualization tools, such as TensorBoard, that make it easy to monitor and debug models
  • 121. 121
  • 122. 122
  • 123. 123
  • 124. 7. Keras  Keras is a high-level neural network API that is written in Python and runs on top of several lower-level deep learning frameworks, including TensorFlow, Theano, and CNTK.  It was developed with the goal of providing a user-friendly interface for building and training deep neural networks.  Keras provides a simple and intuitive interface for building deep learning models, making it accessible to both beginners and experts.  It offers a wide range of pre-built layers and models that can be easily combined to create complex architectures. Keras also includes utilities for data loading, preprocessing, and evaluation.  Keras is widely used in industry and academia for building and training deep learning models for a wide range of applications, including computer vision, natural language processing, and speech recognition.
  • 125.  Some of the key features of Keras include: 1. User-friendly API: Keras provides a simple and intuitive interface for building deep learning models, making it easy for users to get started with deep learning. 2. Modular architecture: Keras models are built using a modular architecture, which allows users to easily add, remove, or modify layers in their models. 3. Multi-backend support: Keras can run on top of several different deep learning backends, including TensorFlow, Theano, and CNTK, allowing users to choose the backend that best suits their needs. 4. Built-in support for data augmentation: Keras includes utilities for data augmentation, which can be used to increase the size of training data and improve the generalization of models. 5. Easy model evaluation: Keras provides utilities for evaluating the performance of trained models, including accuracy, precision, recall, and F1 score.
  • 126. 126
  • 127. 8. PyTorch  PyTorch is an open-source machine learning framework developed by Facebook's artificial intelligence research group.  It is designed to be a flexible, efficient, and easy-to-use platform for building deep learning models.  PyTorch is built around a dynamic computation graph, which allows developers to easily create and modify models on the fly.  It also includes a powerful autograd engine that enables automatic differentiation, which makes it easy to compute gradients for backpropagation during training.  PyTorch is widely used in academia and industry for building deep learning models for a wide range of applications, including computer vision, natural language processing, and robotics.
  • 128.  PyTorch includes a wide range of tools and utilities for building and training deep learning models, including: 1. Tensors: PyTorch provides a powerful tensor library that enables efficient computation on multi-dimensional arrays. Tensors are the basic building blocks for building deep learning models in PyTorch. 2. Neural network modules: PyTorch includes a variety of pre-built neural network modules, such as convolutional layers, recurrent layers, and linear layers, that can be easily combined to create complex models. 3. Optimizers: PyTorch includes several built-in optimization algorithms, such as stochastic gradient descent (SGD) and Adam, that can be used to train deep learning models. 4. Data loaders: PyTorch provides utilities for loading and preprocessing data, including built-in support for popular data formats like CSV and JSON. 5. Visualization tools: PyTorch includes several visualization tools, such as TensorBoard, that make it easy to monitor and debug models during training.
  • 130. 9. Seaborn  Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level interface for creating informative and attractive statistical graphics.  Seaborn makes it easy to create complex visualizations with simple code.  Seaborn offers a variety of visualization types, including 1. Scatter plots 2. Line plots 3. Bar plots 4. Histograms 5. Box plots 6. Heatmaps 7. Violin plots 8. Joint plots 9. Pair plots 10. Facet grids
  • 131.  In addition to these basic types, Seaborn also provides several built-in color palettes and styles to help you customize your visualizations.  Seaborn is designed to work well with Pandas data frames, making it easy to create visualizations from your data.  Seaborn is widely used in data science and machine learning projects, as it provides an intuitive and aesthetically pleasing way to visualize data.
  • 136. 10. Matplotlib  Matplotlib is a Python library for creating static, animated, and interactive visualizations in Python.  It is one of the most widely used visualization libraries in the data science community and is known for its flexibility and customization options.  Matplotlib provides a variety of plotting functions and styles, allowing users to create a wide range of visualizations, including line plots, scatter plots, bar plots, histograms, and many others.  It also provides functionality for adding annotations, legends, and other design elements to visualizations.  Matplotlib can be used in conjunction with other data science libraries in the Python ecosystem, such as NumPy, Pandas, and SciPy, making it a powerful tool for data analysis and visualization.
  • 137.  Some key features of Matplotlib include: 1. Highly customizable: Matplotlib provides many options for customizing visualizations, including colors, fonts, and styles. 2. Variety of plot types: Matplotlib provides functions for creating many different types of plots, including line plots, scatter plots, bar plots, histograms, and more. 3. Integration with other libraries: Matplotlib can be used in conjunction with other popular data science libraries in the Python ecosystem, such as NumPy, Pandas, and SciPy. 4. Interactive capabilities: Matplotlib can be used to create interactive visualizations, allowing users to zoom, pan, and interact with their data. 5. Large user community: Matplotlib has a large and active user community, with many resources available online for learning and troubleshooting.
  • 138. 138
  • 139. 11. Statsmodels  Statsmodels is an open-source Python library for statistical modeling, estimation, and inference.  It provides a wide range of tools and algorithms for regression analysis, time series analysis, hypothesis testing, and more. Statsmodels is designed to be easy to use and provides a consistent API for working with a wide range of statistical modeling problems.  Statsmodels is widely used in industry and academia for statistical modeling and analysis tasks.  It is particularly popular among data scientists, statisticians, and researchers who work with statistical data and need to perform complex analyses.  Statsmodels provides a powerful and flexible statistical modeling environment that allows users to solve a wide range of statistical modeling problems with ease.
  • 140.  Some of the key features of Statsmodels include: 1. Regression analysis: Statsmodels provides a wide range of tools for regression analysis, including linear regression, generalized linear models, mixed-effects models, and more. 2. Time series analysis: Statsmodels provides a wide range of tools for time series analysis, including autoregressive integrated moving average (ARIMA) models, vector autoregression (VAR) models, and more. 3. Hypothesis testing: Statsmodels provides a wide range of tools for hypothesis testing, including t-tests, F-tests, and chi-square tests. 4. Visualization: Statsmodels provides tools for visualizing statistical models and results, including plots of residuals, fitted values, and more. 5. Integration with other Python libraries: Statsmodels integrates seamlessly with other popular Python libraries, such as Pandas, NumPy, and Matplotlib.
  • 142. 12. NLTK  NLTK (Natural Language Toolkit) is a popular open-source Python library for natural language processing (NLP).  It provides a wide range of tools and algorithms for text processing, classification, and language modeling.  NLTK is designed to be easy to use and provides a consistent API for working with a wide range of NLP problems.  NLTK is widely used in industry and academia for NLP tasks.  It is particularly popular among data scientists, researchers, and developers who work with text data and need to perform complex NLP tasks.  NLTK provides a powerful and flexible NLP environment that allows users to solve a wide range of NLP problems with ease.
  • 143.  Some of the key features of NLTK include 1. Text processing: NLTK provides a wide range of tools for text processing, including tokenization, stemming, and part-of-speech tagging. 2. Classification: NLTK provides tools for building and evaluating classifiers, including naive Bayes classifiers, decision tree classifiers, and maximum entropy classifiers. 3. Language modeling: NLTK provides tools for building and evaluating language models, including n-gram models and probabilistic context-free grammars (PCFGs). 4. Sentiment analysis: NLTK provides tools for sentiment analysis, including tools for identifying positive and negative sentiments in text. 5. Integration with other Python libraries: NLTK integrates seamlessly with other popular Python libraries, such as Pandas, NumPy, and Matplotlib.
  • 146. # Write a python program to perform encryption and decryption of given message using DES algorithm from cryptography.fernet import Fernet message = “Data Science" key = Fernet.generate_key() fernet = Fernet(key) encMessage = fernet.encrypt(message.encode()) print("original string: ", message) print("encrypted string: ", encMessage) decMessage = fernet.decrypt(encMessage).decode() print("decrypted string: ", decMessage) 146
  • 147. # Write a python program to perform encryption and decryption of given message using AES algorithm from cryptography.fernet import Fernet message = “cyberforensics" key = Fernet.generate_key() fernet = Fernet(key) encMessage = fernet.encrypt(message.encode()) print("original string: ", message) print("encrypted string: ", encMessage) decMessage = fernet.decrypt(encMessage).decode() print("decrypted string: ", decMessage) 147
  • 148. # Write a python program to perform encryption and decryption of given message using RSA algorithm import rsa publicKey, privateKey= rsa.newkeys(512) message= "cybershiksha" encMessage=rsa.encrypt(message.encode(),publicKey) print("original string: ", message) print("encrypted string: ", encMessage) decMessage=rsa.decrypt(encMessage,privateKey).decode() print("decrypted string: ", decMessage) 148
  • 149.  Tools in Python programming 1. PyCharm IDE [Best Python IDE by a mile] 2. Python Anywhere [Best tool to run Python code online] 3. IDLE : It is Python's Integrated Development and Learning Environment. It is a default editor that comes with Python. 4. Sublime Text : It is one of the most popular code editors for programmers, supporting almost all platforms. 5. Atom : It is a tool that is a free and open-source text and source code editor. 6. Jupyter Notebook : It is an open-sourced web-based application which allows you to create and share documents containing live code, equations, visualisations, and narrative text. 7. Spyder : It is an open-source, powerful scientific environment written in python, built especially for data science. 8. Pip Package [Best Tool to Install Python packages] 9. Scikit-Learn [Best Python library for Data Science]
  • 150.  Technologies used in Python Programming 1. Artificial intelligence (AI) 2. Machine Learning(ML) 3. Deep Learning 4. Cyber Security 5. Big Data 6. IoT 7. Web Development: Django, Pyramid, Bottle, Tornado, Flask, web2py 8. GUI Development: tkInter, PyGObject, PyQt, PySide, Kivy, wxPython 9. Scientific and Numeric: SciPy, Pandas, IPython. 10. Software Development: Buildbot, Trac, Roundup. 11. System Administration: Ansible, Salt, OpenStack, xonsh.
  • 151. 1) What is Python used for? Ans) Python is a high-level, interpreted programming language that is used for a wide range of purposes, including web development, scientific computing, data analysis, artificial intelligence, and more. 2) What are some of the benefits of using Python? Ans) Python has a number of benefits, including its ease of use, large and supportive community, vast libraries and frameworks, and versatility. 151
  • 152. 3) What is a Python module? Ans) A Python module is a collection of Python code that can be reused in other programs. 4) What is the difference between a tuple and a list in Python? Ans) In Python, a tuple is an immutable data structure, while a list is a mutable data structure. This means that once a tuple is created, its values cannot be changed, while values in a list can be changed, added, or removed. Tuples use parentheses, while lists use square brackets. 152
  • 153.  5) What is a dictionary in Python?  Ans) A dictionary in Python is an unordered collection of key-value pairs, where each key is unique. Dictionaries are used to store data that is accessed using keys, rather than index numbers. They are defined using curly braces ({}) and can store a variety of data types.  6) What is a function in Python and how is it defined?  Ans) A function in Python is a block of code that performs a specific task and can be called from other parts of the program. Functions are defined using the "def" keyword, followed by the function name and a set of parentheses that may contain parameters. The code inside the function is indented and runs whenever the function is called. 153
  • 154.  7) What is an exception in Python and how is it handled?  Ans) An exception in Python is an error that occurs during the execution of a program. When an exception is raised, the normal flow of execution is interrupted, and the program jumps to the nearest exception handler. Exception handling in Python is accomplished using the "try" and "except" keywords, where the code that may raise an exception is placed inside the "try" block, and the exception handling code is placed inside the "except" block.  8) Explain the concept of inheritance in Python.  Ans) Inheritance is a mechanism where one class acquires the properties and behavior of another class. The class that inherits properties is called the derived class, and the class from which it inherits properties is called the base class. 154
  • 155.  9) What is the difference between 'is' and '==' in Python?  Ans) 'is' is used to check if two variables refer to the same object, whereas '==' is used to check if two variables have the same value.  10) What is a decorator in Python?  Ans) A decorator is a function that takes another function as input, adds some functionality to it, and returns it as output. It is a way to modify the behavior of a function or class without changing its source code.  11) What are lambda functions in Python?  Ans) Lambda functions are anonymous functions in Python that are defined without a name. They are usually used as a one- liner to perform simple operations and are created using the 'lambda' keyword. 155
  • 156.  12) Explain the concept of generators in Python.  Ans) Generators are functions that return an iterator, which can be iterated over using the 'next()' function. Unlike lists, generators do not store all the values in memory at once, making them more memory-efficient.  13) What is the difference between 'append' and 'extend' methods in Python?  Ans) 'append' method adds a single element to the end of a list, whereas 'extend' method can add multiple elements to the end of a list, as it takes an iterable as input. 156
  • 157. MCQS OF INTRODUCTION TO PYTHON 1. What is Python? a) A programming language b) A type of snake c) A type of database d) A type of operating system Answer: a) A programming language 157
  • 158. MCQS OF INTRODUCTION TO PYTHON 2. Which of the following is an example of a Python data type? a) string b) int c) list d) all of the above Answer: d) all of the above 158
  • 159. MCQS OF INTRODUCTION TO PYTHON 3. What is the output of the following Python code? print("Hello, World!") a) Hello b) World c) Hello, World! d) Nothing Answer: c) Hello, World! 159
  • 160. MCQS OF INTRODUCTION TO PYTHON 4. Which of the following is the correct way to declare a variable in Python? a) variable = value b) value = variable c) var = value d) val = var Answer: a) variable = value 160
  • 161. MCQS OF INTRODUCTION TO PYTHON 5. Which of the following is used to end a line of code in Python? a) ; b) : c) . d) None of the above Answer: d) None of the above (Python uses line breaks to separate lines of code) 161
  • 162. MCQS OF INTRODUCTION TO PYTHON 6. Which of the following is a conditional statement in Python? a) for loop b) while loop c) if statement d) function definition Answer: c) if statement 162
  • 163. MCQS OF INTRODUCTION TO PYTHON 7. What is the output of the following Python code? x = 5 y = 2 print(x + y) a) 3 b) 7 c) 10 d) Error Answer: b) 7 163
  • 164. MCQS OF INTRODUCTION TO PYTHON 8. What is the output of the following Python code? my_list = [1, 2, 3, 4, 5] print(my_list[2]) a) 1 b) 2 c) 3 d) 4 Answer: c) 3 (Python uses zero-based indexing, so the third element in the list is at index 2) 164
  • 165. MCQS OF INTRODUCTION TO PYTHON 9. Which of the following is a built-in Python function? a) input() b) print() c) len() d) all of the above Answer: d) all of the above 165
  • 166. MCQS OF INTRODUCTION TO PYTHON 10. What is the purpose of a function in Python? a) To store data b) To perform a specific task c) To declare variables d) None of the above Answer: b) To perform a specific task 166
  • 167. 5 Big Reasons Python is Useful in Cybersecurity 1. Cybersecurity professionals can get up to speed quickly 2. Cybersecurity teams can form quickly. 3. Python’s extensive library means cybersecurity tools are already available. 4. Python can be used for nearly anything in cybersecurity. 5. Scripts in Python can be developed quickly 167
  • 168. 168
  • 169. 169
  • 170. 5 Big Reasons Python is Useful in Data Science 1. Data Science professionals can get up to speed quickly 2. Data Science teams can form quickly. 3. Python’s extensive library means Data Science tools are already available. 4. Python can be used for nearly anything in Data Science. 5. Scripts in Python can be developed quickly 170
  • 171. 171 Fig: Building Secure Python Application