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

PYTHON PROGRAMM 8870

The document provides an overview of Python programming concepts, including basic data types, operator precedence, the use of else clauses in loops, string functions, and the characteristics of lists, tuples, sets, and dictionaries. It also explains lambda functions and their usage, as well as methods for removing elements from sets. Each section includes examples to illustrate the concepts discussed.

Uploaded by

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

PYTHON PROGRAMM 8870

The document provides an overview of Python programming concepts, including basic data types, operator precedence, the use of else clauses in loops, string functions, and the characteristics of lists, tuples, sets, and dictionaries. It also explains lambda functions and their usage, as well as methods for removing elements from sets. Each section includes examples to illustrate the concepts discussed.

Uploaded by

santhosh45332
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

INTERNAL ASSIGNMENT

BACHELOR OF COMPUTER APPLICATIONS (BCA)

SESSION: November 2024


SEMESTER : 5
SUBJECT CODE: DCA-3104

NAME:M SANTHOSH

ROLL NUMBER: 2214506282

SUBJECT NAME: Python Programming


Q.No:1.a SET-1

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

Concept of operator precedence


The combination of values, variables, functions, and operators is called an expression. The
interpreter in Python can test and interpret whether an expression is valid or not. When an
expression includes more than one operator, then the interpreter operators them as per a
precedence level.
An arithmetic expression in Python when written without any parenthesis will be calculated
from left to right. All the arithmetic operators into various levels as per their order of
precedence. It is through the order of precedence of an operator that its priority is decided.
The precedence of operators in Python is listed in the table below: -
Operator Names
() Parentheses
** Exponent
+x, -x, ~x Unary plus, unary minus, and Bitwise NOT
*, /, //, % Multiplication, division, floor division,
modulus
+, - Addition and subtraction
<<, >> Bitwise left and right shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==,!=, <, >, >=, <=, is, is not, in, in not Comparison operators, identity operators,
membership operators
not Logical NOT
and Logical AND
or Logical OR

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.

➢ while Loop With else


The else block associated with a while loop executes when the loop's condition becomes
false, causing it to terminate unless a break statement is encountered.
Example:-
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1
if count == 3:
# break # If this break were here, the else would not execute
pass # pass does nothing, so the loop continues
else:
print("Loop finished naturally.")

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

String Functions in Python


String functions in Python, along with examples:

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.

my_dict = {"name": "Nishi", "age": 30, "city": "New York"}


my_dict["age"] = 31 # Change a value
my_dict["country"] = "USA" # Add a key-value pair
del my_dict["city"] # Remove a key-value pair
print(my_dict)

Output: {'name': 'Nishi', 'age': 31, 'country': 'USA'}

Summary Table:

Feature List Tuple Set Dictionary

Unordered Unordered (<3.7),


Ordering Ordered Ordered
(3.7+) Ordered (3.7+)
Mutability Mutable Immutable Mutable Mutable

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.

Q.No: 4.a SET-2

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]

Q.No: 4.b SET-2

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}

my_set.discard(6) # 6 is not in the set, but no error occurs


print(my_set)
Output: {1, 2, 4, 5} (set remains unchanged)
3. pop():
• Purpose: Removes and returns an arbitrary element from the set. Because sets are
unordered, you cannot control which element is removed.
• Behavior: If the set is not empty, an element is removed and returned. If the set is
empty, a KeyError is raised.
my_set = {1, 2, 3, 4, 5}
removed_element = my_set.pop() # Removes and returns an arbitrary element (e.g., 1)
print(my_set)
Output (order may vary): {2, 3, 4, 5}
print(removed_element)
Output (e.g.): 1

my_set = set() # Empty set


# my_set.pop() # This raises a KeyError: 'pop from an empty set'
Use:-
• Use remove() when you want to remove a specific element and you want to be
notified (via a KeyError) if the element is not there.
• Use discard() when you want to remove a specific element if it is present, but you
don't care if it's not there (you don't need to handle a potential error).
• Use pop() when you want to remove and retrieve an arbitrary element from the set,
often when you are treating the set like a stack or when the specific element to be
removed doesn't matter. Be careful of the KeyError on an empty set.

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

Uses of Pandas, NumPy, and Matplotlib in Python


Python is widely used for data analysis and scientific computing, including three essential
libraries: Pandas, NumPy, and Matplotlib. Each has a distinct role, yet they frequently
collaborate to handle, modify, and display data effectively.
1. NumPy (Numerical Python)
NumPy is the foundation of numerical computing in Python. It provides powerful tools for
working with large, multi-dimensional arrays and matrices, along with a vast collection of
mathematical functions.
Key Features of NumPy:
• ndarray: A powerful N-dimensional array that is faster and more memory-
efficient than Python lists.
• Mathematical operations: Functions for linear algebra, statistics, and random
number generation.
• Broadcasting: Allows operations on arrays of different shapes without explicit
looping.
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr * 2)
Output: [ 2 4 6 8 10]
print(np.mean(arr))
Output: 3.0

2. Pandas (Data Analysis Library)


Pandas is built on top of NumPy and provides easy-to-use data structures and data
manipulation tools for handling structured data like tables and spreadsheets. (“Difference
Between Pandas and Numpy in 2025 - fynd.academy”)
Key Features of Pandas:
• DataFrame: A 2D labeled data structure similar to an Excel table.
• Series: A 1D labeled array, similar to a column in a spreadsheet.
• Data handling: Supports reading/writing data from CSV, Excel, SQL, etc.
• Data manipulation: Sorting, filtering, grouping, and merging datasets.
Example:
import pandas as pd
data = {'Name': ['Nishi', 'Bobyb', 'Charlie'], 'Age': [25, 30, 28]}
df = pd.DataFrame(data)
print(df)

3. Matplotlib (Data Visualization Library)


Matplotlib is a poweerful plotting library for creating several types of graphs and
visualizations.
Key Features of Matplotlib:
• Supports line plots, bar charts, histograms, scatter plots, and more.
• Highly customizable (titles, labels, colors, etc.).
• Works well with NumPy and Pandas.
Example:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 5, 3]
plt.plot(x, y, marker='o')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Simple Plot")
plt.show()

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.

Q.No: 6.b SET-2

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

You might also like