0% found this document useful (0 votes)
7 views

python file

The document contains a series of Python programming experiments demonstrating various concepts such as control structures, data types (lists, dictionaries, tuples), functions with scoping, exception handling, classes and objects, searching algorithms, sorting algorithms, conditional statements, string operations, and variable scope. Each experiment includes code examples and expected outputs to illustrate the concepts. The document serves as a comprehensive guide for beginners to understand fundamental Python programming techniques.

Uploaded by

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

python file

The document contains a series of Python programming experiments demonstrating various concepts such as control structures, data types (lists, dictionaries, tuples), functions with scoping, exception handling, classes and objects, searching algorithms, sorting algorithms, conditional statements, string operations, and variable scope. Each experiment includes code examples and expected outputs to illustrate the concepts. The document serves as a comprehensive guide for beginners to understand fundamental Python programming techniques.

Uploaded by

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

Experiment – 01

Develop program to understand the control structure of python.

num = 7

if num > 0:

print("Positive number")

else:

print("Non-positive number")

# For loop

print("For loop from 1 to 5:")

for i in range(1, 6):

print(i)

# While loop with break and continue

print("While loop demonstration:")

i=0

while i < 5:

i += 1

if i == 3:

continue # skip printing 3

if i == 5:

break # exit loop when i is 5


print(i)

output:
Experiment – 02

Develop program to implement list, dictionary & tuple.

# List

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

print("List example:", fruits)

print("Second fruit:", fruits[1])

# Tuple

colors = ("red", "green", "blue")

print("Tuple example:", colors)

print("First color:", colors[0])

# Dictionary

student = {"name": "Alice", "age": 20, "grade": "A"}

print("Dictionary example:", student)

print("Student name:", student["name"])

output:
Experiment – 03

Develop program to implement function with stress on scoping.

x = 10 # Global variable

def outer_function():

x = 20 # Enclosing (nonlocal) variable

def inner_function():

nonlocal x

x = 30 # Modifies the enclosing variable

print("Inside inner_function, x =", x)

inner_function()

print("Inside outer_function after inner_function, x =", x)

def modify_global():

global x

x = 50 # Modifies the global variable

print("Inside modify_global, x =", x)

print("Initial global x =", x)

outer_function()
print("Global x after outer_function =", x)

modify_global()

print("Global x after modify_global =", x)

output:
Experiment – 04

Develop a program to implement exception handling.

try:

a = int(input("Enter numerator: "))

b = int(input("Enter denominator: "))

result = a / b

print("Result:", result)

except ZeroDivisionError:

print("You can't divide by zero!")

except ValueError:

print("Please enter valid numbers!")

output:
Experiment – 05

Develop program to implement classes and objects.

# Define a class

class Student:

def __init__(self, name, grade):

self.name = name

self.grade = grade

def display(self):

print("Student Name:", self.name)

print("Grade:", self.grade)

# Create an object of the class

s1 = Student("Alice", "A")

# Call method using the object

s1.display()

output:
Experiment – 06

Develop program to implement linear search & binary search.

# Linear Search

def linear_search(arr, target):

for i in range(len(arr)):

if arr[i] == target:

return i

return -1

# Binary Search (works only on sorted lists)

def binary_search(arr, target):

low = 0

high = len(arr) - 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

low = mid + 1

else:

high = mid - 1
return -1

# Sample list and target

numbers = [3, 6, 9, 12, 15]

target = 12

# Perform searches

print("List:", numbers)

print("Target:", target)

# Linear Search Result

result1 = linear_search(numbers, target)

print("Linear Search: Found at index" if result1 != -1 else "Linear Search: Not


found", result1)

# Binary Search Result

result2 = binary_search(numbers, target)

print("Binary Search: Found at index" if result2 != -1 else "Binary Search: Not


found", result2)
output:
Experiment – 07

Develop program to implement insertion sort , selection sort, bubble sort, &
merge sort.

# Insertion Sort

def insertion_sort(arr):

for i in range(1, len(arr)):

key = arr[i]

j=i-1

while j >= 0 and arr[j] > key:

arr[j + 1] = arr[j]

j -= 1

arr[j + 1] = key

# Selection Sort

def selection_sort(arr):

for i in range(len(arr)):

min_idx = i

for j in range(i + 1, len(arr)):

if arr[j] < arr[min_idx]:

min_idx = j

arr[i], arr[min_idx] = arr[min_idx], arr[i]

# Bubble Sort
def bubble_sort(arr):

n = len(arr)

for i in range(n):

for j in range(0, n - i - 1):

if arr[j] > arr[j + 1]:

arr[j], arr[j + 1] = arr[j + 1], arr[j]

# Merge Sort

def merge_sort(arr):

if len(arr) > 1:

mid = len(arr) // 2

left_half = arr[:mid]

right_half = arr[mid:]

merge_sort(left_half)

merge_sort(right_half)

i=j=k=0

while i < len(left_half) and j < len(right_half):

if left_half[i] < right_half[j]:

arr[k] = left_half[i]

i += 1

else:
arr[k] = right_half[j]

j += 1

k += 1

while i < len(left_half):

arr[k] = left_half[i]

i += 1

k += 1

while j < len(right_half):

arr[k] = right_half[j]

j += 1

k += 1

# Sample List

arr = [64, 25, 12, 22, 11]

print("Original List:", arr)

# Insertion Sort

insertion_sorted = arr.copy()

insertion_sort(insertion_sorted)

print("Insertion Sort:", insertion_sorted)


# Selection Sort

selection_sorted = arr.copy()

selection_sort(selection_sorted)

print("Selection Sort:", selection_sorted)

# Bubble Sort

bubble_sorted = arr.copy()

bubble_sort(bubble_sorted)

print("Bubble Sort:", bubble_sorted)

# Merge Sort

merge_sorted = arr.copy()

merge_sort(merge_sorted)

print("Merge Sort:", merge_sorted)

output:
Experiment – 08

Demonstrate the following conditional statement in python with suitable


example.

(i) If – statement
# Example to check if a number is positive
number = 7

if number > 0:
print("The number is positive.")

output:

(ii) If else – statement


# Example to check if a number is positive or negative
number = -5

if number > 0:
print("The number is positive.")
else:
print("The number is negative.")

output:

(iii) If-elif –else statement


# Example to check if a number is positive, negative, or zero
number = 0

if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")

output:
Experiment – 09
Demonstrate the following function which operates on string in
python with suitable example.
(i) Len
# Example string
text = "Hello, Python!"

# Using len() function to get the length of the string


length = len(text)

# Display the length of the string


print("The length of the string is:", length)

output:

(ii) Strip
# Example string with leading and trailing spaces
text = " Hello, Python! "

# Using strip() to remove leading and trailing spaces


stripped_text = text.strip()

# Display the stripped string


print("Original string:", repr(text))
print("Stripped string:", repr(stripped_text))

output:
(iii) Rstrip
# Example string with trailing spaces
text = "Hello, Python! "

# Using rstrip() to remove trailing spaces


stripped_text = text.rstrip()

# Display the original and stripped strings


print("Original string:", repr(text))
print("Right stripped string:", repr(stripped_text))

output:

(iv) Lstrip
# Example string with leading spaces
text = " Hello, Python!"

# Using lstrip() to remove leading spaces


stripped_text = text.lstrip()

# Display the original and stripped strings


print("Original string:", repr(text))
print("Left stripped string:", repr(stripped_text))

output:
(v) Find
# Example string
text = "Hello, Python! Welcome to Python programming."

# Using find() to search for a substring


position = text.find("Python")

# Display the result


print("Substring 'Python' found at index:", position)

# Searching for a substring that is not in the string


position_not_found = text.find("Java")
print("Substring 'Java' found at index:", position_not_found)

output:

(vi) Rfind
# Example string
text = "Hello, Python! Welcome to Python programming."

# Using rfind() to search for a substring from the end


position = text.rfind("Python")

# Display the result


print("Substring 'Python' found at index:", position)

# Searching for a substring that is not in the string


position_not_found = text.rfind("Java")
print("Substring 'Java' found at index:", position_not_found)
output:

(vii) Index
# Example string
text = "Hello, Python! Welcome to Python programming."

# Using index() to search for the first occurrence of a substring


position = text.index("Python")

# Display the result


print("Substring 'Python' found at index:", position)

# Trying to search for a substring that doesn't exist (this will raise
an error)
try:
position_not_found = text.index("Java")
print("Substring 'Java' found at index:", position_not_found)
except ValueError:
print("Substring 'Java' not found in the string.")

output:

(viii) Rindex
# Example string
text = "Hello, Python! Welcome to Python programming."

# Using rindex() to search for the last occurrence of a substring


position = text.rindex("Python")
# Display the result
print("Substring 'Python' found at index:", position)

# Trying to search for a substring that doesn't exist (this will raise
an error)
try:
position_not_found = text.rindex("Java")
print("Substring 'Java' found at index:", position_not_found)
except ValueError:
print("Substring 'Java' not found in the string.")

output:
Experiment – 10
Write a python program to demonstrate local and global
variables.

# Global variable
x = 10

def my_function():
# Local variable
x=5
print("Inside function, local x =", x)

# Call the function


my_function()

# Print the global variable


print("Outside function, global x =", x)

output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy