[go: up one dir, main page]

0% found this document useful (0 votes)
29 views21 pages

Python Unit 3 Complete Notes

The document provides an overview of Boolean data types, operators in Python, control flow statements, iteration, functions, and strings. It details various types of operators such as arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators, along with examples. Additionally, it explains control flow mechanisms like conditional statements and loops, and introduces concepts of function parameters, scope, recursion, and string operations.

Uploaded by

Deepika V
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)
29 views21 pages

Python Unit 3 Complete Notes

The document provides an overview of Boolean data types, operators in Python, control flow statements, iteration, functions, and strings. It details various types of operators such as arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators, along with examples. Additionally, it explains control flow mechanisms like conditional statements and loops, and introduces concepts of function parameters, scope, recursion, and string operations.

Uploaded by

Deepika V
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/ 21

Boolean:

Boolean data types have two values. They are 0 and 1.


0 represents False 1 represents True
True and False are keywords.
>>> 3==5 >>> 6==6
False True

*** *** *** *** *** ***


OPERATORS IN PYTHON
Operators are special symbols that perform operations on variables and values. In Python,
operators can be classified into several types:
1. Arithmetic Operators
o These operators are used to perform mathematical operations.
o Examples:
 Addition (+): Adds two operands.

result = 5 + 3 # result is 8

 Multiplication (*): Multiplies two operands.

result = 6 * 7 # result is 42

 Division (/): Divides the first operand by the second and returns a float.

result = 15 / 2 # result is 7.5

 Floor Division (//): Divides and returns the largest integer.

result = 15 // 2 # result is 7

 Modulus (%): Returns the remainder of the division.

result = 10 % 3 # result is 1

 Exponentiation (**): Raises the first operand to the power of the


second.

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.

result = (5 == 5) # result is True

 Not equal to (!=): Checks if two operands are not equal.

result = (5 != 3) # result is True

 Greater than (>): Checks if the left operand is greater than the right.

result = (7 > 5) # result is True

 Less than or equal to (<=): Checks if the left operand is less than or
equal to the right.

result = (3 <= 5) # result is True

3. Logical Operators
o These operators are used to combine conditional statements.
o Examples:
 AND (and): Returns True if both operands are true.

result = (5 > 3 and 8 > 6) # result is True

 OR (or): Returns True if at least one of the operands is true.

result = (5 < 3 or 8 > 6) # result is True

 NOT (not): Reverses the truth value of the operand.

result = not(5 > 3) # result is False

4. Bitwise Operators
o These operators perform operations on binary numbers.
o Examples:
 AND (&): Performs a bitwise AND operation.

result = 5 & 3 # result is 1 (binary 101 & 011 = 001)

 OR (|): Performs a bitwise OR operation.

result = 5 | 3 # result is 7 (binary 101 | 011 = 111)

 XOR (^): Performs a bitwise XOR operation.

result = 5 ^ 3 # result is 6 (binary 101 ^ 011 = 110)


 Left Shift (<<): Shifts bits to the left, filling with zeros.

result = 5 << 1 # (0101) result is 10 (binary 1010)

 Right Shift (>>): Shifts bits to the right.

result = 5 >> 1 # (0101) result is 2 (binary 0010)

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

 Add and Assign (+=): Adds and assigns the value.

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

result = (a is b) # result is True

 Is Not (is not): Returns True if both variables do not refer to the
sameobject.

c = [1, 2, 3]

result = (a is not c) # result is True

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.

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

result = ("banana" in fruits) # result is True

 Not In (not in): Returns True if the value is not found in the sequence.

result = ("orange" not in fruits) # result is True

*** *** *** *** *** ***


Control Flow:
Control flow refers to the order in which individual statements, instructions, or operations are
executed in a program, determining the flow of control based on conditions, loops, or
functions.
1. Unconditional Control Flow
An unconditional statement is a declaration that is always true, regardless of any conditions
or circumstances. Ex: "The sun rises in the east." “2+2=4”
2. Conditional Control Flow
Conditional control flow statements (e.g., if-else, switch) evaluate a condition or expression,
and based on its truth value, execute specific blocks of code or alternate paths.

There are various types of Conditional/Branching Statements:


i) Conditional if statements (one way conditional statements)
The if statement allows you to execute a block of code if a certain condition is true. Here's an
example of how to use an if statement to check if a number is positive:

num = 5
if (num > 0):
print("The number is positive.")
Output: The number is positive.

ii) Alternative if else statements (two way conditional statements)


The else statement allows you to execute a different block of code if the if condition is False.
Example of how to use an if-else statement to check if a number is positive or negative:

num = -5
if (num > 0):
print("The number is positive.")
else:
print("The number is negative.")
Output: The number is negative.

iii) Chained if-elif-else statements (many wa conditional statements)


The elif statement allows you to check multiple conditions in sequence, and execute different
code blocks depending on which condition is true. In this example, we use an if-elif-
else statement to assign a letter grade based on a numerical score.

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

iii) Nested if-else statements


When one if condition is present inside another if then it is called nested if conditions.
x=5
if x > 0:
if x % 2 == 0:
print("x is greater than 0 and even")
else:
print("x is greater than 0 and odd")
else:
print("x is less than or equal 0")

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.

*** *** *** *** *** ***


Iteration / Looping Statements
STATE
Transition from one process to another process under specified condition with in a time is called
state.
WHILE
While loop statement in Python is used to repeatedly executes set of statement as long as a
given condition is true.
In while loop, test expression is checked first. The body of the loop is entered only if the test
expression is True. After one iteration, the test expression is checked again. This process
continues until the test expression evaluates to False.
Example:
<statement>
n=int(input(‘Enter the value of n:’))
a=0
b=1
i=0
print(‘Fibonacci Sequence is..’)
while i<n:
print(a)
c=a+b
a,b=b,c
i=i+1
# input=5, Output=0 1 1 2 3

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.

def student( name, roll ):


print(name,roll)
student(“Guru”,98)
Output:Guru, 98

ii) Keyword parameter:


 Both the function definition and function call should have same number of arguments.
 Position/order should not be followed.
 Mapping(assigning value to variable)can be done with the help of keyword/

def student(name,roll,mark): def greet(name, msg="Hello"):


print(name,roll,mark) print(name, msg)
greet(msg="Good morning",
student(90,102,"Bala")
name="Yoga")
Output: 90 102 Bala Output: Yoga, Good morning

iii) Default parameter:


A default argument represent the function arguments that assumes a default value if a value is
not provided in the function call for that argument.
def student( name, age=17):
print (name, age)
student( “kumar”):
Output:
Kumar 17

iv) Variable length parameter

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)

Output: Bala (95,90,83,91,89)


Local and global scope
The scope of a variable refers to the places where you can see or access a variable.
Local Variable:
A local variable is defined within a specific function or block. It works only inside the
function.
Global Scope:
A variable with global scope can be used anywhere in the program. It can be created by
defining a variable outside the function.

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

ESCAPE SEQUENCES IN STRING


In Python, an escape sequence is a sequence of characters that starts with a backslash ‘\ ‘ and is used to
represent special characters, such as newlines (\n), tabs (\t), or quotes ("). Escape sequences allow you
to include these special characters in strings without causing syntax errors or confusion.

*** *** *** *** *** *** ***


LIST AS AN ARRAY:
ARRAY: An array is a collection of similar elements. Elements in the array can be accessed by index. The
index starts with 0. An array can be handled in python by a module named array. To create an array have to
import an array module into the program.
Methods in array : A=[ 2,3,4,5 ]

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

-2 5 (-2)5 = -2*-2*-2*-2*-2 = -32


2 1.5 21.5 = 23/2 = (23)1/2= √23 = √8 = 2.828 # if the exponent is float, calculation is done this way.
Example-2: The double asterisk, ** operator
base = 3
exponent = 4
print ("Exponential: ", base ** exponent)
Input: 34 Output: Exponential Value is: 81

Example-3: Using the Power pow() method


base = 3
exponent = 2
print ("Exponential: ", pow(base, exponent))
Input: pow(3,2) Output: Exponential: 9
2. Square Root using Newtons Method:

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.

- Start with an initial guess (n/2)

- Update the guess using the formula (root + n/root)/2 approaches the actual square root with
each iteration.

- Repeat the update step until convergence (at least, 10 iterations)

def newtonsqrt(n): How machine perform each iteration.


root=n/2 4.5
for i in range(10): 3.25
root=(root+n/root)/2 3.0096153846153846
print('final',root) 3.000015360039322
n=int(input("enter number to find Sqrt:")) 3.0000000000393214
newtonsqrt(n)
3.0
Input : 9
3.0
Output: 3
3.0
math.sqrt(n): This function calculates the square root of n using Python's internal
implementation, which is optimized and precise.
import math
def newtonsqrt(n):
print("math.sqrt() result:", math.sqrt(n))
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
Input : 36
Output: 6
3. GCD (GREATEST COMMON DIVISOR)
The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both
without leaving a remainder.

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

Example For an array = [1, 2, 3, 4, 5]:

Here is the algorithm for the program to sum an array of numbers:

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.

3. Loop: Iterate through each number num in the array.

- Add num to total.

4. Output: Print or return the final value of total.

numbers = [1, 2, 3, 4, 5]

total = 0

for num in numbers:

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.

*** *** *** *** *** ***


BINARY SEARCH
Binary searchingvis a searching algorithm used to find the position of a target value within a
sorted array. Binary search works by repeatedly dividing the search interval in half. If the target
value is less than the middle element, the search continues in the left half; if the target value is
greater, the search continues in the right half.
Here are the steps to solve the problem:
1. Initialize the boundaries: left starts at 0 (beginning of the list) and right starts at len(arr)
- 1 (end of the list).
2. Loop until left is greater than right:
o Calculate mid, the midpoint of the current search range.
o If arr[mid] == target, we found the target and return the index mid.
o If arr[mid] < target, update left to mid + 1 to search in the right half.
o If arr[mid] > target, update right to mid - 1 to search in the left half.
3. Return -1 if the target is not found.

PROGRAM

def binary_search(arr, target):


left, right = 0, len(arr) - 1 # Initialize the search boundaries
while left <= right:
mid = (left + right) // 2 # Find the middle index
if arr[mid] == target:
return mid # Target found, return the index
elif arr[mid] < target:
left = mid + 1 # Move to the right half
else:
right = mid - 1 # Move to the left half
return -1 # Target not found
arr = [1, 3, 5, 7, 9, 11]
target = 7
result = binary_search(arr, target)
if result >= 0 :
print("Index of target:", result) # Expected output: Index of target: 3
else:
print("Target Not Found")

Input=7 Output=Index of target: 3


Given arr = [1, 3, 5, 7, 9, 11] and target = 7:

1. Initial: left = 0, right = 5.


2. First Iteration:
o mid = (0 + 5) // 2 = 2, arr[2] = 5.
o Since 5 < 7, update left = 3.
3. Second Iteration:
o mid = (3 + 5) // 2 = 4, arr[4] = 9.
o Since 9 > 7, update right = 3.
4. Third Iteration:
o mid = (3 + 3) // 2 = 3, arr[3] = 7.
o arr[3] matches target, so return 3.
The output is 3, which is the index of 7 in the array.

You might also like