PYTHON PROGRAMM 8870
PYTHON PROGRAMM 8870
NAME:M SANTHOSH
Python provides a number of data types that help in storing and processing data in different
forms. The basic data types in Python are:
1. Integer (int): This type is used to store whole numbers (both positive and negative),
without any fractional part.
Example: x = 5.
2. Floating Point (float): Used to store numbers that have a decimal point. These can
represent both rational and irrational numbers.
Example: y = 3.14.
3. String (str): Strings store sequences of character enclosed in single or double quotes.
They are used for textual data.
Example: name = "Nishi".
4. Boolean (bool): This type represents one of two values: True or False. It is typically
used for logical operations or conditional statements.
Example: is_active = True.
5. List (list): A list is an ordered collection of items that can be of any type, including
other lists. Lists are mutable, meaning their content can be changed. Example:
numbers = [1, 2, 3, 4].
6. Tuple (tuple): Similar to lists, but immutable. Once created, the values in a tuple
cannot be changed.
Example: coordinates = (4, 5).
7. Set (set): A set is an unordered collection of unique items. Sets do not allow duplicate
values.
Example: fruits = {"apple", "orange", "banana"}.
8. Dictionary (dict): A dictionary stores key-value pair. Keys are unique and are used to
access the associated values.
Example: person = {"name": "Bob", "age": 25}.
These data types form the foundation for creating and manipulating data in Python. Each
serves a specific purpose, making Python versatile and efficient for various applications.
Q.No:1.b SET-1
Example:
• result = 10 + 2 * 3 ** 2 // 4 - 5
• print(result)
Evaluation order:
1. 3 ** 2 → 9 (Exponentiation)
2. 2 * 9 → 18 (Multiplication)
3. 18 // 4 → 4 (Floor division)
4. 10 + 4 → 14 (Addition)
5. 14 - 5 → 9 (Subtraction)
Output: 9
Q.No:2.a SET-1
The else clause in Python can be used with both for and while loops. It executes after the
loop completes unless the loop is prematurely terminated by a break statement. This makes it
useful for situations where you want to do something only if the loop runs its natural course.
➢ For Loop With else:
The else block associated with a for loop executes when the loop finishes iterating through all
the elements in the iterable.
Example:-
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
if fruit == "grape": # This condition will never be met in this example
break # The else block would not execute if this break happened
else:
print("All fruits processed.") # This will print because the loop completed fully
Output:
1. apple
2. banana
3. cherry
4. All fruits processed.
If we were to add "grape" to the list and the if condition was met, the break statement would
execute, and the else block would be skipped.
Output:
• Count is: 0
• Count is: 1
• Count is: 2
• Count is: 3
• Count is: 4
• Loop finished naturally.
If the break statement within the if condition were uncommented, the loop would terminate
early, and the else block would not execute.
Using Cases:
Searching: You can use the else block to indicate that an item was not found after iterating
through a list.
Example :-
def search(arr, target):
for item in arr:
if item == target:
print(f"Found {target} at index {arr.index(item)}")
break # Exit the loop once found
else:
print(f"{target} not found in the list")
my_list = [1, 2, 3, 4, 5]
a) search(my_list, 3)
Output:
Found 3 at index 2
b) search(my_list, 6)
Output:
1. 6 not found in the list
Loop Completion:
You can use the else block to perform actions that should only happen if a loop completes
without interruption. This is less common but can be useful.
Q.No:2.b SET-1
1. upper()
The upper() method converts all lowercase letters in a string to uppercase.
Example:
text = "hello world"
result = text.upper()
print(result)
Output: "HELLO WORLD"
Explanation: Convert all character in the string "hello world" to uppercase.
2. lower ()
The lower() method convert all uppercase letters in a string to lowercase.
Example:
text = "HELLO WORLD"
result = text.lower()
print(result)
Output: "hello world"
Explanation: Converts all character in the string "HELLO WORLD" to lowercase.
2. isdigit ()
The isdigit() method checks if all characters in a string are digits. It returns True if all
character are digits and False otherwise.
Example:
text = "12345"
result = text.isdigit()
print(result)
Output: True
Explanation: Since the string "12345" contains only digits, it returns True.
Example with non-digit string:
text = "abc123"
result = text.isdigit()
print(result)
Output: False
Explanation: The string contains non-digit character, so it returns False.
4. Isalpha ()
The isalpha () method checks if all character in a string are alphabetic (letters only). It returns
True if all character is alphabetic, and False otherwise.
Example:
text = "hello"
result = text.isalpha()
print(result)
Output: True
Explanation: Since the string "hello" consists of only alphabetic character, it returns True.
Example with non-alphabetic string:
text = "hello123"
result = text.isalpha()
print(result)
Output: False
Explanation: The string contains numbers, so it returns False.
5. split ()
The split() method splits a string into a list of substrings based on a delimiter (default is
space).
Example:
text = "apple orange banana"
result = text.split()
print(result)
Output: ['apple', 'orange', 'banana']
Explanation: The string is split into words based on spaces and returned as a list.
Example with custom delimiter:
text = "apple,orange,banana"
result = text.split(",")
print(result)
Output: ['apple', 'orange', 'banana']
Explanation: The string is split at each comma.
6. join()
The join() method combines a list (or other iterable) of strings into a single string, with a
specified separator.
Example:
words = ['apple', 'orange', 'banana']
result = ", ".join(words)
print(result)
Output: "apple, orange, banana"
Explanation: Joins the words in the list with ", " as the separator.
Example without separator:
words = ['apple', 'orange', 'banana']
result = "".join(words)
print(result)
Output: "appleorangebanana"
Explanation: Joins the words without any space or separator.
• upper() and lower() are used to change the case of the string.
• isdigit() checks if all character are numeric, while isalpha() checks if all character are
alphabetic.
• split() is used to split a string into a list of substrings, and join() is used to concatenate
a list of strings into a single string with a separator.
Q.No:3 SET-1
Lists, tuples, sets, and dictionaries are fundamental data structures in Python, each with
distinct characteristics and use cases. Here's a breakdown of their key differences:
1. Lists:
• Ordered: Elements maintain their insertion order.
• Mutable: You can modify lists after creation (add, remove, change elements).
• Duplicates allowed: Lists can contain duplicate values.
• Defined by: Square brackets [].
Example:
my_list = [1, 2, "apple", 3.14, 2] # Mixed data types, duplicate 2
my_list.append(5) # Add an element
my_list[0] = 10 # Change an element
print(my_list)
Output: [10, 2, "apple", 3.14, 2, 5]
2. Tuples:
• Ordered: Elements maintain their insertion order.
• Immutable: Once created, tuples cannot be changed. This makes them useful for
representing fixed collections of data.
• Duplicates allowed: Tuples can contain duplicate values.
• Defined by: Parentheses () (though parentheses are optional in some cases).
Example:
my_tuple = (1, 2, "apple", 3.14, 2) # Mixed data types, duplicate 2
# my_tuple[0] = 10 # This will raise a TypeError: 'tuple' object does not support item
assignment
# my_tuple.append(5) # This will also raise an AttributeError: 'tuple' object has no attribute
'append'
print(my_tuple)
Output: (1, 2, "apple", 3.14, 2)
3. Sets:
• Unordered: Elements do not have a specific order. You cannot access them by index.
• Mutable: You can add or remove elements from a set.
• No duplicates allowed: Sets automatically remove duplicate values.
• Defined by: Curly braces {}.
my_set = {1, 2, "apple", 3.14, 2} # Duplicate 2 is removed
my_set.add(5)
my_set.remove("apple")
print(my_set)
Output (order may vary): {1, 2, 3.14, 5}
4. Dictionaries:
• Unordered (in Python versions before 3.7): Dictionaries did not guarantee order. From
3.7 onward, they maintain insertion order.
• Mutable: You can add, remove, or change key-value pairs.
• Keys must be unique: Values can be duplicated, but keys cannot.
• Defined by: Curly braces {} with key-value pairs separated by colons.
Summary Table:
Keys: Unique,
Duplicates Allowed Allowed Not Allowed
Values: Allowed
Use Cases:
• Lists: Use when you need an ordered, mutable sequence of items. Good for storing
collections of items that might need to be modified.
• Tuples: Use when you need an ordered, immutable sequence of items. Useful for
representing fixed records or data that should not be changed. Also often used to
return multiple values from a function.
• Sets: Use when you need a collection of unique elements and order doesn't matter.
Useful for operations like finding intersections, unions, and differences between
collections.
• Dictionaries: Use when you need to associate keys with values (like a map or hash
table). Useful for representing structured data or lookups.
A lambda function in Python is a tiny, anonymous, and nameless function created with the
lambda keyword. It's a concise approach to construct basic functions, especially when you
just need them for a short time and don't want to declare a whole function with the def
keyword.
Structure of a Lambda Function:
lambda arguments: expression
1. lambda: The keyword that indicates you're creating a lambda function.
2. arguments: A comma-separated list of input arguments (can be zero or more).
3. expression: A single expression that is evaluated and returned. Lambda functions
implicitly return the result of this expression. They cannot contain
statements (like if, for, or while).
Example:
def add(x, y):
return x + y
add_lambda = lambda x, y: x + y
print(add(5, 3))
Output: 8
print(add_lambda(5, 3))
Output: 8
the lambda function add_lambda achieves the same result as the regular function add but in a
much more compact way.
➢ Lambda Functions Usage:
1. Conciseness: Lambda functions are great for short, simple operations where
defining a full function would be overkill. They make your code more readable
when the function's logic is straightforward.
2. Anonymous functions: Lambda functions don't need a name. This is helpful
when you need a function for a one-time use and don't want to clutter your code
with named functions.
3. Higher-order functions: Lambda functions are often used as arguments to
higher-order functions (functions that take other functions as arguments). This is
where they shine. Common examples include:
➢ map(): Applies a function to each item in an iterable.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers)) # Square each number
print(squared) Output: [1, 4, 9, 16, 25]
1. filter(): Filters items in an iterable based on a function.
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers)) # Get even numbers
print(even)
Output: [2, 4, 6]
remove(), discard(), and pop() are all used to delete elements from a set in Python, but
They have some key differences:
1. remove(element):
• Purpose: Removes the specified element from the set.
• Behavior: If the element is present in the set, it's removed. If the element is not
present, a KeyError is raised.
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set)
Output: {1, 2, 4, 5}
my_set.remove(6) This will raise a KeyError because 6 is not in the set.
2. discard(element):
• Purpose: Removes the specified element from the set.
• Behavior: If the element is present, it's removed. If the element is not present,
nothing happens (no error is raised). This is the key difference between remove() and
discard().
my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set)
Output: {1, 2, 4, 5}
Q.No: 5 SET-2
Exception handling is a programming tool that allows you to responsibly manage mistakes
or extraordinary occurrences that arise during the execution of your code. Instead of the
software crashing or abruptly terminating, you may foresee future issues and build code to
handle them in a controlled manner.
Benefits of Exception Handling :
1. Prevents crashes: It stops your program from terminating unexpectedly due to errors.
2. Improves robustness: It makes your code more reliable and able to handle unexpected
input or conditions.
3. Provides informative messages: You can provide helpful error messages to the user
instead of cryptic technical details.
4. Allows for recovery: In some cases, you might be able to recover from an exception
and continue program execution.
Structure of Exception Handling in Python:
• try:
• # Code that might raise an exception
• # ...
• except ExceptionType1:
• # Code to handle ExceptionType1
• # ...
• except ExceptionType2:
• # Code to handle ExceptionType2
• # ...
• else:
• # Code that executes if no exceptions occur in the try block
• # ...
• finally:
• # Code that *always* executes, regardless of whether an exception occurred
• # ...
Example Program:
Python program that asks the user for an integer and throws an exception if the value is less
than or equal to zero
Python program :
• while True: # Loop until a valid positive number is entered
• try:
• user_input = input("Enter a positive integer (greater than zero): ")
• number = int(user_input) # Try converting the input to an integer
• if number <= 0:
• raise ValueError("Input must be greater than zero.") # Raise a ValueError if
the number is not positive
• else:
• print("You entered:", number)
• break # Exit the loop if a valid number is entered
• except ValueError as e: # Handle the ValueError (and other potential errors)
• print(f"Invalid input: {e}") # Print the error message
• except Exception as e: # Catch any other exceptions
• print(f"An unexpected error occurred: {e}")
• finally:
• print("This always executes, regardless of whether an exception was raised.")
• print("Program finished.")
Explanation:
1. try block: The try block contains the code that may cause an exception (converting
the input to an integer and determining whether it is positive).
2. except ValueError block: This block handles ValueError exceptions, which can
occur if the user enters something that cannot be converted to an integer or if the
number is not positive. The as e part allows us to access the exception object and its
message.
3. except Exception block: This block will catch any other exceptions that might occur.
This is a good practice to have as a general catch-all in case you have not specifically
handled an exception type.
4. else block: The else block is optional. It will only execute if no exceptions are raised
in the try block.
5. finally block: The finally block is also optional. The code inside it will always
execute, whether an exception was raised or not. This is often used for cleanup tasks
(like closing files or releasing resources).
6. raise ValueError(...): If the user enters a value less than or equal to zero, we
explicitly raise a ValueError with a descriptive message. This allows us to control
when and what kind of exception is thrown.
7. while True loop: The loop continues to prompt the user until a valid positive integer
is entered. The break statement is used to exit the loop once a valid number is
provided.
Q.No: 6.a SET-2
Libraries Acts:
1. NumPy: Performs fast numerical operations on arrays.
2. Pandas: Organizes data into tables and simplifies data analysis.
3. Matplotlib: Visualizes the data for better insights.
Example:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Create a dataset
data = {'A': np.random.raandint(1, 100, 10), 'B': np.random.randint(1, 100, 10)}
df = pd.DataFrame(data)
# Plot the data
plt.scatter(df['A'], df['B'])
plt.xlabel("Feature A")
plt.ylabel("Feature B")
plt.title("Scatter Plot of A vs B")
plt.show()
• NumPy, Pandas, and Matplotlib are essential tools for data analysis and scientific
computing in Python. NumPy provides fast numerical operations, Pandas simplifies
data handling, and Matplotlib enables effective data visualization. Together, they
form a powerful ecosystem for data science and machine learning.
The word CRUD stands for Create, Read, Update, and Delete. These are the four
fundamental data operations that may be performed, and they are required for permanent
storage and data management in almost all applications. Consider these the primary activities
you can perform with information.
CRUD operations are typically used when interacting with databases, files, or other forms of
storage where you want to keep track of data throughout time.
CRUD operations are essential for managing data in applications. They are broadly
used in:
1. Databases (MySQL, PostgreSQL, SQLite)
2. File handling (CSV, JSON, text files)
3. APIs and Web Applications (Django, Flask, FastAPI)
By understanding CRUD, you can effectively build data-driven applications in Python.
Applying process :
➢ Create: Adds new data to the storage. This might involve inserting a new row into a
database table, adding a new entry to a file, or creating a new object in a data store.
Example: # Create operation
• data = [] # Empty list (simulating a database)
• data.append({"id": 1, "name": "Nishi", "age": 25})
• data.append({"id": 2, "name": "Bob", "age": 30})
• print(data)
Output: [{'id': 1, 'name': 'Nishi', 'age': 25}, {'id': 2, 'name': 'Bob', 'age': 30}]
➢ Read: Existing data from storage is retrieved. This might include retrieving a
particular record, retrieving a collection of records depending on certain criteria, or
reading all of the data.
• Example: Displaying a list of Users on an website.
# Read operation
• for record in data:
• print(f"SR: {record['id']}, Name: {record['name']}, Age: {record['age']}")
Output:
SR: 1, Name: Nishi, Age: 25
SR: 2, Name: Bobby, Age: 30
➢ Update: Alters the existing data in the storage. This might include altering the value
of a field in a database record, updating data in a file, or editing an object's properties.
• Example: Changing a user's age in a database.
# Update operation
for record in data:
if record["id"] == 1:
record["age"] = 26 # Updating Nishi age
print(data)
Output: [{'id': 1, 'name': 'Nishi', 'age': 26}, {'id': 2, 'name': 'Bob', 'age': 30}]
➢ Delete: Removes data from the storage. This could involve deleting a record from a
database table, removing an entry from a file, or deleting an object.
• Example: Removing a product from an website.
# Delete operation
data = [record for record in data if record["id"] != 2] # Remove Bobby record
print(data)
Output: [{'id': 1, 'name': 'Nishi', 'age': 26}]
CRUD Operations are Implemented in Python:
The specific way to implement CRUD operations in Python depends on the type of storage
using.
There are some common scenarios:
1. Files: You can perform CRUD operations on files using Python's built-in file I/O
functions.
Python program:-
• # Create (Write)
• with open("my_file.txt", "w") as f:
• f.write("Hello, world!\n")
• # Read
• with open("my_file.txt", "r") as f:
• content = f.read()
• # Update (Rewrite or append)
• with open("my_file.txt", "a") as f:
• f.write("More content.\n")
• # Delete
• import os
• os.remove("my_file.txt")
2. NoSQL Databases: To conduct CRUD activities on NoSQL databases (such as
MongoDB), utilize database-specific libraries (such as pymongo) and their associated
methods.
3. APIs: When communicating with online APIs, you would normally utilize HTTP
methods (POST for creating, GET for reading, PUT/PATCH for updating, and
DELETE for deleting) to