Python Unit 3 Complete Notes
Python Unit 3 Complete Notes
result = 5 + 3 # result is 8
result = 6 * 7 # result is 42
Division (/): Divides the first operand by the second and returns a float.
result = 15 // 2 # result is 7
result = 10 % 3 # result is 1
result = 2 ** 3 # result is 8
2. Comparison Operators
o These operators compare two values and return a Boolean value (True or False).
o Examples:
Equal to (==): Checks if two operands are equal.
Greater than (>): Checks if the left operand is greater than the right.
Less than or equal to (<=): Checks if the left operand is less than or
equal to the right.
3. Logical Operators
o These operators are used to combine conditional statements.
o Examples:
AND (and): Returns True if both operands are true.
4. Bitwise Operators
o These operators perform operations on binary numbers.
o Examples:
AND (&): Performs a bitwise AND operation.
5. Assignment Operators
o These operators are used to assign values to variables.
o Examples:
Simple Assignment (=): Assigns the right operand to the left operand.
x = 10 # x is assigned 10
x += 5 # x becomes 15
6. Identity Operators
o These operators are used to check if two variables point to the same object
in memory.
o Examples:
Is (is): Returns True if both variables refer to the same object.
a = [1, 2, 3]
b=a
Is Not (is not): Returns True if both variables do not refer to the
sameobject.
c = [1, 2, 3]
7. Membership Operators
o These operators are used to test if a value is a member of a sequence
(like a list, string, or tuple).
o Examples:
In (in): Returns True if the value is found in the sequence.
Not In (not in): Returns True if the value is not found in the sequence.
num = 5
if (num > 0):
print("The number is positive.")
Output: The number is positive.
num = -5
if (num > 0):
print("The number is positive.")
else:
print("The number is negative.")
Output: The number is negative.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Your grade is:", grade)
Output: Your grade is: B
In this example, we have two if statements nested inside each other. The first if statement
checks if x is greater than 0. If it is, then the second if statement checks if x is even or odd. If
x is not greater than 0, then the else statement print x is less than or equal 0.
FOR
for in range:
We can generate a sequence of numbers using the range() function. range(10) will
generatenumbers from 0 to 9 (10 numbers).
In range, a function has to define the start, stop and step size as a range(start, stop, step
size). default values if not provided.(0, n-1, 1)
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over a
sequenceis called traversal. Loop continues until we reach the last element in the sequence.
Print nos divisible by 5 not by 10
n=eval(input("enter a number:"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)
Input:30 Output:5,15,25
BREAK
Break statements can alter the flow of a loop. It terminates the current Loop and executes the
remaining statement outside the loop.
for i in "AMARAN":
if(i=="R"):
break
print(i)
Outout: AMA
CONTINUE
It terminates the current iteration and transfers the control to the next iteration in the loop.
for i in "AMARAN":
if(i=="R"):
continue
print(i)
Outout: AMAAN
PASS
It is used when a statement is required syntactically, It is a null statement, nothing
happens when it is executed. DO NOTHING.
for i in "AMARAN":
if(i=="R"):
pass
print(i)
Outout: AMARAN
FRUITFUL FUNCTION
Fruitful function (Return values)
A function that returns a value is called a fruitful function. return is used to exit a function
and go back to the place where it was called. It can also return a value to the caller.
def add(a, b):
return a + b
result = add(2, 3)
print(result) # Output: 5
In this example, the add function returns the sum of a and b.
Void function (Return None)
def print_hello():
print("Hello!")
print_hello() # Output: Hello!
In this example, the print_hello function does not return any value. It simply prints "Hello!" and exits.
Parameters
i) Required/ Positional Parameter:
Both the function definition and function call should have same number of
arguments.Position/order should be followed.
Sometimes, we do not know in advance the number of arguments that will be passed
into afunction. Python allows us to handle this kind of situation through function calls with
several arguments. In the function definition, we use an asterisk (*) before the parameter
name to denote this is thevariable length of the parameter.
def student( name,*mark):
print(name,mark)
student (“Bala”,95,90,83,91,89)
x = 10 # global variable
def my_function():
x = 20 # local variable
print("Inside function:", x)
my_function()
print("Outside function:", x)
Output: Inside function: 20 , Outside function: 10
In this example:
- x is a global variable with a value of 10.
- Inside my_function(), x is a local variable with a value of 20.
- When we print x inside the function, it prints the local value of 20.
- When we print x outside the function, it prints the global value of 10.
Note that if we want to modify the global variable x inside the function, we need to use the
global keyword:
x = 10
def my_function():
global x
x = 20
print("Inside function:", x)
my_function()
print("Outside function:", x)
Output:Inside function: 20 , Outside function: 20
In this case, both prints will output 20, because we modified the global variable x inside the
function.
Function composition
Function composition is the way of combining two or more functions in such a way that the
output of one function becomes the input of the second function and so on.
def add(x):
return x + 2
def multiply(x):
return x * 2
print("Add 2+5 and multipl the result with 2: ",multiply(add(5)))
Recursion
A function calling itself till it reaches the base value - stop point of function call.
Here is a simple example of a recursive function in Python:
def count_down(n):
if n == 0:
print("Blast off!")
else:
print(n)
count_down(n-1)
count_down(10)
Output:
5
4
3
2
1
Blast off!
In this example, the count_down function calls itself with the argument n-1 until it reaches 0,
at which point it prints "Blast off!".
Here's how it works:
- count_down(5) is called, which prints 5 and then calls count_down(4)
- count_down(4) is called, which prints 4 and then calls count_down(3)
- count_down(3) is called, which prints 3 and then calls count_down(2)
- count_down(2) is called, which prints 2 and then calls count_down(1)
- count_down(1) is called, which prints 1 and then calls count_down(0)
- count_down(0) is called, which prints "Blast off!" and ends the recursion
This is a simple example of a recursive function that counts down from a given number to 0.
STRINGS
A string is defined as a sequence of characters represented in quotation marks (either singlequotes ( ‘
) or double quotes ( “ ).
An individual character in a string is accessed using an index. An index starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be changed after it is created.
OPERATIONS ON STRING:
IMMUTABILITY
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
STRING FUNCTIONS AND METHODS
Syntax to access the method
Stringname.method()
a=”happy birthday”
here, a is the string name.
STRING MODULE
A module is a file containing Python definitions, functions, and statements.
The standard library of Python is extended as modules.
Once we import a module, we can reference or use to any of its functions or variables in our code.
Syntax: import module_name
import string Output
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~
Happy Birthday
print(string.capwords("happ
y birthday"))
print(string.hexdigits) 0123456789abcdefABCDEF
print(string.octdigits) 01234567
Example: program to convert list into array and find sum of array elements
import array
sum=0
listA=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(listA)
for i in a:
sum=sum+i
print(sum)
Output: 35
Illustrative Program
1. Calculating the exponential value in Python
The exponent value is calculated by multiplying the base number by the number of times
specified by the exponent, accommodating positive, negative, and floating-point values.
Applications of exponentiation
Data analysis, Mathematical calculations:
Machine learning and AI: Exponentiation is necessary for tasks such as activation
functions of neural networks (e.g., exponential linear unit (ELU)) or in image recognition
for normalization and feature scaling, which are crucial for training effective models.
Example-1 math.exp() method allows users to calculate the exponential value with the base set
to ‘e’. e is a Mathematical constant known as Euler’s number, with a value approximately equal
to 2.71828. The function takes the exponent value as the input.
import math
exponent = 1
print ("Exponential Value is: ", math.exp(exponent))
Input: e1 = (2.71828)1 Output: 2.71828
Input: e2 = (2.71828)2 Output: 7.38905
This is a Python implementation of the Newton method for finding the square root of a number.
This method is iterative and refines an initial guess until it approaches the actual square root.
- Update the guess using the formula (root + n/root)/2 approaches the actual square root with
each iteration.
Algorithm
1. Start.
2. Take two numbers a and b.
3. While b is not zero:
o Set temp = b.
o Set b = a % b.
o Set a = temp.
4. The GCD is now stored in a.
5. End.
PYTHON PROGRAM
def gcd(a, b):
while b != 0:
a, b = b, a % b
print(a,b)
return a
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(gcd(num1, num2))
Example:
The program defines a function gcd(a, b) that calculates the GCD of two numbers a and b using
the Euclidean algorithm. The algorithm works by repeatedly replacing a and b with b and the
remainder of a divided by b, respectively, until b becomes 0. At that point, a is the GCD of the
original a and b.
a b a%b a b a%b
12 15 12 % 15 (12) 98 56 98 % 56 (42)
15 12 15 % 12 (3) 56 42 56 % 42 (14)
12 3 12 % 3 (0) 42 14 42 % 14 (0)
3 0 14 0
Since b is now 0, the algorithm terminates, and the GCD is a = 3.
The program will print 3 as the output, which is the GCD of 12 and 15.
4. SUM OF AN ARRAY
To find the sum of all elements in an array, we iterate through each element and add it to an
accumulator variable sum.
Algorithm
1. Start.
2. Initialize an array arr with n elements.
3. Set sum = 0.
4. For each element arr[i] in the array, add arr[i] to sum.
5. End with sum containing the total sum of elements in arr.
Python Program
def sum_array(arr):
return sum(arr)
arr = [1, 2, 3, 4, 5]
print("Sum of array elements =", sum_array(arr))
# Output: 15
1. Input: Get the array of numbers from the user or a predefined source.
2. Initialize: Set a variable total to 0. This will store the sum of the numbers.
numbers = [1, 2, 3, 4, 5]
total = 0
total += num
print(total) # Output: 15
LINEAR SEARCH
Linear Search is a program that searches for a user-input element in a given list of integers. If the
element is found, print the index at which it is located (with indexing starting at 1). If the element
is not found, print a message indicating that it is not present in the list."
Here are the steps to solve the problem:
1. Take a list of integers as input.
2. Ask the user to enter an integer to search for in the list.
3. Search for the user-input integer in the list.
4. If the integer is found, print the index at which it is located (with indexing starting at 1).
5. If the integer is not found, print a message indicating that it is not present in the list.
PROGRAM
a=[20,30,40,50,60,70,89]
print(a)
search=int(input("enter a element to search:"))
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")
1. a=[20,30,40,50,60,70,89]: Defines a list a with 7 elements.
2. print(a): Prints the entire list a.
3. search=int(input("enter a element to search:")): Prompts the user to enter an integer to search
for in the list.
4. for i in range(0,len(a),1): Loops through the list a using a for loop, starting from index 0, with
a step size of 1.
5. if(search==a[i]): Checks if the current element a[i] is equal to the user-input search element.
6. print("element found at",i+1): If the element is found, prints a success message along with the
index i+1 (because indices start at 0).
7. break: Exits the loop if the element is found.
8. else: print("not found"): If the loop completes without finding the element, prints a failure
message.
For example, if the input list is [20, 30, 40, 50, 60, 70, 89] and the user inputs 50, the program
should output element found at 5. If the user inputs 90, the program should output not found.
PROGRAM