Python
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 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
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
PYTHON JAVA C
PYTHON JAVA C
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:
PRINTING VARIABLES:
• x = 42
• print(x) # Output: 42
VARIABLE REASSIGNMENT:
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
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!”
Example:-
str1 = "Hello"
print(str1[0]) # Output: ‘H’
print(str1[-1]) # Output: ‘o’
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
• 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’
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:
name = "Alice"
age = 30
sentence = "Name: {0}, Age: {1}".format(name, age)
print(sentence)
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.
Example
● Mutable: You can modify, add, or remove items after the list is created.
● 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”
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":
print(thislist[-4:-1])
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]
48
TUPLE
TUPLE
Tuples are just like lists except that they are immutable. i.e. we cannot modify
tuples.
For example:
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”
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])
Python has two built-in methods that you can use on tuples.
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).
Dictionaries are written with curly brackets, and have keys and values:
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)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Clear() Method:
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.
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"}
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)
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"}
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}
• 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
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
/= a/=10 a = a/ 10
%= a%=10 a = a % 10
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'
base for converting from other numbering systems to # Converting from octal to decimal
decimal. decimal_from_octal = int('52', 8) # 42
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.
• 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
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
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
• 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")
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)
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:
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)
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
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
to bind the data and the functions that work on that together as a single unit so that no
class ClassName:
# Statement-1
. . .
# Statement-N
Example: Creating an empty Class in Python
class Cat:
pass
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 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.
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.
# default constructor
def __init__(self):
self.name = “abc"
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:
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.
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.
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 ).
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 all of the lines from the file and return them as a list.
lines = f.readlines()
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):
# 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”)
For Example:
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
else:
print(content)
finally:
print("Execution finished.")
Syntax:
raise ExceptionType("Error message")
Example:
Raising a built-in Exception:
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
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.
For Example:
#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
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’)
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)
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
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()
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:
v,a = ser_sock.accept()
print("Client Connected")
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:
a. import tkinter
b. create main window
c. add widgets
d. run the main window with mainloop
# Geometry configuration:
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="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
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}")
#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
❖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 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.
Creating
Database
See a
newdatabase
telephonedir is
created
output
Creating
table
Displaying
list of
tables
OUTPUT
USE OF DESC <TABLE> TO VIEW TABLE STRUCTURE
OUTPUT
Inserting data into table customer
Inserting
a record
OUTPUT
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
OUTPUT
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)
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
# Find all the article titles (in this case, book titles)
titles = soup.find_all('h3')