0% found this document useful (0 votes)
19 views214 pages

Python

Uploaded by

Iphone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views214 pages

Python

Uploaded by

Iphone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 214

PYTHON

PROGRAMMING
AGENDA
• Introduction to python
• PIP and Modules
• Data types, Keywords and Variables
• User input and Data type Casting
WHAT IS PROGRAMMING 3

Computer doesn’t understand our human language like English, Hindi etc. We use programming language to
communicate with the computer. Computer only understand the binary language.
 Low-Level Programming Language:

Low-level languages are more like speaking the computer's language directly.
They are closer to the computer's hardware and can perform tasks efficiently.
However, they are more challenging for humans to understand and use because you have to manage many
details.
Examples: Assembly language, machine language (binary code).

 Middle-Level Programming Language:

Middle-level languages are like a compromise between high-level and low-level languages.
They provide some level of abstraction, making them easier to use than low-level languages.
At the same time, they give you more control over the computer's resources than high-level languages.
Examples: C, Go, Rust.

 High-level languages

High-level languages are like using a simple and friendly language to communicate with the computer.
They allow you to write code that is easier for humans to understand, read, and write.
You don't need to worry about low-level details, like managing computer memory or hardware operations.
Examples: Python, Java, JavaScript, Ruby.
COMPILER INTERPRETER

• A compiler translates the entire • An interpreter reads and translates


source code of a program into the source code line-by-line,
machine code or bytecode before executing each line immediately
the program is executed. after translation. It doesn't create a
separate translated file.
• It goes through the entire source
code and generates the translated • Debugging is easy in Interpreter
output as a separate file. because errors are reported as soon
as they occur in execution which
results in faster development.
 Does python use a compiler or interpreter?

Python uses both interpretation and compilation in a two-step process to execute Python code.

• Compilation: When you run a Python script for the first time, Python reads and translates the
code into a special format called "bytecode." This step happens only once.

• Interpretation: Every time you run the script again, Python uses the translated bytecode to
execute the code and make it work.

• So, Python compiles the code once, stores it for future use, and interprets and runs the compiled
code whenever you want to use the script again. This combination helps Python be both easy to
use and reasonably fast when running your programs
USE OF COMPUTER
PROGRAMS
Computer programs are used for a multitude of reasons and have become
an integral part of modern life. Here are some key reasons why computer
programs are used:-

 Problem Solving
 Communication
 Education
 Security
 Navigation
 E-commerce
 Artificial Intelligence
 Transportation
 Government Services
 Weather Forecasting
ALGORITHM
Algorithms are a fundamental part of computer science and many different fields, including computer science,
mathematics, engineering, and finance. Algorithms are step-by-step instructions that can be used to solve a wide
variety of problems and to perform many different tasks.

Applications of algorithms:
Algorithms are used in a wide variety of applications, including:
• Web search engines: Search engines use algorithms to index the web and return relevant results to users'
queries.
• Social media platforms: Social media platforms use algorithms to recommend content to users and to rank
posts in users' feeds.
• Recommendation systems: Recommendation systems use algorithms to recommend products, movies, music,
and other items to users based on their past behavior.
• Machine learning: Machine learning algorithms are used to train computers to learn from data and make
predictions.
• Robotics: Robotics algorithms are used to control robots and enable them to perform tasks autonomously.
FLOW CHART
• A flowchart is a diagram that shows the steps of a process in a
sequential order. Flowcharts are often used to document and
analyze processes, as well as to communicate complex
processes to others.
• Flowcharts are made up of a variety of symbols, each of which
represents a different step in the process.

Advantages of Flowchart:
• Flowcharts are a better way of communicating the logic of the
system.
• Flowcharts act as a guide for blueprint during program
designed.
• With the help of flowcharts programs can be easily analyzed.
• It provides better documentation.
• Flowcharts serve as a good proper documentation.
• Easy to trace errors in the software.
• Easy to understand.
• It helps to provide correct logic.
INTRODUCTION TO
PYTHON
 Python is a general-purpose high-level programming
language.
 Python was developed by Guido Van Rossum in 1989
while working at National Research Institute at
Netherlands.
 But officially Python was made available to public in 1991. The
official Date of birth for Python is: Feb 20th 1991.
 Python is case sensitive.
 It is a dynamically typed language.
 Python is recommended as first programming language for
beginners.
WHY PYTHON CREATED
• Python was created by Guido van Rossum in 1991.
• He was looking for a new programming language that was simple, readable, and
versatile. He also wanted to create a language that would be fun to use.
• Van Rossum was inspired by the ABC programming language, which he had helped
to create earlier in his career. However, he felt that ABC was too complex and
difficult to learn. He also wanted to create a language that would be more portable
and less dependent on specific hardware and software platforms.
• Python is a powerful and versatile programming language that is well-suited for a
wide range of tasks. It is a popular choice for both beginners and experienced
programmers alike.
WHERE WE CAN USE PYTHON
We can use everywhere. The most common important application areas are:
1. For developing Desktop Applications

2. For developing web Applications

3. For developing database Applications

4. For Network Programming

5. For developing games

6. For Data Analysis Applications

7. For Machine Learning

8. For developing Artificial Intelligence Applications


9. For IOT Internet of Things
USE OF PYTHON IN CYBER SECURITY
 Writing and executing security tools…
 Web application security testing….
 Security automation: Python scripts can be used to automate repetitive security tasks, streamline incident
response, and manage security operations.
 Network security: Python can be used for network scanning, monitoring, and intrusion detection, helping to
identify potential threats….
 Password cracking and recovery: In a controlled and authorized environment, Python scripts can be used to
test the strength of passwords and evaluate password policies.
 penetration testing: Reconnaissance, Scanning, Vulnerability Assessment, Exploitation, and Reporting
 Keylogger: It is also known as keystroke logger or system monitor, is a type of software or hardware that
secretly records every keystroke made on a computer or mobile device without the user's knowledge or
consent. In simpler terms, it is a tool that can track and log everything you type on your keyboard.
REASON FOR USING PYTHON
 Simple and easy to learn
 Freeware and Open Source
 High Level Programming language
 Platform Independent
 Dynamically Typed
 Extensive Library
INSTALLATION OF
IDE(PYCHARM/VISUAL STUDIO)
RUNNING A HELLO WORLD PROGRAM
• Create a new file with a .py extension, such as hello_world.py.
• Open the file in a text editor or IDE.
• Add the following code to the file:
print("Hello, world!")
• Save the file.
• Open a terminal or command prompt.
• Navigate to the directory where you saved the file.
• Type the following command and press Enter:
python hello_world.py
• This will run the program and print the message "Hello, World!" to
the console.
COMPARISON OF PYTHON WITH
OTHER PROGRAMMING LANGUAGE

PYTHON JAVA C

Print(‘Hello World’) Public class Hello World{ #include<stdio.h>


public static void int main(){
main(string[] args){
System.out.println(“Hello printf(“Hello World”)
World”); return 0;
} }
}
COMPARISON OF PYTHON WITH
OTHER PROGRAMMING LANGUAGE

PYTHON JAVA C

Public class For_Loop{ #include<stdio.h>


public static void main(string[] int main(){
args){ int i;
for i in range(1,10):
for(int i=1; i<=10; i++){ for(int i=1; i<=10; i++){
print(i)
System.out.pritln(i) printf(“%d”, i)
}}} }
return 0;
}
PIP
AND
MODULES
MODULES
Module is like a code library which can be borrow the code written by somebody else in
our python program. Python module is a specific type of file that contains Python code
meant to be imported and reused in other Python files. There are two types of modules in
python:-
• Built-in module:- These modules are ready to import and use and ships with the
python interpreter. There is no need to install such modules explicitly.
Example:- array, math ,numpy ,random,etc.
• External module:- these modules are important from a third party file or can be
installed using a package manager like pip. Since this code is written by someone
else, we can install different versions of a same module with time.
Examples:- pandas, stegno ,etc.

 Using a module in python


import pandas
PIP
Pip is the default package manager for Python, and it stands for "Pip
Installs Packages". It is a command-line tool used to install, upgrade, and
manage Python packages, which are third-party libraries and modules that
extend the functionality of Python.
Open your “cmd” and type “pip.you” will see all the functions we can
perform
For example:- pip install panda
COMMENTS
COMMENTS
Comments in Python are lines of text that are ignored by the Python interpreter when it runs your code. They are meant
for humans to read and understand the code better. You can use comments to explain what your code does, provide
context, or make notes for yourself and others who might read your code.

In Python, there are two ways to write comments:

 Single-line Comments: These comments are used for explaining a single line of code. They start with the # symbol
and continue until the end of the line.
Example:
# This is a single-line comment
print("Hello, World!") # This comment explains the print statement

 Multi-line Comments (Docstrings): These comments are used for longer explanations, often used to describe
functions, classes, or modules. They are enclosed in triple quotes (''' or """) and can span multiple lines.
Example:
'''
This is a multi-line comment.
Print(“hello world”)’’’
DATA TYPES
KEYWORDS
AND
VARIABLE
VARIABLE
• variables are used to store and manipulate data. Python is dynamically
typed, which means you don't need to declare the data type of a variable
explicitly; Python infers it based on the value assigned to the variable.

VARIABLE ASSIGNMENT:-

• You can assign values to variables using the assignment operator (=).
For example:
• age = 25
• name = "Alice"
VARIABLE NAMING RULES
• Variable names can consist of letters, numbers, and underscores
(_).
• Variable names must start with a letter or an underscore (_).
• Variable names are case-sensitive (e.g., my Variable and my
variable are treated as different variables).
• Reserved keywords (e.g., if, while, for, in, etc.) cannot be used
as variable names
VARIABLE SCOPE:

• Variables in Python can have different scopes:


• Local Variables: Defined within a specific function or code block and
only accessible within that scope.
• Global Variables: Defined at the top level of a script or module and
accessible throughout the entire program.

PRINTING VARIABLES:
• x = 42
• print(x) # Output: 42
VARIABLE REASSIGNMENT:

• you can reassign a variable with a different value or data type:


• x=5
• x = x + 1 # Reassigning x with a new value (6)
KEYWORDS
Keywords in Python are reserved words that have special meanings in the
language. They cannot be used as variable names, function names, or any
other identifiers. Keywords are always available—you'll never have to
import them into your code.

There are 35 keywords in Python 3.11:


• False, None, True, and, as
• Assert, async, await, break, class, continue, def, del
• elif, else, except, finally, for, from, global, if, import
• in, is, lambda, nonlocal, not, or, pass, raise, return, try
• while, with, yield
DATA TYPES IN
PYTHON
DATA TYPES
Data Type represent the type of data present inside a variable.
In Python we are not required to specify the type explicitly. Based on value Provided, the type will be assigned
automatically. Hence Python is Dynamically typed Language.
The following are the standard or built-in data types in Python:

We have a type() function to check their data types of a variable


Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A numeric value can be an integer, a
floating number, or even a complex number.

1) Integer:
This value is represented by int class. It contains positive or negative whole numbers (without fractions or decimals).
Example: a=10
type(a) #int

2) Float:
This value is represented by the float class. It is a real number with a floating-point representation. It is specified by a
decimal point.
Example: f=1.234
type(f) #float

3) Complex Numbers:
A complex number is represented by a complex class. It is specified as (real part) + (imaginary part)j .
Example: c = 2+3j
Boolean Data Types in Python
We use bool() to represent Boolean data type. Booleans are often used for making decisions and
controlling the flow of a program through conditional statements like if, else, and while. The only
allowed Values for this data type are: True(1) and False(0)
Example: a=10 b=20
c=a<b
print(c) #True
type(b) #bool

Sequence Data Types in Python


The sequence Data Type in Python is the ordered collection of similar or different Python data types.
Sequences allow storing of multiple values in an organized and efficient fashion.
There are several sequence data types of Python:
1. Python String
2. Python List
3. Python Tuple
STRINGS
STRING
Strings are sequences of characters used to represent text in programming. In Python, strings are one of the
fundamental data types and are immutable, meaning that once created, their contents cannot be changed. They can
include letters, numbers, and special characters.

 Declaration:
Strings are created by enclosing characters in single quotes ('), double quotes ("), or triple quotes (''' or """).

Single Quotes:
String1 = ‘Hello, World!’

Double Quotes:
String1 = “Hello, World!”

Triple Quotes (for multi-line strings):


string3 = """Hello,
World!"""
 Escape Characters:
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.

code Result Example


\n newline print("Hello\nWorld”) #Output: # Hello
# World
\t tab print("Hello\tWorld") #Output: Hello World

\\ backslash print(“It is backslash\\") #Output: It is backslash\

\’ single quotes print('It\’s a quote’) #Output: It’s a quote

\” double quotes print(“she said, \"Hello!\"") #Output: She said, "Hello!"

 How to access characters of a String:


We can access characters of a string by using the following ways.

1. Indexing: Accessing individual characters in a string using zero-based indexing.


2. Slicing: Extracting a substring using the slice notation [start: stop: step].
 By using index:
Python supports both +ve and -ve index.
• +ve index means left to right(Forward direction) +tv
• -ve index means right to left(Backward direction) –tv

Example:-
str1 = "Hello"
print(str1[0]) # Output: ‘H’
print(str1[-1]) # Output: ‘o’

 Accessing characters by using slice operator:


Syntax: s[begin: end: step]

Example:-
s="Learning Python is very easy!!!"
print(s[0:8:1] ) # Output: ‘Learning’

Note:
if +ve then it should be forward direction (left to right) and we have to consider begin to end-1 if -ve then it should be backward direction (right to
left) and we have to consider begin to end+1
 Mathematical Operators for String:
We can apply the following mathematical operators for Strings.
1. + operator for concatenation
2. * operator for repetition
Ex:-
print("craw"+"cyber") #crawcyber
print("craw"*2) # crawcraw

Note:
1.To use + operator for Strings, compulsory both arguments should be str type
2.To use * operator for Strings, compulsory one argument should be str and other argument should be int

 String Methods:
Python provides a variety of methods for string manipulation.
• len(): It returns the length of the string..
Example:
s=‘hello’
print(len(s)) #5
• upper(): Converts all characters in the string to uppercase.
s=‘hello’
print(s.upper()) #HELLO

• lower(): Converts all characters in the string to lowercase.


s=‘HELLO’
print(s.lower()) #hello

• capitalize(): Converts the first character of string to uppercase.


s=‘hello world’
print(s.capitalize()) #Hello world

• title(): Converts the first character of each word to uppercase.


s=‘hello world’
print(s.title()) #Hello World

• strip(): Removes leading and trailing whitespace.


s=‘ hello ’
print(s.strip()) #‘hello’

• find(): Returns the lowest index of the substring if found, otherwise returns -1.
s=‘Hello world’
print(s.find(world)) #6
• replace(): Replaces all occurrences of the old substring with new.
s=‘hello world’
print(s.replace(“world", "Python")) #Hello Python

• split(): Splits the string into a list using the specified delimiter.
s= "Hello, World!"
print(s.split(“,”)) # Output: ['Hello', 'World!’]

• join(): Joins elements of a list into single string with the specified separator.
s= ['Hello', 'World’]
print(“ ".join(s)) # Output: 'Hello World’

• count(): Returns the number of times a specified value occurs in a string


s= ‘Hello’
print(s.count(‘l’)) # Output:2

• startswith(): Returns True, if string start with specified substring(prefix)


s= ‘Hello World’
print(s.startswith(‘H’)) # Output: True

• endswith(): Returns True, if string end with specified substring(suffix)


s= ‘Hello World’
print(s.endswith(‘World’)) # Output:True
 Formatting the Strings:

Formatting with % Operator:


Concept: Using the % operator to insert values into a sentence template.
Step 1: Create Template: Write a sentence with placeholders like %s, %d, %f for strings, integers, and floating-point numbers.
Step 2: Insert Values: Use % to insert values at the end of the sentence, in order, separated by commas.
Different Placeholders:
 %s: For strings (names, words).
 %d: For integers (ages, numbers without decimals).
 %f: For floating-point numbers (numbers with decimals).

Example:
name = "Alice"
age = 30
print("Hello, %s! You are %d years old." % (name, age))
 Formatting with f-strings (Formatted String Literals):

Concept: Using f-strings to easily create formatted strings with placeholders and values.
Creating F-Strings: Start your string with f or F, and then use curly braces {} to enclose placeholders for values.
Inserting Values: Inside the curly braces, you can directly put the variables or expressions you want to include in the
string.

Example:
name = "Alice"
age = 30
formatted_string = f"Hello, {name}! You are {age} years old."
print(formatted_string)
Expressions and Calculations: You can even include calculations or expressions inside the curly braces.

Example:
radius = 5
area = f"The area of a circle with radius {radius} is {3.14 * radius ** 2}."
print(area)
 Advanced Placeholder Control:

Using Index Numbers:

 {0} refers to the first value passed to .format().


 {1} refers to the second value passed to .format().
And so on...

name = "Alice"
age = 30
sentence = "Name: {0}, Age: {1}".format(name, age)
print(sentence)

f_string = "Name: {name}, Age: {age}".format(name="Carol", age=22)


print(formatted_string) # Output: 'Name: Carol, Age: 22'
PYTHON LIST
LIST
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and
Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Example

thislist = ["apple", "banana", "cherry"]

print(thislist) #Output: ["apple", "banana", "cherry"]

Lists can hold a mixture of data types, including other lists.

list1 = [["apple", "banana", "cherry"], “veg“, 23, 78]


Characteristics:
● Ordered: Lists maintain the order of items as they were added. and that order will not change.If you add new items to
a list, the new items will be placed at the end of the list.

● Mutable: You can modify, add, or remove items after the list is created.

● Allow Duplicate Values: Lists can contain duplicate items.

● Indexed: Items in a list are accessed via indices, starting from 0. The slice operator [] can be used to get to the List's
components.
thislist = ["apple", "banana", "cherry"]
print(thislist[1]) #output: “apple”

python supports negative indexing also.


print(thislist[-1]) #output: “cherry”
Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.

Example:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5]) #output: ["cherry", "orange", "kiwi"]

Example:
This example returns the items from the beginning to, but NOT including, "kiwi":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[:4]) #output: ["apple", "banana", "cherry", "orange"]


Example-
By leaving out the end value, the range will go on to the end of the list:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:]) #output: ["cherry", "orange", "kiwi", "melon", "mango"]

Range of Negative Index


thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[-4:-1])

Python - Change List Items

Change Item Value:


thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"

Change a Range of Item Value:


thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
 List Methods:
Python lists come with a variety of methods that allow for various operations.

1. append(item): add item at the end of the list.


my_list = [1,2,3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

2. extend(iterable): Extends the list by appending elements from an iterable.


list1 = [1,2,3]
list2 = [4,5]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4,5]

3. insert(index, item): Inserts an item at a specified index.


my_list = [1,2,4]
my_list.insert(2,3)
print(my_list) # Output: [1,2,3,4]

4. remove(item): remove first occurrence of specified item.


my_list = [1,2,3,2]
my_list.remove(2)
print(my_list) # Output: [1,3,2]

47
5. pop(index): Removes and returns the item at the specified index. If no index is specified, pop() removes and
returns the last item.
my_list = [1, 2, 3]
print(my_list.pop()) # Output: 3
print(my_list) # Output: [1, 2]

6. index(item): Returns the index of the first occurrence of an item.


list1 = [1,2,3]
print(list1.index(2)) # Output: 1

7. count(item): Returns the number of occurrences of an item.


my_list = [1,2,4,4]
print(my_list.count(4)) # Output: 2

8. reverse(): Reverses the elements of the list in place


my_list = [1,2,3,4]
print(my_list.reverse()) # Output: [4,3,2,1]

9. sort(): Sorts the list in ascending order.


my_list = [1,5,3,2,4]
print(my_list.sort()) # Output: [1,2,3,4,5]

if we want list in descending order.


my_list.sort(reverse=True) # Output: [1,2,3,4,5]

48
TUPLE
TUPLE
Tuples are just like lists except that they are immutable. i.e. we cannot modify
tuples.

Tuples are defined by specifying items separated by commas within a pair of


parentheses.

Typically used in cases where a statement or a user-defined function can safely


assume that the collection of values i.e. the tuple of values used will not
change.

For example:

tup = ("apple", "banana", "cherry“)


tup = (1,2,3)

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index
[1] etc.
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1]) #output: “apple”

print(thistuple[-1]) #output: “cherry”

Range of Indexes:
You can specify a range of indexes by specifying where to start and where to end the range.
thistuple = ("apple", "banana", "cherry“, "orange", "kiwi", "melon", "mango")
print(thistuple[2:5]) #output: ('cherry', 'orange', 'kiwi’)

This example returns the items from the beginning to, but NOT including, "kiwi":
thistuple = ("apple", "banana", "cherry“, "orange", "kiwi", "melon", "mango")
print(thistuple[:4])

#output: ("apple", "banana", "cherry", "orange“)

Python has two built-in methods that you can use on tuples.

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it was found
DICTIONARY
DICTIONARY
A dictionary is like an address-book used to find address/contact details of a
person by knowing only his/her name.
i.e. we associate keys (name) with values (details).

Note that the key must be unique.


i.e. we cannot find out the correct information if we have two persons with
the exact same name.

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow


duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and


earlier, dictionaries are unordered.
SYNTAX:

Dictionaries are written with curly brackets, and have keys and values:

d = {key1 : value1, key2 : value2 }.


Notice that:
• the key and value pairs are separated by a colon
• pairs are separated themselves by commas
• all this is enclosed in a pair of curly brackets or braces
For Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}


Accessing Items
Using key:
You can access the items of a dictionary by referring to its key name, inside square brackets:
For Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"] #"Mustang"

Using get() method:


There is also a method called get() that will give you the same result:
For Example:
x = thisdict.get("model") #"Mustang

Get keys:
The keys() method will return a list of all keys in the dicionary:
For Example:
x = thisdict.keys() #["brand","model“,"year"]
Get Values:
The values() method will return a list of all values in the dicionary:
For Example:
x = thisdict.values() #["Ford","Mustang",1964]

Get Items:
The items() method will return each item in a dictionary, as tuples in a list.
For Example:
x = thisdict.items() #[("brand","Ford"),("model","Mustang"),("year",1964)]

Change Values
You can change the value of a specific item by referring to its key name:
For Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

thisdict["year"] = 2018
Add Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
For Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
#Output: {'brand':'Ford','model':'Mustang','year':1964,'color':'red' }

Update Items
The update() method will update the dictionary with the items from a given argument. If the item does not exist, the
item will be added.
thisdict.update({"year": 2020})
Remove Items
There are several methods to remove items from a dictionary:
Using pop() method:
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Using del keyword:


The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
The del keyword can also delete the dictionary completely:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

Clear() Method:

The clear() method empties the dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict) #{}
SET
SETS
Sets are used to store multiple items in a single variable.

A set is a collection which is unordered, unchangeable*, and do not allow duplicate


values.

Unordered: items in a set do not have a define order. Set item can appear in a
different order every time you use them, and cannot be referred to by index or key.

Unchangeable: we cannot change the items after the set has been created. Once set
is created, you cannot change its items, but you can remove or add items.

Sets are written with curly brackets.


myset = {"apple", "banana", "cherry“}

Sets cannot have two items with same value.


myset = {"apple", "banana", "cherry“, "apple“}
print(myset) //output: {"banana", "cherry", "apple"}
Access Items
You cannot access items in a set by referring to an index or a key. But you can loop through the set items using a for
loop, or ask if a value is present in a set, by using in keyword.
Example:
myset = {"apple", "banana", "cherry"}

for x in myset:
print(x)
Check if “apple” present in a set:
print({"apple" in myset)

Add Items
You cannot change its items, but you can add new items.
add() method: to add one item in a set use add() method.
myset = {"apple", "banana", "cherry"}
myset.add(“orange")
output: {"apple", "banana", "cherry", "orange"}
Add Any Iterable
To add items from another set or any iterable object(tuple, list, dictionary) into current set, use update() method.
Example:
myset = {"apple", "banana", "cherry"}
set2 = {"mango", "orange", "litchi"}
myset.update(set2)
print(myset) //{"apple", "banana", "cherry", "mango", "orange", "litchi"}

Remove Items
To remove items in a set, use the remove(), or discard() method.
myset = {"apple", "banana", "cherry"}
myset.discard("banana")
myset.remove("banana")

Note: if item to remove doesn’t exist, discard() will not raise an error, but remove() will raise error
pop() method:
We can also use pop() method to remove an item, but this method will remove a random item.
Example:
myset = {"apple", "banana", "cherry"}
myset.pop()
print(myset) //{"banana", "cherry"}

clear() method:
The clear method empties the set.
myset.clear()
print(myset)

del() keyword:
The del keyword will delete the set completely.
del myset
Join Sets
There are several ways to join two or more sets in Python.
The union() and update() methods joins all items from both sets.
The intersection() method keeps ONLY the duplicates.
The difference() method keeps the items from the first set that are not in
the other set(s).
The symmetric_difference() method keeps all items EXCEPT the
duplicates…..
union():
The union() method returns a new set with all items from both sets.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3) //{1,"a",2,"b",3,"c"}

We can use the | operator instead of union() method.


set3 = set1|set2

The union() method allows you to join a set with other data types, like lists or tuples.
y = (1, 2, 3)
z = set1.union(y)

update():
The update() method inserts all items from one set into another. The update() changes the original set, and does not return
a new set.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)

We can use the |= operator instead of update() method.


set1|=set2

print(set1)
intersection():
Keeps only the duplicates.
The intersection() method will return a new set, that only contains the items that are present in both sets.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3, "a" }
set3 = set1.intersection(set2)
print(set3) //{"a"}

you can use the & operator instead of the intersection() method.
set3 = set1 & set2
print(set3) //{"a"}

intersection_update():
The intersection_update() method will also keep ONLY the duplicates, but it will change the original set instead of returning a
new set.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3, "a" }
set1.intersection_update(set2)
print(set1)

you can use the &= operator instead of the intersection_update() method.
set1 &= set2
print(set1) //{"a"}
difference():
The difference() method will return a new set that will contain only the items from the first set that are not present in the other
set.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3, "a" }
set3 = set1.difference(set2)
print(set3) //{"b", "c"}

you can use the - operator instead of the intersection() method.


set3 = set1-set2
print(set3) //{"b", "c"}
difference_update():
The difference_update() method will also keep the items from the first set that are not in the other set, but it will change the
original set instead of returning a new set.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3, "a" }
set1.difference_update(set2)
print(set1) //{"b", "c"}

you can use the -= operator instead of the intersection() method.


set1 -= set2
print(set1) //{"b", "c"}
symmetric_difference():
The symmetric_difference() method will keep only the elements that are NOT present in both sets.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3, "a" }
set3 = set1.symmetric_difference(set2)
print(set3) //{"b", "c", 1, 2, 3}

you can use the ^ operator instead of the intersection() method.


set3 = set1^set2
print(set3) //{"b", "c", 1, 2, 3}

symmetric_difference _update():
The symmetric_difference_update() method will also keep all but the duplicates, but it will change the original set instead of
returning a new set.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3, "a" }
set1.symmetric_difference_update(set2)
print(set1) //{"b", "c", 1, 2, 3}

you can use the ^= operator instead of the intersection() method.


set1 ^= set2
print(set1) //{"b", "c", 1, 2, 3}
USER INPUT
AND
DATA TYPE CASTING
USER INPUT
User input in Python allows you to get information or data from a user while your program is running. This input can be
anything from numbers and text to choices or options. Here are common data types you may encounter when receiving user
input and how to handle them:

• String Input:
By default, the input() function treats user input as a string.
user_input = input("Enter a string: ")

• Integer Input:
To receive an integer input from the user, you can use int() to convert the string input to an integer.
user_input = int(input("Enter an integer: "))

• Floating-Point Input:
To receive a floating-point input from the user, you can use float() to convert the string input to a float.
user_input = float(input("Enter a floating-point number: "))
• List or Tuple Input:
To receive a list or tuple as input, you can split the user's input string based on a delimiter (e.g., a comma or space).
user_input = input("Enter a list of numbers separated by commas: ")
user_list = user_input.split()

 split() method is used to split a string into a list of substrings based on a specified delimiter

• Custom Input Handling:


Depending on your application, you might need to implement custom input handling and validation to ensure the
input matches your requirements.

while True:
user_input = input("Enter a valid option (A, B, or C): ").strip().upper()
if user_input in ('A', 'B', 'C'):
break
else:
print("Invalid input. Please try again.")
This code repeatedly asks the user for input until they enter 'A', 'B', or 'C'.
DATA TYPE CASTING
The conversion of one data type to another data type is known as data type casting in python. There are so
many ways:-
• Integer to Float:

x = 42
y = float(x)
print(y) # Output: 42.0
In this example, we convert an integer (x) to a floating-point number (y) using the float() function.

• Float to Integer:

x = 3.14
y = int(x)
print(y) # Output: 3
Here, we convert a float (x) to an integer (y) using the int() function. The fractional part is truncated.

• String to Integer:

num_str = "42"
num_int = int(num_str)
print(num_int) # Output: 42
We use int() to convert a string containing a numeric value to an integer.
• Integer to String:

x = 42
x_str = str(x)
print(x_str) # Output: "42"
In this case, we convert an integer (x) to a string (x_str) using the str() function.

• String to Float:

float_str = "3.14"
float_num = float(float_str)
print(float_num) # Output: 3.14
We use float() to convert a string containing a floating-point value to a float.

• Boolean to Integer:

bool_value = True
int_value = int(bool_value)
print(int_value) # Output: 1
Boolean True is converted to the integer 1 using int().
• Integer to Boolean:

int_value = 0
bool_value = bool(int_value)
print(bool_value) # Output: False
An integer value of 0 is converted to the boolean False using bool().

• List to Tuple:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)
We convert a list to a tuple using the tuple() function.

• Tuple to List:

my_tuple = (4, 5, 6)
my_list = list(my_tuple)
print(my_list) # Output: [4, 5, 6]
Here, a tuple is converted to a list using the list() function.
OPERATORS
OPERATORS
• Operators in Python are special symbols or keywords that are
used to perform operations on values or variables.
• They enable you to manipulate data by performing actions like
addition, subtraction, comparison, logical operations, and more.
• Python provides various types of operators.
TYPES OF OPERATORS

Arithmetic
operator

Assignmen Logical
t operators operators

Membership
operators

Compariso Identity
n operators operators

Bitwise
operators
 ARITHMETIC OPERATORS:
EXAMPLE
These operators are used for mathematical
calculations. Operators Meaning Example Result

Common arithmetic operators include: + addition 2+2 4


• + (Addition): Adds two values together. - Subtraction 4-2 2
• - (Subtraction): Subtracts the right operand from
* Multiplication 2*2 4
the left operand.
• * (Multiplication): Multiplies two values. / Division 4/2 2
• / (Division): Divides the left operand by the % Modulus 5%2 1
right operand. operator
• % (Modulus): Returns the remainder of the ** Exponent 5**2 25
division. // Floor division 5//2 2
• ** (Exponentiation): Raises the left operand to
the power of the right operand. -5//2 -3
• // (Floor Division): Returns the quotient of the
division, discarding the remainder.
 COMPARISON OPERATORS:
These operators are used to compare two values EXAMPLE
and return a Boolean result (True or False).
Operator Meaning Example Result
Common comparison operators include:
s
• == (Equal to): Checks if two values are equal.
< Less than 5<2 False
• != (Not equal to): Checks if two values are not
equal. > Greater than 5>2 True
• < (Less than): Checks if the left operand is less <= Less than or equal to 5<=2 False
than the right operand.
• > (Greater than): Checks if the left operand is >= Greater than or equal 5>=2 True
greater than the right operand. to
• <= (Less than or equal to): Checks if the left == Equal to equal to 5==2 False
operand is less than or equal to the right != Not equal to 5!=2 True
operand.
• >= (Greater than or equal to): Checks if the left
operand is greater than or equal to the right
operand.
 LOGICAL OPERATORS:
EXAMPLE
These operators are used to perform logical
operations on Boolean values. Operator Meaning Example Result
Common logical operators include:
• and (Logical AND): Returns True if both and Logical (5<2) and False
operands are True. and (5>3)

• or (Logical OR): Returns True if at least or Logical or (5<2) or (5>3) True


one operand is True.
• not (Logical NOT): Returns the opposite not Logical Not (5<2) True
of the operand's value. not
 ASSIGNMENT OPERATORS:
EXAMPLE
These operators are used to assign values to
variables. Operat Example Equivalent Resul
or expression t
Common assignment operators include: (a= 2)
• = (Assignment): Assigns the value on = a = 2 +2 a = 2+2 4
the right to the variable on the left. += a+=10 a = a+ 10 12
• +=, -=, *=, /=, %= (Compound
-= a-=10 a = a- 10 -8
Assignment): Performs the operation and
assigns the result to the variable. *= a*=10 a = a* 10 20

/= a/=10 a = a/ 10

%= a%=10 a = a % 10

**= a**=10 a = a**10

//= a//=10 a = a//10


NUMBERING SYSTEM
• In the decimal numbering system, numbers are represented Example

using ten digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. # Binary representation (base-2)


• Most numerical operations and data types in Python work binary_number = bin(42) # '0b101010'

with decimal numbers by default. # Octal representation (base-8)


• For example, integers, floating-point numbers, and octal_number = oct(42) # '0o52'

arithmetic operations are all based on the decimal system. # Hexadecimal representation (base-16)
• These functions include bin(), oct(), and hex() for hexadecimal_number = hex(42) # '0x2a'

converting to binary, octal, and hexadecimal # Converting from binary to decimal


representations, respectively, and int() with a specified decimal_from_binary = int('101010', 2) # 42

base for converting from other numbering systems to # Converting from octal to decimal
decimal. decimal_from_octal = int('52', 8) # 42

# Converting from hexadecimal to decimal


decimal_from_hexadecimal = int('2a', 16) # 42
 BITWISE OPERATORS:
• Binary Representation
The representation of a decimal number as a binary number involves converting the decimal number
into its binary equivalent using a process called binary conversion. In binary, each digit is either a 0
or a 1.

We can do this conversion manually also


Truth Table

These operators perform bit-level operations on integers.


Common bitwise operators include:
• & (Bitwise AND): Performs a bitwise AND operation.
• | (Bitwise OR): Performs a bitwise OR operation.
• ^ (Bitwise XOR): Performs a bitwise XOR (exclusive OR) operation.
• ~ (Bitwise NOT): Inverts the bits of a number.
• << (Left Shift): Shifts the bits to the left.
• >> (Right Shift): Shifts the bits to the right.
EXAMPLES:-
a = 5 # binary: 0101
b = 3 # binary: 0011
result = a & b # Bitwise AND (binary result: 0001, decimal result: 1)

a = 5 # binary: 0101
b = 3 # binary: 0011
result = a | b # Bitwise OR (binary result: 0111, decimal result: 7)

a = 5 # binary: 0101
b = 3 # binary: 0011
result = a ^ b # Bitwise XOR (binary result: 0110, decimal result: 6)

a = 5 # binary: 0101
result = ~a # Bitwise NOT (binary result: 1010, decimal result: -6 due to two's complement representation)

a = 5 # binary: 0101
result = a << 2 # Bitwise Left Shift by 2 (binary result: 010100, decimal result: 20)

a = 16 # binary: 10000
result = a >> 2 # Bitwise Right Shift by 2 (binary result: 0010, decimal result: 4)
 MEMBERSHIP OPERATORS:
These operators are used to test if a value is a member of a sequence (e.g., a list, tuple, or
string).
Common membership operators include:

• in: This operator is used to check if an element exists in a sequence. It returns True if
the element is found and False if it's not.

Example 1 (with a list):


fruits = ["apple", "banana", "cherry"]
result = "banana" in fruits # True, because "banana" is in the list

Example 2 (with a string):


text = "Hello, world!"
result = "world" in text # True, because "world" is in the string # True, because "world"
is in the string
• not in Operator: This operator is used to check if an element does not exist in a
sequence. It returns True if the element is not found and False if it is found.

Example 1 (with a list):


fruits = ["apple", "banana", "cherry"]
result = "orange" not in fruits # True, because "orange" is not in the list

Example 2 (with a string):


text = "Hello, world!"
result = "goodbye" not in text # True, because "goodbye" is not in the string
 IDENTITY OPERATORS:
These operators are used to compare the memory addresses of two objects.
Common identity operators include:
• is: This operator returns True if two variables reference the same object in memory and False
otherwise. It checks if the operands have the same identity.
Example:-
a = [1, 2, 3]
b = a # Both variables reference the same list object
result = a is b # True, because 'a' and 'b' refer to the same list object

• is not: This operator returns True if two variables reference different objects in memory and
False if they reference the same object. It checks if the operands have different identities.

Example:-
x = "hello"
y = "world"
result = x is not y # True, because 'x' and 'y' reference different string objects
OPERATOR PRECEDENCE
Operator precedence describes the order in which operations are performed.
The precedence order is described in the table below, starting with the highest precedence at the top:

If two operators have the same precedence, the expression is evaluated from left to right.
FLOW CONTROL
STATEMENT
Flow Control Statement
CONDITIONAL STATEMENTS
• Python conditional statements allow you to control the flow of your
program by executing different blocks of code depending on whether
certain conditions are met. The primary conditional statements in Python
are if, elif (short for "else if"), and else.

Conditional
statement

‘if’ statement ‘elif’ statement ‘else’ statement


 IF STATEMENT:
• The if statement is used to execute a block of code only if a specified condition is True.
• The basic syntax is:
if condition:
# Code to execute if the condition is True

Example:
age = 18
if age >= 18:
print("You are an adult.")
 ELIF STATEMENT:
• The elif statement is used to check additional
conditions if the preceding if condition is
False. Example:-
• You can have multiple elif clauses. x = 10
if x > 15:
• The basic syntax is:
print("x is greater than 15")
if condition1: elif x > 5:
# Code to execute if condition1 is True print("x is greater than 5 but not greater
elif condition2: than 15")
# Code to execute if condition2 is True else:
print("x is 5 or less")
 ELSE STATEMENT:
• The else statement is used to execute a block
of code if none of the preceding conditions
is True.
• It comes at the end of an if-elif-else block. Example:
age = 15
• The basic syntax is: if age >= 18:
print("You are an adult.")
if condition: else:
# Code to execute if condition is True print("You are a minor.")
else:
# Code to execute if condition is False
 NESTED CONDITIONAL STATEMENTS:
• You can nest if-elif-else statements within each other to handle more complex
conditions.
Example:
x = 10
y=5
if x > y:
print("x is greater than y.")
if x % 2 == 0:
print("x is even.")
else:
print("x is odd.")
else:
print("x is not greater than y.")
 TERNARY CONDITIONAL EXPRESSION:
• Python also supports a shorter way to write conditionals known as
the ternary conditional expression.
• It provides a way to return a value based on a condition in a single
line.

Example:
age = 20
status = "adult"
if age >= 18 else "minor"
print(f"You are an {status}.")
INTERATIVE / LOOP STATEMENT
• Python provides several iterative statements that allow you to execute a
block of code repeatedly. These statements are used to create loops and
are essential for performing repetitive tasks. The primary iterative
statements in Python are:

Loop statement

For loop While loop


 FOR LOOP
• The for loop is used to iterate over a sequence (e.g., a list, tuple, string, or
range) or other iterable objects.
• It executes a block of code for each item in the sequence.

Example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output:
apple
banana
cherr
 WHILE LOOP
• The while loop repeatedly executes a block of code as long as a specified
condition is True.
• It continues until the condition becomes False.
Example:
i=0
while i < 5:
print(i)
i += 1

OUTPUT:
0
1
2
3
4
 RANGE() FUNCTION
• The range() function is often used in conjunction with for loops to generate
a sequence of numbers.
• It allows you to specify the start, end, and step size of the sequence.

Example
for i in range(1, 6):
print(i)

Output:
1
2
3
4
5
 INFINITE LOOP
• An infinite loop in Python is a loop that continues to execute indefinitely, never reaching
a point where the loop's exit condition becomes False.

Example
i=0
while True:
i=i+1
print(i,”Hello”)
 NESTED FOR LOOP
• Sometimes we can take a loop inside another loop, which are
also known as nested loops.

Example
for i in range(2):
print("Outer Loop",i)
for j in range(3):
print("Inner Loop",j)
print("Rest of the code")
CONTROL / TRANSFER STATEMENT
• Python relies on various control flow statements and functions to achieve similar
functionality.
• Depending on what you mean by "transfer statement," here are a few possible
interpretations:

Transfer statement

Break Continue
 Break:  pass Statement:
We can use break statement inside loops to break loop The pass statement is a null statement which can be used as a
execution based on some condition. placeholder for future code.
Example:
Suppose we have a loop or a function that is not implemented
for i in range(5): Output
yet, but we want to implement it in the future. In such cases, we
if i == 3: 0
can use the pass statement.
break 1
2
print(i) The syntax of the pass statement is:
Pass

 Continue: Example:
We can use continue statement to skip current iteration and n = 10
continue next iteration.
Output # use pass inside if statement
Example:
0 if n > 10:
for i in range(5): pass
1
if i == 3: 2
continue 4 print('Hello')
print(i)
FUNCTIONS
FUNCTIONS
Functions is a block of statements that return the specific task. It's a way to group together a set of
instructions that can be easily reused.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability

Types of Functions in Python


There are mainly two types of functions in Python.

• Built-in library function: These are Standard functions in Python that are available to use.
Example:- print(), type(), id() etc.

• User-defined function: We can create our own functions based on our requirements.
Create a function in python:

We can create a user-defined function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require.

Syntax:
A simple Python function

def fun():
print("Welcome to craw security")

Calling a Python Function


After creating a function in Python we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.

# Driver code to call a function


fun()

Output:
Welcome to craw security
Arguments:
A function can accept some values it can work with.
Arguments are specified after the function name, inside the parentheses.
Example:
def fun(name):
print("Hello "+name)

fun("Reena") //Hello Reena


You can add as many arguments as you want, just separate them with a comma.

Types of Arguments:
• Formal argument (Parameter): Parameter as a placeholder or a variable name used in a function's definition.
In other words, Parameters are like empty boxes or slots that a function expects. They are defined in the function's
blueprint (the function declaration).

 Actual Argument (Argument): An argument, is the actual value or data that you pass to a function when you call it.
In simple words, Arguments are the actual items you put inside those boxes or slots when you use the function. You
provide arguments when you call or use the function.
Here ,we see some example of parameters and arguments:-
Example 1:
def add_numbers(a , b): # 'a' and 'b' are parameters
result = a + b
return result
# Using the function with arguments
sum_result = add_numbers(5,3) # '5' and '3' are arguments
print(sum_result) # Output: 8

Example 2:

def greet(name): # 'name' is a parameter


greeting = f"Hello, {name}!"
return greeting

# Using the function with an argument

message = greet("Alice") # "Alice" is an argument


print(message) # Output: Hello, Alice!
 Types of Actual Arguments
In the context of Python programming, when you mention "types of arguments," you're likely referring to the different ways
you can pass arguments to functions. Here are the common types of arguments you can use in Python functions:

1. **Positional Arguments**: These are the most basic type of arguments. They are passed to a function in the order they
appear in the function's parameter list. The function's parameters should be defined to accept them in the same order.
Example:-
def nameAge(name, age): Output:
print("Hi, I am", name)
print("My age is ", age) Case-1:
# You will get correct output because Hi, I am Suraj
# argument is given in order My age is 27
print("Case-1:")
nameAge("Suraj", 27) Case-2:
# You will get incorrect output because Hi, I am 27
# argument is not in order My age is Suraj
print("\nCase-2:")
nameAge(27, "Suraj")
2. **Keyword Arguments**: With keyword arguments, you explicitly mention the parameter names and their corresponding
values when calling the function. This allows you to pass arguments in any order, making the code more readable and less
prone to errors.
Example:-
Output:
def student(firstname, lastname):
print(firstname, lastname) Geeks Practice
# Keyword arguments Geeks Practice
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks’)
3. **Default Arguments**: Default arguments have preset values in the function's parameter list. If the caller doesn't provide
a value for these parameters, the default value is used.
Example:-
Output:
def myFun(x, y=50):
x: 10
print("x: ", x)
y: 50
print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(10)
4. **Variable-Length Positional Arguments (Arbitrary Arguments)**: Variable length argument is an argument that can
accept any number of values.
The variable length argument is written with * symbol.
It stores all the value in a tuple.
def recipe(ingredient1, *extra_ingredients):
print("Main Ingredient:", ingredient1)
print("Extra Ingredients:", extra_ingredients)

recipe("chicken", "carrots", "peas", "potatoes")


Output: Main Ingredient: chicken
Extra Ingredients: ('carrots', 'peas', 'potatoes')

5. **Variable-Length Keyword Arguments (Arbitrary Keyword Arguments)**: Keyword Variable length argument is an
argument that can accept any number of values provided in the form of key-value pair.
The keyword variable length argument is written with ** symbol.
It stores all the value in a dictionary in the form of key-value pair
LAMBDA FUNCTION
 A lambda function in Python is a small, anonymous (unnamed) function. It's also known as a "lambda
expression.“.
 Unlike regular functions defined using the def keyword, lambda functions are defined using the lambda
keyword.
 Lambda functions are often used for short, simple operations that can be written in a single line of code.
 They are particularly useful when you need a quick function for a specific task and don't want to go through
the process of defining a regular function.
Here's the basic structure of a lambda function:
 lambda arguments: expression
 lambda: The keyword used to define a lambda function.
 arguments: The input variables (parameters) for the function.
 expression: The operation or calculation you want the function to perform.
Syntax:-
lambda arguments : expression

#Example 1 Single Argument


show = lambda x : print(x)
show(5)

Lambda functions can take any number of arguments:

#Example 2 Two Arguments


add = lambda x,y : (x+y)
print(add(5, 2))

#Example 3 Return Multiple


add_sub = lambda x,y : (x+y, x-y)
a, s = add_sub(5, 2)
print(a)
print(s)

#Example 4 with Default Argument


add = lambda x,y=3 : (x+y)
print(add(5))
GLOBAL KEYWORD
I can change the value of the global variable from inside a function also
a=10
def func():
global a
a=20
print(a)
func()
print(a)

 Output:
20 20
The global keyword in Python is specifically used within functions to indicate that a
variable defined inside the function refers to a global variable with the same name,
OBJECT ORIENTED
PROGRAMMING LANGUAGE
OBJECT ORIENTED PROGRAMMING
LANGUAGE
Object-oriented Programming (OOPs) is a programming paradigm that uses objects

and classes in programming. It aims to implement real-world entities like inheritance,

polymorphisms, encapsulation, etc. in the programming. The main concept of OOPs is

to bind the data and the functions that work on that together as a single unit so that no

other part of the code can access this data.


MAIN CONCEPTS OF OBJECT-ORIENTED
PROGRAMMING
•Class
•Objects
•Polymorphism
•Encapsulation
•Inheritance
CLASS
A class is a collection of objects. A class contains the blueprints or the
prototype from which the objects are being created.
It is a logical entity that contains some attributes and methods.

To understand the need for creating a class let’s consider an example:


let’s say you wanted to track the number of cat’s that may have different
attributes like breed, age.
If a list is used, the first element could be the cat’s breed while the second
element could represent its age.
Let’s suppose there are 100 different cats, then how would you know which
element is supposed to be which?
What if you wanted to add other properties to these cats? This lacks
organization and it’s the exact need for classes.
Some points on Python class:
•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

Class Definition Syntax:

class ClassName:
# Statement-1
. . .
# Statement-N
Example: Creating an empty Class in Python

class Cat:
pass

In the above example, we have created a class named cat


using the class keyword.
OBJECT
The object is an entity that has a state and behavior associated with it.
It may be any real-world object like a mouse, keyboard, chair, table, pen,
etc. Integers, strings, floating-point numbers, even arrays, and dictionaries,
are all objects.
More specifically, any single integer or any single string is an object. The
number 12 is an object, the string “Hello, world” is an object, a list is an
object that can hold other objects, and so on.

An object consists of :
State: It is represented by the attributes(data) of an object. It also reflects
the properties(methods) of an object.
Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
Identity: It gives a unique name to an object and enables one object to
interact with other objects.

To understand the state, behavior, and identity let us take the example
of the class cat (explained above):

The identity can be considered as the name of the cat.


State or Attributes can be considered as the breed, age, or color of the cat.
The behavior can be considered as to whether the cat is eating or sleeping.
Example: Creating an object
obj= cat()
This will create an object named obj of the class cat defined above. Before
diving deep into objects and class let us understand some basic keywords
that will we used while working with objects and classes.

The self
Class methods must have an extra first parameter in the method definition.
We do not give a value for this parameter when we call the method, Python
provides it.
If we have a method that takes no arguments, then we still have to have
one argument.

This is similar to this pointer in C++ and this reference in Java.


self represents the instance of the class.
By using the “self” keyword we can access the attributes and methods of
the class in python. It binds the attributes with the given arguments.
The reason you need to use self. is because Python does not use the @
syntax to refer to instance attributes. Python decided to do methods in a
way that makes the instance to which the method belongs be passed
automatically, but not received automatically: the first parameter of
methods is the instance the method is called on.

Self must be provided as a First parameter to the Instance method and


constructor. If you don’t provide it, it will cause an error.
CONSTRUCTORS IN PYTHON
Constructors are generally used for instantiating an object. The task
of constructors is to initialize(assign values) to the data members of
the class when an object of the class is created.
In Python the __init__() method is called the constructor and is
always called when an object is created.

Syntax of constructor declaration :


def __init__(self):
# body of the constructor

Types of constructors :
1. Default constructor:
2. Parameterized constructor:
Default Constructor: The default constructor is a simple
constructor which doesn’t accept any arguments. Its
definition has only one argument which is a reference to
the instance being constructed.

Parameterized Constructor: constructor with parameters


is known as parameterized constructor. The parameterized
constructor takes its first argument as a reference to the
instance being constructed known as self and the rest of
the arguments are provided by the programmer.

Example of default constructor :


class Employee:

# default constructor
def __init__(self):
self.name = “abc"

# a method for printing data members


def info(self):
print(self.name)

# creating object of the class


obj = Employee()

# calling the instance method using the object obj


obj.info()

Result:
abc
Example of the parameterized constructor :
class Employee:

# parameterized constructor
def __init__(self, empname, empsalary, empage):
self.name = empname
self.salary = empsalary
self.age = empage

def display(self):
print(“Employee name = " + str(self.name))
print(“Employee salary = " +
str(self.salary))
print(“Employee age = " + str(self.age))
# creating object of the class
# this will invoke parameterized constructor
obj = Employee(‘abc’, 700000,24)

# display result
obj.display()

Result:
Employee name: abc
Employee salary: 700000
Employee age: 24
INHERITANCE
Inheritance is defined as the capability of one class to derive or
inherit the properties from some other class and use it whenever
needed. Inheritance provides the following properties:

It provides reusability of code. We don’t have to write the same


code again and again. Also, it allows us to add more features to a
class without modifying it.

It is transitive in nature, which means that if class B inherits from


another class A, then all the subclasses of B would automatically
inherit from class A.
class employee:
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def isEmployee(self):
return False
class company(employee):
def isEmployee(self):
return True

a = employee(“ABC")
print(a.getName(), a.isEmployee())
b = company(“BCD")
print(b.getName(), b.isEmployee())
TYPES OF INHERITANCE
Types of Inheritance depends upon the number of child and parent classes involved. There are four types of
inheritance in Python:
Single Inheritance: Single inheritance enables a derived class to inherit properties from a single parent class,
thus enabling code reusability and the addition of new features to existing code.
For Example:
class A:
a = "I am A"
class B(A): #single inheritance
b = "I am B"
ob = B()
print(ob.b)
print(ob.a)

Multiple Inheritance: When a class can be derived from more than one base class this type of inheritance is
called multiple inheritance. In multiple inheritance, all the features of the base classes are inherited into the
derived class.
For Example:
class A:
a = "I am A"
class B:
b = "I am B"
class C(A,B):
c = "I am C"
Multilevel Inheritance : In multilevel inheritance, features of the base class and the derived class are further inherited
into the new derived class. This is similar to a relationship representing a child and grandfather.
For Example:
class A:
a = "I am A"
class B(A):
b = "I am B"
class C(B):
c = "I am C"

Hierarchical Inheritance : When more than one derived classes are created from a single base this type of inheritance is
called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes.
For Example:
class A:
a = "A"
class B(A):
b = "B"
class C(A):
c = "C"

Hybrid Inheritance : Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
POLYMORPHISM
The word polymorphism means having many forms.
In programming, polymorphism means the same function name (but
different signatures) being used for different types.

Polymorphism with class methods:

class A():
def intro(self):
print(“I am Class A")

class B():
def intro(self):
print(“I am Class A")
FILE HANDLING
FILE HANDLING (INPUT/OUTPUT)
File handling in Python involves working with files on your computer's storage. You can read data from files
(input) and write data to files (output). It's like opening a book to read or write something in it. File handling is
like a temporary database.

For Example: To store high score while developing a game in python


 To open a file
f=open('myfile.txt",'r')
first argrument is filename and second is the mode

By default, the open() function returns a file object that can be used to read from or write to the file , depending
on the mode.
 Modes in files

 read(r): this mode will open the file for reading only and gives an error if the file does not exist. This is the default
mode if no mode is passed as a parameter.
 write(w): This mode opens the file for writing only and creates the new file if the file does not exist, if we open
existing file having some data with this mode,
this mode will remove all data and open this file as a blank file.
 append(a): this mode opens the file for appending only , it keeps existing data safe and can append further data in
existing file…..
this will create a new file if files does not exist….
 exclusive create(x): This mode creates a file and gives an error if the file already exist
 text(t): Apart from these modes we also need to specify how the file must be handled, t mode is used to handle text
files, t refers to text mode
There is no difference between r and rt or w and wt since text mode is the default.
 binary(b): It is used to handle binary files (images,pdfs , etc ).

we need to close a file whenever opened


 Here are the basic steps for file handling:

 Opening a file for reading


file = open("example.txt", "r")
Reading from a File:
In reading mode, you can read the content of the file. This is like reading the words from a book.
content = file.read()
print(content)

 Writing to a File:
In writing mode, you can write new content to the file, overwriting the existing content.
file = open("example.txt", "w")
file.write("Hello, this is new content.")
file.close() # Close the file when done

 Appending to a File:
In append mode, you can add new content to the end of the existing content.
file = open("example.txt", "a")
file.write("\nThis is additional content.")
file.close()
 Closing a File:
Always remember to close the file when you're done with it using the close() method.
file.close()

 with statement
Alternatively , you can use the "with" statement to automatically close the file after you are done with it.
with open('myfile.txt','a') as f:
#do something with the file
f.write("hello world")
Example of file handling
# Open the file "data.txt" in read mode.
with open("data.txt", "r") as f:
# Read the entire file.
data = f.read()

# Read a single line from the file.


line = f.readline()

# Read all of the lines from the file and return them as a list.
lines = f.readlines()

# Open the file "data.txt" in write mode.


with open("data.txt", "w") as f:
# Write a line of text to the file.
f.write("This is a line of text.\n")

# Write a list of lines to the file.


f.writelines(["This is another line of text.\n", "This is the last line of text.\n"])

# Truncate the file "data.txt" to 10 bytes.


with open("data.txt", "wb") as f:
f.truncate(10)

# Close the file "data.txt".


f.close()
EXCEPTION
HANDLING
TYPES OF ERRORS IN PYTHON
Errors in Python fall into two main categories:

1. Syntax Error: These occur when Python code violates the language's syntax rules. The interpreter spots
these errors before execution.
For Example:
print("Hello, This is print statement) //
Output:
SyntaxError: unterminated string literal

2. Runtime Errors (Exceptions):These occur while the program is running. Python throws an exception
when something unexpected happens.
For Example:
a=12
b=0
print(a/b)

Output:
ZeroDivisionError: division by zero
Here are common types of runtime errors (exceptions):

Error Type Description


ZeroDivisionError Division by zero
NameError Using a variable that is not defined
TypeError Incompatible data types
ValueError Function receives the right type but inappropriate value
IndexError Index out of range for lists, tuples
KeyError Dictionary key not found
FileNotFoundError File does not exist
AttributeError Invalid attribute access

# 1. ZeroDivisionError # 4. IndexError
print(10 / 0) # numbers = [1, 2, 3]
print(numbers[5]) # no such index
# 2. NameError
print(x) # 'x' is not defined # 5. KeyError
data = {"name": "John"}
# 3. TypeError print(data["age"]) # no 'age' key
print("5" + 5) # mixing str and int
EXCEPTION HANDLING IN PYTHON
Exception Handling handles errors that occur during the execution of a program(runtime errors) using try except
block. Exception handling allows to respond to the error, instead of crashing the running program.
Syntax:
try:
# code that might raise an exception
except ExceptionType:
# code that runs if an exception occurs

For Example:
#handling division by zero
try:
output = 10/0
except ZeroDivisionError:
print(“You can’t divide by zero”)

Catching Multiple Exceptions


try:
num = int(input("Enter a number: "))
print(10 / num)
except ValueError:
print("Enter a valid number!")
except ZeroDivisionError:
print("Division by zero is not allowed.")
Using else and finally:

else: runs only if no exception occurs


finally: runs no matter what, used for cleanup

For Example:
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
else:
print(content)
finally:
print("Execution finished.")

Catching All Exceptions:


try:
x = int("abc")
except Exception as e:
print(f"An error occurred: {e}")
Raise Statement:
The raise statement forces an exception to occur. You can use it:
• To throw a built-in exception
• to create and throw a custom exception

Syntax:
raise ExceptionType("Error message")

Example:
Raising a built-in Exception:
age = -5
if age < 0:
raise ValueError("Age cannot be negative")

Custom Exceptions with raise:


class InvalidEmailError(Exception):
pass

def validate_email(email):
if "@" not in email:
raise InvalidEmailError("Invalid email address")

validate_email("no-at-symbol.com")
ARRAY
ARRAY
Array is a container which can hold a fix 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.

Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.

As per the above illustration, following are the important points to be considered.
• Index starts with 0.
• Array length is 10 which means it can store 10 elements.
• Each element can be accessed via its index. For example, we can fetch an element at index 6 as 70
Difference between Python Lists and Arrays:
• In Python, Array are just like Lists: an ordered sequence of elements.
• They are also mutable and not fixed in size. Items can be added and removed. However, lists and arrays are not the
same thing.
• Lists store items that are of various data types, But array store only items that are of the same single data type. They
are useful when you want to work with homogeneous data.
• They are also more compact and take up less memory and space which makes them more size efficient compared to
list.
• Arrays are not built-in data structure, and therefore need to imported via array module in order to be used.

How to Use Array in Python:


In Python to create python arrays, we’ll first have to import the array module, which contains all necessary functions.
There are three ways you can import array module:
1. By using import array at the top of the file: This includes the module array. You would then go on to create an array
using array.array().
import array
#how would you create an array
array.array()
2. By using alias name.
import array as arr
#how would you create an array
arr.array()
3. With *: It import all functionalities available.
from array import *
#how would you create an array
array()

How to define Arrays in Python:


Syntax for creating array:
var_name = array(type_code,[elements])

• var_name would be the name of array.


• type_code specifies what kind of elements would be store in the array.
• Inside square brackets you mention elements that would be store in the array, with each element being separated by
comma.
Typecode table with different typecodes used with different data types when defining Python array
Typecode C type Python Type Size
'b' signed char int 1
'B' unsigned char int 1
'u' wchar_t Unicode character 2
'h' signed short int 2
'H' unsigned short int 2
'i' signed int int 2
'I' unsigned int int 2
'l' signed long int 4
'L' unsigned long int 4
'q' signed long I int 8
'Q' unsigned long I int 8
'f' float float 4
'd' double float 8

For Example:

import array as arr


numbers = arr.array('i',[10,20,30])
print(numbers)

Output: array('i', [10, 20, 30])


How to Access Items in an Array:
1. Indexing: Accessing individual characters in a string using zero-based indexing.
2. Slicing: Extracting a substring using the slice notation [start: stop: step].
import array as arr
#original array
numbers = arr.array('i',[10,20,30])

print(numbers[0]) #gets the 1st element


print(numbers[-1]) #gets last item

print(numbers[1:3]) #get the values 20 and 30 only

How to Change the Value of an Item in an Array


#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40
print(numbers)

#output
#array('i', [40, 20, 30])
ARRAY METHODS
DATE & TIME
DATE & TIME
• Date and time are handled by the datetime module. This module provides classes for representing dates, times, and time
intervals.
• Here's an overview of how to work with date and time in Python using the datetime module:
 Import the ‘datetime’ module:
from datetime import datetime, date, time, timedelta

 Current Date and Time:


from datetime import datetime
current_datetime = datetime.now()
print(current_datetime)
# Output: Current date and time in the format: "YYYY-MM-DD HH:MM:SS.ssssss“

 Date and Time Components:


year = current_datetime.year
month = current_datetime.month
day = current_datetime.day
hour = current_datetime.hour
minute = current_datetime.minute
second = current_datetime.second
print(f"Year: {year}, Month: {month}, Day: {day}, Hour: {hour}, Minute: {minute}, Second: {second}")
# Output: Year: XXXX, Month: XX, Day: XX, Hour: XX, Minute: XX, Second: XX (actual values)
 Creating Date and Time Objects:  Print calendar using calendar module
import calendar
from datetime import date, time print(calendar.calendar(2020,1,1,1))

custom_date = date(2023, 9, 22)


custom_time = time(15, 30)

print("Custom Date:", custom_date)


print("Custom Time:", custom_time)

 Formatting Dates and Times:

formatted_date = current_datetime.strftime('%Y-%m-%d’)
formatted_time = current_datetime.strftime('%H:%M:%S’)
formatted_datetime = current_datetime.strftime('%Y-%m-%d %H:%M:%S’)

print("Formatted Date:", formatted_date)


print("Formatted Time:", formatted_time)
print("Formatted Datetime:", formatted_datetime)
MAIL SENDING
PROGRAM
Mail sending program:
1. import smtplib
2. use SMTP class
3. give two information inside SMTP class. First
is gmail ip and second is gmail port number.
4. starttls()
5. login with valid mail id and password
6. write a message
7. sendmail with message from sender to receiver
8. close the connection

https://myaccount.google.com/u/4/apppasswords
Example1:
import smtplib
a = smtplib.SMTP('smtp.gmail.com',587)
a.starttls()
a.login(‘[email protected]','yaualzkljafsbzks’)
msg = 'hello'
a.sendmail(‘[email protected]’,’[email protected]’,msg)
a.quit()

Example2:

import smtplib
import time
a= smtplib.SMTP('smtp.gmail.com',587)
a.starttls()
a.login(‘[email protected]','ijpbnjnwcqumsxqn')
while True:
msg = 'hello'
time.sleep(10)
a.sendmail('[email protected]','[email protected]',msg)
Example3:
import smtplib
import time
a= smtplib.SMTP('smtp.gmail.com',587)
a.starttls()
a.login(‘[email protected]','ijpbnjnwcqumsxqn')
while True:
m= input('enter message: ')
a1= input('enter mail: ')
if m=='' or a1=='':
break
a.sendmail('[email protected]',a1,m)

# send mail to multiple user:


import smtplib
a= smtplib.SMTP('smtp.gmail.com',587)
a.starttls()
a.login('[email protected]','hgzgcrvimnikaywf')
b = ['[email protected]','[email protected]','[email protected]','[email protected]']
for i in b:
m= 'hello'
a.sendmail('[email protected]',i,m)
a.quit()
send mail with body text and subject text,

import smtplib
from email.message import EmailMessage

msg = EmailMessage()

msg['subject']= "sending a message…"


msg['To'] = "[email protected]"
msg['From'] = "[email protected]"
msg['Cc'] = "[email protected]"
msg['Bcc'] = "[email protected]"

text_msg = ‘This is the text message!!!’


msg.set_content(text_msg)

ser = smtplib.SMTP('smtp.gmail.com',587)
ser.starttls()
ser.login(‘[email protected]','jatxkvrkhjiswoyl’)

ser.send_message(msg)

ser.quit()
send mail with attachments

import smtplib
from email.message import EmailMessage

msg = EmailMessage()

msg['subject']= "sending a message…"


msg['To'] = "[email protected]"
msg['From'] = "[email protected]"
msg['Cc'] = "[email protected]"
msg['Bcc'] = "[email protected]"

text_msg = ‘This is the text message!!!’


msg.set_content(text_msg)

Attach the text file


with open('file.txt', 'rb') as file:
data = file.read()
msg.add_attachment(data, maintype='text', subtype='plain', filename='text file')

ser = smtplib.SMTP('smtp.gmail.com',587)
ser.starttls()
ser.login(‘[email protected]','jatxkvrkhjiswoyl’)

ser.send_message(msg)
INTERACTING WITH
NETWORK
Interacting with networks

Server : Client:
1. import socket 1. import socket
2. call socket class 2. call socket class
3. bind the connection with the ip address and 3. connect with the server with server ip and
port number. server port number
4. listen the connection 4. write a message
5. accept the client requests with address and 5. encode the message
message 6. send the message
6. use recv method 7. close the connection
7. decode the message
8. print the message
9. close the connection
Server: Client:

import socket import socket


ip_add = 'localhost' ip_add = 'localhost'
port = 1234 port = 1234
add = (ip_add,port) add = (ip_add,port)

ser_sock = socket.socket() cl_sock = socket.socket()


#type of network(IPv4)
cl_sock.connect(add)
#type of connection(TCP)
ser_sock.bind(add)
m = cl_sock.recv(1024).decode()
print("Server Started.....")
print(m)
m1 = cl_sock.send("Hello Server. I am
ser_sock.listen(3)
client".encode())
print("Listening...")

v,a = ser_sock.accept()
print("Client Connected")

msg = "Hello Client"


v.send(msg.encode())
print(v.recv(1024).decode())
CHAT APPLICATION
Server:

import socket
ip_add = 'localhost'
port = 1234 Client:
add = (ip_add,port)
import socket
ser_sock = socket.socket() ip_add = 'localhost'
#type of network(IPv4) port = 1234
#type of connection(TCP) add = (ip_add,port)
ser_sock.bind(add)
print("Server Started.....") cl_sock = socket.socket()
cl_sock.connect(add)
ser_sock.listen(3)
print("Listening...") while True:
print(cl_sock.recv(1024).decode())
v,a = ser_sock.accept() m1 = input(“Client: ")
print("Client Connected") cl_sock.send(m1.encode())
while True:
msg = input("Server: ")
v.send(msg.encode())
print(v.recv(1024).decode())
If you want to add multiple client at the same time:
# socket with multithreading
import socket
import threading
ip_add = 'localhost'
port = 1234
add = (ip_add,port)
ser_sock = socket.socket()
ser_sock.bind(add)
print("Server Started.....")
ser_sock.listen(3)
print("Listening...")
def conn(client_socket, client_address):
msg = "Hello Client"
client_socket.send(msg.encode())
print(client_socket.recv(1024).decode())
client_socket.close() # Close the client connection
while True:
client_socket, client_address = ser_sock.accept()
print(f"Client {client_address} connected")
t1 = threading.Thread(target=conn, args=(client_socket, client_address))
t1.start()
GRAPHICAL USER
INTERFACE
Graphical User Interface:

tkinter is a module which is used to create a desktop application.

a. import tkinter
b. create main window
c. add widgets
d. run the main window with mainloop

# Geometry configuration:

1. pack()= it will place widgets in block format.


2. grid()= it will place widgets in table format.
3. place()= it will place widgets in desired position.

Total widgets list:

1. Button 8. LabelFrame 15. Frame


2. Canvas 9. Pannedwindow 16. Message
3. Entry 10. Scrollbar 17. Spinbox
4. Text 11. Menu 18. Filedialog
5. Scale 12. Checkbutton
6. Listbox 13. Radiobutton
7. Label 14. Toplevel
1. Label and Entry:
import tkinter
a= tkinter.Tk()
a.geometry('700x500')
a.title('Welcome to craw security..')

d1= tkinter.Label(a,text='Enter your first name',font=('callibri',15,'bold'))


d1.place(x=0,y=10)

d= tkinter.Entry(a,width=30,font=('callibri',15),fg='red',bg='light green')
d.place(x=250,y=10)
a.mainloop()

2. Button:
from tkinter import *
x = Tk()
x.geometry('400x100')
x.title("Welcome to my page")
def say_hi():
Label(x,text='Hi!!!!').pack()

btn = Button(x,text="Click Me",command=say_hi)


btn.pack()
x.mainloop()
Program to calculate sum of Two Numbers :

from tkinter import *


x = Tk()
x.geometry('400x300')
x.title("Get Sum")
l1 = Label(x,text="Enter Number1: ",width=20)
l1.grid(row=1,column=1)
e1 = Entry(x)
e1.grid(row=1, column=2)
l2 = Label(x,text="Enter Number2: ",width=20)
l2.grid(row=3,column=1)
e2 = Entry(x)
e2.grid(row=3, column=2)
def get_sum():
n1 = int(e1.get())
n2 = int(e2.get())
sum = n1 + n2
l = Label(x, text="Sum is: %d"%sum, width=30).grid(row=5,column=2)

btn = Button(x,text="sum",command=get_sum)
btn.grid(row=4,column=2)

x.mainloop()
3. Text and ScrollBar:
from tkinter import *
x = Tk()
x.geometry('400x300')
x.title("Welcome to the craw cyber security")
t = Text(x)
sc = Scrollbar(x,orient=VERTICAL,command=t.yview)
t.config(yscrollcommand=sc)
sc.pack(side=RIGHT,fill=Y)
t.pack(side=LEFT,expand=True)
x.mainloop()

4. Radio Button:
from tkinter import *
x = Tk()
x.geometry('400x300')
x.title("Welcome to the craw cyber security")
v = IntVar()
Radiobutton(x,text="Male",variable=v,value=0).pack()
Radiobutton(x,text="Female",variable=v,value=1).pack()
x.mainloop()
5. CheckButton:
from tkinter import *
x = Tk()
x.geometry('400x100')
x.title('Welcome to craw security..')
v1 = IntVar()
v2 = IntVar()
v3 = IntVar()
c1 = Checkbutton(x, variable=v1,text="Choice1").grid(row=0,column=0)
c2 = Checkbutton(x, variable=v2,text="Choice1").grid(row=1,column=0)
c3 = Checkbutton(x, variable=v3,text="Choice1").grid(row=2,column=0)
x.mainloop()

6. SpinBox:
from tkinter import *
x = Tk()
x.geometry('400x100')
x.title("Welcome to my page")
s = Spinbox(x,from_=0,to=10).pack()
x.mainloop()
5. ComboBox:
from tkinter import *
from tkinter import ttk
x = Tk()
x.geometry('400x100')
x.title('Welcome to craw security..')
country_var = StringVar()
country_combobox = ttk.Combobox(x, textvariable=country_var, values=["USA", "India", "UK",
"Germany", "Australia"], state="readonly")
country_combobox.pack()
x.mainloop()

5. MessageBox:
from tkinter import *
from tkinter import messagebox
x = Tk()
x.geometry('100x100')
x.title('Welcome to craw security..')
messagebox.showinfo('information','Information')
x.mainloop()
Registration Form
#importing tkinter and additional modules
from tkinter import *
from tkinter import ttk, messagebox

# Create the main window


x = Tk()
#set geometry
x.geometry('500x500')
#title
x.title('Registration Form')

# Create and place the form labels and entries


l = Label(x, text="Registration Form", width=20, font=("bold", 20), bg="red")
l.place(x=90, y=45)

l1 = Label(x, text="Name", width=10, font=("bold", 10))


l1.place(x=80, y=100)
e1 = Entry(x)
e1.place(x=240, y=100)

l2 = Label(x, text="Email", width=10, font=("bold", 10))


l2.place(x=80, y=150)
e2 = Entry(x)
e2.place(x=240, y=150)
l3 = Label(x, text="Gender", width=10, font=("bold", 10))
l3.place(x=80, y=200)
gender_var = IntVar()
rad1 = Radiobutton(x, text="Male", variable=gender_var, value=1)
rad1.place(x=240, y=200)
rad2 = Radiobutton(x, text="Female", variable=gender_var, value=2)
rad2.place(x=300, y=200)

l4 = Label(x, text="Age", width=10, font=("bold", 10))


l4.place(x=80, y=250)
spin = Spinbox(x, from_=0, to=60, width=8)
spin.place(x=240, y=250)

l5 = Label(x, text="Country", width=10, font=("bold", 10))


l5.place(x=80, y=300)
country_var = StringVar()
country_combobox = ttk.Combobox(x, textvariable=country_var, values=["USA", "India", "UK", "Germany", "Australia"],
state="readonly")
country_combobox.place(x=240, y=300)

l6 = Label(x, text="Language", width=10, font=("bold", 10))


l6.place(x=80, y=350)
chk1_var = IntVar()
chk2_var = IntVar()
chk1 = Checkbutton(x, text="English", variable=chk1_var)
chk1.place(x=240, y=350)
chk2 = Checkbutton(x, text="Hindi", variable=chk2_var)
chk2.place(x=320, y=350)
# Function to handle submit button click

def submit():
name = e1.get()
email = e2.get()
gender = "Male" if gender_var.get() == 1 else "Female"
age = spin.get()
country = country_var.get()
languages = []
if chk1_var.get():
languages.append("English")
if chk2_var.get():
languages.append("Hindi")
languages_str = ", ".join(languages)
messagebox.showinfo("Form Submitted", f"Name: {name}\nEmail: {email}\nGender: {gender}\nAge:
{age}\nCountry: {country}\nLanguages: {languages_str}")

# Create and place the submit button


bt = Button(x, text="Submit", width=20, bg="brown", fg="white", command=submit)
bt.place(x=160, y=400)

#run
x.mainloop()
DATABASE
CONNECTIVITY
Before we start let us know bit about MySQL
MySQL is the most popular Open Source Relational SQL Database
Management System.

FEATURES

❖It is written in C and C++

❖MySQL is quicker than other databases so it can work well even with the
large data set.

❖MySQL supports many operating systems with many languages like PHP,
PERL, C, C++, JAVA, etc.

❖MySQL uses a standard form of the well-known SQL data language.

❖MySQL is used for many small and big businesses.

❖MySQL is an open-source database, so It is available free of cost


TO DOWNLOAD MYSQL

❑Visit MySQL official website


http://www.mysql.com/downloads/

❑Choose the version number for MySQL community server


which you want.
TO DOWNLOAD: MYSQL PYTHON CONNECTOR

MySQL Python Connector is used to access the MySQL database from Python,
you need a database driver. MySQL Connector/Python is a standardized
database driver provided by MySQL.

Step 1: Open Command window


Step2 : type pip install mysql-connector-python
Note: You can use pymysql also….

Visit www.pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan 185


Now, to check whether mysql-connector is
installed/working properly-
1. Open Python IDLE
2. Type import mysql

3. If no error occurs, it means mysql-connector is


working properly
Visit www.pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan 186
Steps to connect a python application
to our MySQL database

1. Import mysql.connector module


2. Create the connection object.
3. Create the cursor object
4. Execute the query
Creating the connection : connect () method
• Pass the database details like HostName, username,
and the database password in the method call. The
method returns the connection object.
Syntax :
ConnObject = mysql.connector.connect
(host = <hostname>, user = <username> , passwd = <password> )
Cursor in Python
Cursors are created by the connection.cursor() method :
they are bound to the connection for the entire lifetime
of the program and all the commands are executed in
the context of the database session wrapped by the
connection.
<cur_obj> = conn.cursor()

Note : We need cursor to execute our MySQL Queries


To display list of available databases in MySQL
With the help of
execute () one can
run any MySQL
query

Showing list of databases


We can also create our database through python

Creating
Database

See a
newdatabase
telephonedir is
created
output

Visit www.pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan 191


Now , lets create a table ‘customer’

Creating
table

Displaying
list of
tables

OUTPUT
USE OF DESC <TABLE> TO VIEW TABLE STRUCTURE

OUTPUT
Inserting data into table customer

Inserting
a record

Visit www.pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan 194


INSERTING RECORDS BY TAKING ITS INPUT BY USER

OUTPUT

With INSERT INTO statement, we can


mention the format specifier (%s) in
place of values.
In the same way, We can insert multiple records also

Inserting many records


by creating list of
tuples

Note that here we have to use executemany() instead of


execute()

Visit www.pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan 196


UPDATING DATA … HAVE A LOOK ON THE TABLE BELOW-
WE ARE GOING TO CHANGE THE NAME OF CUSTOMER
1003 TO ‘SUDHA’

Visit www.pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan 197


Code to update

Name of 1003
customer is
changed to
Sudha
DELETING RECORD: LETS DELETE THE
RECORD

Record with
cust_id 1006 is
deleted now
Cursor.rowcount
• It will tell display no. of records fetched after running
• You can Query.run this command after executing any query.
Displaying all records : using fetchall()

OUTPUT
Any of the following functions you can use as per
your need
• cursor.fetchall() fetches all the rows of a query result. It
returns all the rows as a list of tuples. An empty list is
returned if there is no record to fetch.
• cursor.fetchmany(size) returns the number of rows
specified by size argument. When called repeatedly
this method fetches the next set of rows of a query
result and returns a list of tuples. If no more rows are
available, it returns an empty list.
• cursor.fetchone() method returns a single record or
None if no more rows are available.
FOR ERROR HANDLING TWO MORE
MODULE WE NEED TO IMPORT, ARE:
•>>>from mysql.connector import Error
•>>>from mysql.connector import errorcode

MySQL connector Error object is used to show us an


error when we failed to connect Databases or if any
other database error occurred while working with
the database.

Error expecting code must be written in try………..except


block
Visit www.pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan 203
Error Handling code while displaying records

Visit www.pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan 204


OUTPUT OF PREVIOS PROGRAM

Visit www.pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan 205


See, I have written wrong database name which is not exists

OUTPUT

Visit www.pythonclassroomdiary.wordpress.com by Sangeeta M Chauhan 206


WEB SCRAPING
WEB SCRAPING
Web scraping is a technique to fetch data from websites. While surfing on the web,
many websites don’t allow the user to save data for personal use. One way is to
manually copy-paste the data, which both tedious and time-consuming. Web Scraping
is the automation of the data extraction process from websites. This event is done with
the help of web scraping software known as web scrapers. They automatically load
and extract data from the websites based on user requirements. These can be custom
built to work for one site or can be configured to work with any website.
There are mainly two ways to extract data from a website:
•Use the API of the website (if it exists). For example,
Facebook has the Facebook Graph API which allows
retrieval of data posted on Facebook.
•Access the HTML of the webpage and extract useful
information/data from it. This technique is called web
scraping or web harvesting or web data extraction.

There are three libraries which has been used such as:

1. requests
2. html5lib
3. bs4
1.Send an HTTP request to the URL of the webpage you want to access. The
server responds to the request by returning the HTML content of the
webpage. For this task, we will use a third-party HTTP library for python-
requests.

2.Once we have accessed the HTML content, we are left with the task of
parsing the data. Since most of the HTML data is nested, we cannot extract
data simply through string processing. One needs a parser which can create a
nested/tree structure of the HTML data. There are many HTML parser
libraries available but the most advanced one is html5lib.

3.Now, all we need to do is navigating and searching the parse tree that we
created, i.e. tree traversal. For this task, we will be using another third-party
python library, Beautiful Soap. It is a Python library for pulling data out of
HTML and XML files.
import requests
URL = "http://books.toscrape.com"
r = requests.get(URL)
print(r.content)

• First of all import the requests library.


• Then, specify the URL of the webpage you want to scrape.
• Send a HTTP request to the specified URL and save the
response from server in a response object called r.
• Now, as print r.content to get the raw HTML content of the
webpage. It is of ‘string’ type.
import requests
from bs4 import BeautifulSoup

u = "http://books.toscrape.com"
r = requests.get(u)

a = BeautifulSoup(r.content, 'html5lib')
print(a.prettify())

soup.prettify(), gives the visual representation of the parse tree created from the raw
HTML content.
import requests
from bs4 import BeautifulSoup

u = "http://books.toscrape.com"
r = requests.get(u)

a = BeautifulSoup(r.content, 'html5lib')

# If this line causes an error, run 'pip install html5lib' or install html5lib
print(a.prettify())
Find all the article titles (in this case, book titles)

# import requests
from bs4 import BeautifulSoup

# URL of the webpage to scrape


url = 'http://books.toscrape.com'

# Send a GET request to the URL


response = requests.get(url)

# Parse the HTML content of the page


soup = BeautifulSoup(response.content, 'html.parser')

# Find all the article titles (in this case, book titles)
titles = soup.find_all('h3')

# Print each title


for title in titles:
# Extract the title text from the anchor tag
book_title = title.find('a')['title']
print(book_title)

You might also like