dl lab-2
dl lab-2
PART A:
1. Comment with an eg on the use of local and global identifier name.(N/D22&23)
The scope of a variable refers to the places that we can see or access a variable. If we define a variable
on the top of the script or module, the variable is called global variable. The variables that are defined
inside a class or function is called local variable.
Eg:
def my_local():
a=10
print(“This is local variable”)
Eg:
a=10
def my_global():
print(“This is global variable”)
return temp
Composition:
Calling one function from another is called composition.
Eg:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
4. Define string immutability(A/M23)
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We can’t mutate the
string but can change what value of the variable to a new string
len(list2) → 8
len(list3) → 4
10. How to split strings and what function is used to perform operation? (A/M24)
split() – returns a list of words in string
text = "Hello, world! Welcome to Python."
words = text.split()
print(words)
# Output: ['Hello,', 'world!', 'Welcome', 'to', 'Python.']
11. Why are string immutable? (N/D22)
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We can’t mutate the
string but can change what value of the variable to a new string
12. Write for a loop that prints no from 0 to 57 using range function in python (N/D23)
Program:
for number in range(58):
print(number)
PART B:
1. Write python program for finding square root of numbers without using inbuilt function
and explain (N/D22)8M
Newton-Raphson method:
Steps:
Initial Guess: Start with an initial guess for the square root.
Iterative Improvement: Improve the guess iteratively using the formula:
new_guess=guess+nguess2\text{new\_guess} = \frac{\text{guess} + \frac{n}{\
text{guess}}}{2}
Convergence Check: Repeat the steps until the guess converges to a stable value (i.e.,
the change between iterations is very small)
Program:
def newtonsqrt(n):
root=n/2
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
OUTPUT: enter number to find Sqrt: 9 3.0
2. Write python program for linear and binary search and its implementation in
detail(N/D22).
Linear Search
Linear search is a simple search algorithm that checks each element of a list sequentially until the
desired element is found or the end of the list is reached. It's straightforward but not very efficient for
large datasets.
Implementation
# Example usage
numbers = [10, 23, 45, 70, 11, 15]
target = 70
result = linear_search(numbers, target)
if result != -1:
print(f'Element found at index {result}')
else:
print('Element not found')
Binary Search
Binary search is a more efficient algorithm that works on sorted lists. It repeatedly divides the search
interval in half and compares the target with the middle element.
Implementation
def binary_search(arr, target):
left, right = 0, len(arr) - 1
# Example usage
numbers = [10, 23, 45, 70, 11, 15]
numbers.sort() # Binary search requires a sorted array
target = 70
result = binary_search(numbers, target)
if result != -1:
print(f'Element found at index {result}')
else:
print('Element not found')
3. Explain string module (A/M23)
String modules:
A module is a file containing Python definitions, functions, statements.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the module.
Once we import a module, we can reference or use to any of its functions or variables in our code.
There is large number of standard modules also available in python.
Standard modules can be imported the same way as we import our user-defined modules.
Syntax:
import module_name
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567
import array 10
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
5. Write python program to perform search operation which sequentially checks each
element of list until a match is found or who the list is searched (A/M23)
PROGRAM
def linear_search(arr, target):
for index, element in enumerate(arr):
if element == target:
return index
return -1
# Example usage
numbers = [10, 23, 45, 70, 11, 15]
target = 70
result = linear_search(numbers, target)
if result != -1:
print(f'Element found at index {result}')
else:
print('Element not found')
• String functions are built-in methods in Python used to manipulate and process strings.
• These functions make it easier to work with string data by providing tools to perform various
operations.
• Here’s an overview of some common string functions and their types:
Common String Functions:
len()
o Description: Returns the length of the string.
o Usage: len("hello") returns 5.
str()
o Description: Converts the specified value into a string.
o Usage: str(123) returns "123".
lower()
split()
Description: Splits the string into a list of substrings based on a delimiter.
Usage: "hello world".split(" ") returns ["hello", "world"].
join()
Description: Joins the elements of a list into a single string, separated by a specified delimiter.
Usage: " ".join(["hello", "world"]) returns "hello world".
count()
Description: Returns the number of occurrences of a specified substring.
Usage: "hello".count("l") returns 2.
isalpha()
Description: Checks if all characters in the string are alphabetic.
Usage: "hello".isalpha() returns True.
isdigit()
Description: Checks if all characters in the string are digits.
Usage: "123".isdigit() returns True.
islower()
Description: Checks if all characters in the string are lowercase.
Usage: "hello".islower() returns True.
isupper()
Description: Checks if all characters in the string are uppercase.
Usage: "HELLO".isupper() returns True.
7. Explain the difference between break and continue in python with eg (A/M22)
1.BREAK
Break statements can alter the flow of a loop.
It terminates the current
loop and executes the remaining statement outside the loop.
If the loop has else statement, that will also gets terminated and come out of the loop completely.
Syntax:
Break
Flowchart:
example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax: Continue
Flowchart
Example:
for i in "welcome": if(i=="c"):
continue print(i)
Output
we l ome
Conditional Statements
Conditional if
Alternative if… else
Chained if…elif…else
Nested if….else
Conditional (if):
conditional (if) is used to test a condition, if the condition is true the statements inside if will be executed.
syntax:
Flowchart
Example
If the condition1 is False, it checks the condition2 of the elif block. If all the conditions are False, then the
else part is executed.
Among the several if...elif...else part, only one part is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
o The way to express a computation like that is a chained conditional.
lOMoARcPSD|22814775
Syntax:
Flowchart
Example
Nested conditionals
One conditional can also be nested within another. Any number of condition can
be nested inside one another. In this, if the condition is true it checks another if
condition1. If both the conditions are true statement1 get executed otherwise
statement2 get execute. if the condition is false statement3 gets executed
Syntax:
Flowchart
Example
a = 10
b = 20
c = 30
if a >= b:
if a >= c:
greatest = a
else:
greatest = c
lOMoARcPSD|22814775
else:
if b >= c:
greatest = b
else:
greatest = c
9. Write python program for finding sum of 1st n natural odd no and print
the result using function (J22)
def sum_of_odd_numbers(n):
# Initialize the sum to 0
total_sum = 0
return total_sum
# Example usage
n = 5 # Change this value to the desired number of terms
result = sum_of_odd_numbers(n)
print(f'The sum of the first {n} natural odd numbers is {result}')
Output: The sum of the first 5 natural odd numbers is 25
Call by Value
Definition: When a function is called, a copy of the argument's value is passed to the
function.
Implication: Changes made to the parameter inside the function do not affect the
original argument.
Call by Reference
Definition: When a function is called, a reference to the actual argument (not a copy)
is passed to the function.
Implication: Changes made to the parameter inside the function affect the original
argument.
Mutable Objects (e.g., lists, dictionaries): If you pass a mutable object, the function
can modify the original object because the reference to the object is passed.
lOMoARcPSD|22814775
Immutable Objects (e.g., integers, strings, tuples): If you pass an immutable object,
the function cannot modify the original object itself, but it can reassign the reference
to a new object.
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
With return type
Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enterb")) return
c=a+b c
return c a=int(input("enter a"))
c=add() b=int(input("enter b"))
c=add(a,b)
print(c)
print(c)
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
lOMoARcPSD|22814775
# Example usage
input_string = input("Enter a string: ")
if is_palindrome(input_string):
print(f'"{input_string}" is a palindrome.')
else:
print(f'"{input_string}" is not a palindrome.')
Output:
Enter a string: Racecar
"Racecar" is a palindrome.