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

Python Manual-3sem

python data on loops

Uploaded by

adityachute358
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Manual-3sem

python data on loops

Uploaded by

adityachute358
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 14
‘An Autonomous Institute Affiliated to R.TM.Nagpur University ‘Accredited with Grade “At"by NAAC LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING INDEX Experiment No.1: Experiment No.; Experiment No.: Experiment No. Experiment No. Experiment No. Experiment No.’ Experiment No. Experiment 9: Programs on NumPy Operations. rograms on basic control structures & loops. rograms on operators & /O operations... rograms on Lists.. rograms on Tuples. rograms on Dictionary. rograms on Set. rograms on File Handling Experiment No.1: Programs on basic control structures & loops. ‘Aim: To implement and understand basic control structures and loops such as conditionals, iteration, and flow control in Python. 1)Conditional (if-else) Statement: # Program to determine if a number is even or odd nut if num % 2 == 0: print(f"{num} is even.") else: print(P'{num} is odd.") int(input("Enter a number:")) 2)While Loop: # Program to print numbers from 1 to 5 using a while loop count While count <= 5: print(count) count += 1 3)For Loop: # Program to calculate the sum of numbers from 1 to 10 using a for loop sum = 0 for iin range(1, 11): sum += print("Sum of numbers from 1 to 10 is:", sum) 4)Nested Loop: # Program to print a pattem of stars in a nested loop n = 5. for i in range(1, n + 1): for j in range(i): print("*, end=") print() 5)Break and Continue: # Program to find the first even number in a list and continue to the next number if odd numbers = [7, 12, 5, 8, 3, 10] for num in numbers: if num % 2 ‘An Autonomous Institute Affiliated to R.TM Nagpur University : ‘Accredited with Grade “A+"by NAAC — LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING print(F"The first even number in the list is {num}.") break else: Continue 6)Switch Case (Using Dictionary): # Program to implement a simple switch case using a dictionary def add(x, y): retum x+y def subtract(x, y): return x - y def multiply(x, fetun x* y def divide(x, y): return x / y choice = input("Enter operation (+, -, *,/):") num = float(input("Enter first number:")) num2 = float(input("Enter second number:")) operations ‘+: add(num 1, num2), ‘-': subtract(num4, num2), ‘; multiply(num1, num2), "?: divide(num1, num2) } if choice in operations: print(PResult: {operations[choice}") else: print(“Invalid operation") Result: Successfully implemented basic control structures and loops to determine even/odd numbers, print sequences, and handle patterns. Viva Questions: 1. What is the purpose of the if-else statement? 2. How does the while loop differ from the for loop? 3. Can you write a for loop to calculate the sum of numbers from 1 to 100? 4, Why would you use a break statement inside a loop? 5. What could happen if you forget to increment a counter in a while loop? ‘An Autonomous Institute Affiliated to R.TM Nagpur University : ‘Accredited with Grade “A+"by NAAC — LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING Experiment No.2: Programs on operators & I/O operations. Aim: To apply arithmetic, comparison, and logical operators and perform basic file operations in Python. 1)Arithmetic Operators: # Program to perform arithmetic operations on two numbers num1 = float(input("Enter the first number: ") num2 = float(input("Enter the second number: ")) sum = num + num2 difference = num/1 - num2 product = num * num? quoti num2 print(P'Sum: {sum)") print(f*Difference: (difference}") print(P*Product: {product}") print(PQuotient: {quotient}") 2)Comparison Operators: # Program to compare two numbers num1 = float(input("Enter the first numbe » :")) num2 = float(input("Enter the second number: if num > num2: print(f'{num 1} is greater than {num2}") elif num1 < num2: print(P{num 1} is less than {num2}") else: print(F{num 1} is equal to {num2}") 3)Logical Operators: # Program to check if a number is within a specified range num = int(input("Enter a number: » lower_limit = 10 upper_limit = 50 if num >= lower_limit and num <= upper_imit: print(F'{num)} is within the range [(lower_limit}, {upper_limit}]") else: print(P'{num} is outside the range.") 4)Input/Output Operations:. # Program to read and write to a text file fle_name = "sample.txt" +# Writing to a file with openi{file_name, 'w') as file: file.write("Hello, this is a sample file. file.write("Python is a great programming language.") ‘An Autonomous Institute Affiliated to R.TM Nagpur University : ‘Accredited with Grade “A+"by NAAC — LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING # Reading from a file with open(file_name, 'r') as file: content = file.read() print("File Contents:") print(content) 5)String Operators: # Program to concatenate strings str1 str2 = "world!" concatenated _str = str1 + str2 print(concatenated_str) Hello, " # Program to repeat a string original_str = "Python" repeated_str = original_str * 3 print(repeated_str) Result: Correctly performed arithmetic operations, comparisons, and file VO operations with proper handling of strings and numbers. Viva Questions: 1. List all arithmetic operators in Python. 2. How does a comparison operator differ from a logical operator? 3. Can you demonstrate how to check if a number is within a specific range using logical operators? Why is file handling important in Python programming? 5. How can string concatenation impact the performance of a program involving large strings? s Experiment No.3: Programs on Lists. Aim: To manipulate and operate on lists using various methods including creation, modification, iteration, and advanced operations 1)Creating and Accessing Lists: # Program to create a list and access its elements fruits = "apple", "banana’, "cherry", “date"] # Accessing elements print("First fruit", fruits[0)) print("Last fruit: print("Slicing the list, fruits[1:3)) fruits[-1]) 2)Modifying Lists: # Program to modify a list numbers = [1, 2, 3, 4, 5] ‘An Autonomous Institute Affiliated to R.TM.Nagpur University ‘Accredited with Grade “At"by NAAC LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING # Appending an element numbers.append(6) # Updating an element numbers(2] = 10 # Removing an element numbers.remove(4) # Printing the modified list print(numbers) 3)lterating Over Lists: # Program to iterate over a list fruits = ['apple", "banana’, "cherry", “date"] for fruit in fruits: print(fruit) 4)List Comprehension: # Program to create a new list using list comprehension numbers = [1, 2, 3, 4, 5] squared_numbers = [num**2 for num in numbers] print(squared_numbers) 5)Finding Elements in Lists: # Program to find an element in a list fruits = ["apple", banana’, "cherry", “date"] search_fruit "banana" if search_fruitin fruits: print(P{search_fruit} is in the list. else: print('{Search_fruit} i not in th “) 6)Sorting and Reversing List # Program to sort and reverse numbers = [3, 1, 4, 2, 5] # Sorting the list in ascending order numbers.sort() print("Sorted list:", numbers) # Reversing the list numbers.reverse() print("Reversed list:", numbers) LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: PRIYADARSHINI COLLEGE OF ENGINEERING ‘An Autonomous Institute Affiliated to R.TM.Nagpur University ‘Accredited with Grade “At"by NAAC Result: Effectively created, modified, iterated over, and performed operations like sorting and list comprehension on lists. Viva Que! : 1. What is the syntax to create a list in Python? 2. Explain the difference between appending and modifying a list element. 3. How would you iterate through a list to print each element? 4, Whatis the advantage of list comprehension over regular loops? 5. How would you efficiently search for an element in a large list? Experiment No.4: Programs on Tuples. ‘Aim: To work with tuples in Python, focusing on their creation, element access, packing/unpacking, and operations. 1)Creating and Accessing Tuples: # Program to create a tuple and access its elements fruits = ("apple", "banana’, "cherry", "“date") # Accessing elements print("First fruit", fruits[0}) print("Last fruit: fruits[-1)) print("Slicing the tuple:”, fruits[1:3)) 2)Tuple Packing and Unpacking: # Program to use tuple packing and unpac! 1g person = ("John”, 30, "Engineer" # Unpacking the tuple into variables name, age, occupation = person print(f'Name: {name}") print(F*Age: {age}") print(f"Occupation: {occupation}") 3)Combining Tuples: # Program to combine two tuples fruits = "apple", "banana") more_fruits = ("cherry", “date") combined _fruits = fruits + more_fruits print("Combined tuple:", combined_fruits) 4)Finding Elements in Tuples: ‘An Autonomous Institute Affiliated to R.TM Nagpur University : ‘Accredited with Grade “A+"by NAAC — LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING # Program to find an element in a tuple fruits = ("apple", "banana", “cherry”, "date") search_fruit = "banana" ifsearch_fuil in fruits else: print(f'{search_fruit) is not in the tuple.") (P{search_fuil} is in the tuple.") 5)Counting and Indexing: # Program to count occurrences and find the index of an element in a tuple fruits "banana", "cherry", "banana’, "date") count = fruits.count("banana’) index = fruits.index("cherry") print(F'Count of banana’: {count}") print(f"index of ‘cherry’: {index}") Result: Successfully created, accessed, and manipulated tuples, demonstrating packing, unpacking, and combining Viva Questions: 1. How do you define a tuple in Python? 2. Whatis tuple unpacking, and how is it useful? 3. Can you create a program that combines two tuples into one? 4, How would you count the occurrences of an element in a tuple? 5. Inwhat scenarios would you prefer using tuples over lists? Experiment No. rograms on Dictionary. Aim: To manage and manipulate dictionaries in Python by performing operations like creation, modification, and iteration. 1)Creating and Accessing Dictionaries: # Program to create a dictionary and access its elements ice", “roll_ number": 101, "marks": 95 } # Accessing elements print("Student Name:", student['name")) print("Roll Number:”, student["roll_number")) print("Marks:", student{"marks")) 2)Modifying Dictionarie: ‘Add headings (Format > Paragraph styles) and they will appear in your table of contents. # Program to modify a dictionary student = { ‘An Autonomous Institute Affiliated to R.TM Nagpur University : ‘Accredited with Grade “A+"by NAAC — LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S WW PRIYADARSHINI COLLEGE OF ENGINEERING "name": “Alice”, "roll_number": 101, "marks": 95 } # Updating a value student{"marks"] = 98 # Adding a new key-value pair student["grade")= # Removing a key-value pair del student{"roll_number"] # Printing the modified dictionary print("Modified Student Info:", student) 3)Iterating Over Dictionary: # Program to iterate over a dictionary student = { "name": "Alice", *roll_number": 101, "marks": 95 } for key, value in student.items(): print(P{key}: {value}") 4)Checking for Key Existence: # Program to check if a key exists in a dictionary student = { “name”: "Alice", "roll_number": 101, "marks": 95 if search_key in student: print(P{search_key} exists in the dictionary.") else: print(P'{search_key} does not exist in the dictionary.") 5)Dictionary Comprehension: # Program to create a new dictionary using dictionary comprehension numbers = (1, 2, 3, 4, 5] squared _dict = {num: num**2 for num in numbers} print("Squared Dictionary:", squared_dict) Result: Accurately created, accessed, modified, and iterated over dictionaries, including using dictionary comprehensions. Viva Que: 1. What is the structure of a dictionary in Python? 2. How is a key-value pair in a dictionary different from a list element? 3. Write a Python program to update a value in a dictionary. ‘An Autonomous Institute Affiliated to R.TM.Nagpur University ‘Accredited with Grade “At"by NAAC LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING 4. How can you check for the existence of a key in a dictionary? 5. What are the benefits of using dictionary comprehension? Experiment No.6: Programs on Set. Aim: To understand and use sets in Python, including creation, modification, and performing set operations. 1. Creating and Accessing Sets: # Program to create a set and access its elements fruits = ('apple", "banana’, "cherry", "date"} # Accessing elements for fruit in fruits: print(fruit) 2, Modifying Sets: # Program to modify a set fruits = {"apple", "banana", "cherry", “date"} # Adding an element fruits.add("grape") # Removing an element fruits.remove("cherry") # Printing the modified set print("Modified Set:", fruits) 3. Set Operations: # Program to perform set operations A={1, 2,3, 4, 5} B={3,4,5,6,7} # Union of sets union = A|B print("Union of A and B:", union) # Intersection of sets intersection = A& B print("Intersection of A and B: # Difference of sets ‘An Autonomous Institute Affiliated to R.TM.Nagpur University ‘Accredited with Grade “At"by NAAC LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING difference = A-B print("Difference of A and B:", difference) 4, Set Comprehension: # Program to create a new set using set comprehension numbers = {1, 2, 3, 4, 5} squared_set = {num**2 for num in numbers} print("Squared Set:”, squared_set) Result: Correctly created sets, performed set operations, and used set comprehensions to handle unique elements and operations. Viva Questions: 1. How do you create a set in Python? 2. Explain the difference between union and intersection operations in sets. 3. Write a program to perform union and intersection operations on two sets. 4, How does a set ensure that all its elements are unique? 5. Why would you use sets instead of lists for certain operations? Experiment No.7: Programs on File Handling. ‘Aim: To perform basic file handling operations in Python such as reading from, writing to, and appending data to files. 1. Writing to a Text Fil # Program to write data to a text fle file_name = "sample.txt" # Open the file in write mode (creates a new file or overwrites an existing one) with open({file_name, 'w’) as file: file.write("Hello, this is a sample text fle.\n") file.write("Python is a great programming language.") print(P'Data written to ‘{file_namey' successfully.") 2. Reading froma Text Fil # Program to read data from a text fle file_name = "sample.txt" # Open the file in read mode 10 ‘An Autonomous Institute Affiliated to R.TM Nagpur University : ‘Accredited with Grade “A+"by NAAC — LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING with openi(file_name, 'r') as file: content = file.read() print(’File Contents") print(content) 3. Appending to a Text File: # Program to append data to an existing text file file_name = "sample.txt" # Open the file in append mode (keeps the exist with openifile_name, 'a') as file: file.write("\nThis is an additional line added to the file.") content and adds new content) print("Data appended to the file successfully.") Result: Efficiently managed file operations, including writing, reading, and appending data to text files. Viva Questions: 1. How do you open a file in write mode in Python? 2. Whatis the difference between reading and appending a file? 3. Write a Python program to append data to a text file, 4. Why should you always close a file after opening it in Python? 5. How can improper file handling lead to errors in large programs? Experiment No.8: Programs on Strings. ‘Aim: To manipulate strings in Python using concatenation, slicing, length calculation, and various string methods. 4. String Concatenation: # Program to concatenate two strings strt = "Hello, " str2 = "world!" concatenated_str = stri + str2 print(concatenated_str) 2. String Length: # Program to find the length of a string text = "Python is a powerful language.” length = len(text) n ‘An Autonomous Institute Affiliated to R.TM Nagpur University : ‘Accredited with Grade “A+"by NAAC — LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING print(P'The length of the string is {length} characters.") 3. String Slicing: # Program to slice a string text = "Python is fun!" # Slicing the string to get a substring substring = text[7:9] print(f'Substring: {substring)") 4, String Methods: # Program to use string methods text = "Hello, world!" # Convert to uppercase uppercase_text = text.upper() print("Uppercase:", uppercase_text) # Convert to lowercase lowercase_text = text.lower() print("Lowercase:", lowercase_text) # Replace a substring replaced_text = text.replace("world’, "Python") print(’Replaced Text", replaced_text) 5. String Splitting: # Program to split a string into a list, text = "apple, banana, cherry, date" # Split the string by commas fruits_list = text.spiit(", ") print("List of Fruits:", fruits_list) Result: Successfully performed string operations including concatenation, length calculation, slicing, and splitting, Viva Questions: 1. What function is used to find the length of a string in Python? 2. How does string slicing work in Python? 3. Write a Python program to convert a string to lowercase and then uppercase. 4. How would you split a string into a list of words based on a specific delimiter? 12 ‘An Autonomous Institute Affiliated to R.TM.Nagpur University ‘Accredited with Grade “At"by NAAC LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA'S: WW PRIYADARSHINI COLLEGE OF ENGINEERING 5. What are the advantages of using string methods like replace() and split() in text processing? Experiment 9: Programs on NumPy Operations ‘Aim: To perform basic operations with NumPy arrays including creation, reshaping, slicing, arithmetic operations, and broadcasting, 1)Array Creation: # Program to create a 1D and 2D array using NumPy import numpy as np # Creating a 1D array aray_1d = np.array((1, 2, 3, 4, 5]) print("1D Array:", array_1d) # Creating a 2D array array_2d = nparray({[1, 2, 3], [4. 5, 6]]) print("2D Array:\n", array_2d) 2)Array Shape and Size # Program to find shape and size of a NumPy array import numpy as np array = np.array([[1, 2, 3], [4, 5, 6), [7, 8, 9]]) # Getting the shape of the array print("Shape of array:", array.shape) # Getting the size (number of elements) print("Size of array: array.size) 3)Array Slicing: # Program to slice a NumPy array import numpy as np array = np.array([10, 20, 30, 40, 50) # Slicing the array to get elements from index 1 to 3 sliced_array = array[1:4] print("Sliced Array:", sliced_array) 4)Array Reshaping: # Program to reshape a NumPy array import numpy as np 13 ‘An Autonomous Institute Affiliated to R.TM Nagpur University : ‘Accredited with Grade “A+"by NAAC — LOKMANYA TILAK JANKALYAN SKISHAN SANSTHA’S WW PRIYADARSHINI COLLEGE OF ENGINEERING array = np.array((1, 2, 3, 4, 5, 6)) # Reshaping into a 2x3 anray reshaped_array = array.reshape(2, 3) print('Reshaped Avray:in", reshaped_array) 5)Array Arithmetic Operations: # Program for arithmetic operations on NumPy arrays import numpy as np arrayt array2 p.array([1, 2, 3]) parray({4, 5, 6) # Element-wise addition addition = array1 + array2 print("Addition:", addition) # Element-wise multiplication multip array! * array print("Muttiplication:", multiplication) 6)Array Broadcasting: # Program to demonstrate broadcasting in NumPy import numpy as np array = np.array([1, 2, 3]) # Broadcasting a scalar value broadcasted_array = array + 10 print("Broadcasted Array:", broadcasted_array) Result: Effectively created and manipulated NumPy arrays, demonstrating array creation, reshaping, slicing, and arithmetic operations. Viva Questions: 1. What function do you use to create a NumPy array? 2. What does the array.size attribute tell you about a NumPy array? 3. Given the NumPy array array = np.array([10, 20, 30]), how would you slice it to get the first two elements? 4. you have an array array = np.array({[1, 2], [3, 4]]), what will array.shape return? 5. Write a simple NumPy program to add two arrays: array1 = np.array([1, 2, 3]) and array2 = np.array({4, 5, 6)). 14

You might also like