INTERNAL ASSIGNMENT
SESSION NOVEMBER 2024
PROGRAM BACHELOR OF COMPUTER APPLICATIONS (BCA)
SEMESTER 5
COURSE CODE & NAME DCA3104 – PYTHON PROGRAMMING
CREDITS 4
NUMBER OF ASSIGNMENTS & MARKS 02
30
SET 1
1. a) Discuss different datatypes used in Python Programming.
b) Explain the concept of operator precedence with example.
Ans - (a)Python provides a variety of built-in data types that allow developers to work with different
kinds of data efficiently. Below are some of the most commonly used data types in Python:
1. Numeric Types:
o int: Represents whole numbers (e.g., 10, -5).
o float: Represents decimal numbers (e.g., 3.14, -2.5).
o complex: Represents complex numbers with a real and imaginary part (e.g., 3 + 4j).
2. Sequence Types:
o list: A mutable (modifiable) collection of ordered elements (e.g., [1, 2, 3]).
o tuple: An immutable (non-modifiable) collection of ordered elements (e.g., (1, 2, 3)).
o range: Represents a sequence of numbers and is often used in loops (e.g., range(1, 10)).
3. Text Type:
o str: Represents a sequence of Unicode characters (e.g., "Hello, World!").
4. Set Types:
o set: A collection of unordered, unique elements (e.g., {1, 2, 3}).
o frozenset: An immutable version of a set.
5. Mapping Type:
o dict: Stores key-value pairs, allowing efficient lookups (e.g., {"name": "Alice", "age": 25}).
6. Boolean Type:
o bool: Represents truth values (True or False).
7. Binary Types:
o bytes: Immutable sequence of bytes.
o bytearray: Mutable sequence of bytes.
o memoryview: Provides a memory-efficient way to handle binary data.
Python’s dynamic typing allows variables to hold different data types without explicit declaration,
making it a flexible and powerful programming language.
(b) Operator Precedence in Python
Operator precedence determines the order in which operators are evaluated in an expression. Python
follows specific rules to decide which operation to perform first when multiple operators appear in a
single expression. Operators with higher precedence are evaluated before those with lower
precedence.
Precedence Order (Highest to Lowest)
1. Parentheses () – Expressions inside parentheses are evaluated first.
2. Exponentiation ** – Exponentiation is performed before other arithmetic operations.
3. Unary operators +, -, ~ – Unary plus, minus, and bitwise NOT.
4. Multiplication *, Division /, Floor Division //, Modulus % – These operators are evaluated
before addition and subtraction.
5. Addition +, Subtraction - – Evaluated after multiplication and division.
6. Bitwise Shift <<, >> – Left and right shift operators.
7. Bitwise AND &, Bitwise XOR ^, Bitwise OR | – Performed in sequence.
8. Comparison Operators ==, !=, >, <, >=, <= – Evaluated after arithmetic operations.
9. Logical NOT not, Logical AND and, Logical OR or – Logical operations are evaluated last.
2. a) Discuss the use of else statement with for and while loop. Explain with an example.
b) Explain the use of following string functions: - upper(), lower(), isdigit(), isalpha(), split(), join() with
example.
Ans – (a)Using else with for and while Loops in Python
In Python, the else statement can be used with for and while loops. It executes after the loop finishes
normally, meaning it does not execute if the loop is terminated by a break statement.
1. else with for Loop
• The else block runs only if the for loop completes all iterations.
• If a break is encountered, the else block is skipped.
Example:
for num in range(1, 6):
if num == 3:
print("Breaking the loop")
break
print(num)
else:
print("Loop completed without break")
Output:
Breaking the loop
(The else block does not execute because break was used.)
2. else with while Loop
• The else block runs only if the while condition becomes False naturally.
• If break is used, the else block is skipped.
Example:
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop ended normally")
Output:
Loop ended normally
(b) String Functions in Python
Python provides several built-in string functions for string manipulation. Below are six commonly used
string functions:
1. upper()
• Converts all characters in a string to uppercase.
Example:
text = "hello world"
print([Link]())
Output:
HELLO WORLD
2. lower()
• Converts all characters in a string to lowercase.
Example:
text = "HELLO WORLD"
print([Link]())
Output:
hello world
3. isdigit()
• Returns True if all characters in the string are digits, otherwise False.
Example:
num = "12345"
print([Link]())
text = "abc123"
print([Link]())
Output:
True
False
4. isalpha()
• Returns True if all characters in the string are alphabets (A-Z or a-z), otherwise False.
Example:
word = "Python"
print([Link]())
word = "Python123"
print([Link]())
Output:
True
False
5. split()
• Splits a string into a list of words based on a specified separator (default is space).
Example:
text = "Python is fun"
print([Link]())
Output:
['Python', 'is', 'fun']
6. join()
• Joins a list of strings into a single string using a specified separator.
Example:
words = ['Python', 'is', 'fun']
print(" ".join(words))
Output:
Python is fun
These functions help efficiently manipulate and process string data in Python.
3. a) How to delete an element from list? Explain different cases with examples.
b) Explain differences between list, tuple, set and dictionary.
Ans – (a) Deleting an Element from a List in Python
Python provides several methods to delete elements from a list. Below are different ways to remove
elements based on various cases.
1. Using del Statement
• Removes an element by index.
• Can also delete a slice of elements.
Example:
numbers = [10, 20, 30, 40, 50]
del numbers[2] # Removes element at index 2
print(numbers) # Output: [10, 20, 40, 50]
# Deleting a slice
del numbers[1:3]
print(numbers) # Output: [10, 50]
2. Using remove() Method
• Removes the first occurrence of a specific value.
• Raises an error if the value is not found.
Example:
fruits = ["apple", "banana", "cherry", "banana"]
[Link]("banana")
print(fruits) # Output: ['apple', 'cherry', 'banana']
3. Using pop() Method
• Removes an element by index and returns it.
• If no index is provided, removes and returns the last element.
Example:
numbers = [1, 2, 3, 4, 5]
removed_element = [Link](2)
print(numbers) # Output: [1, 2, 4, 5]
print(removed_element) # Output: 3
4. Using List Comprehension (for Multiple Occurrences)
• Removes all occurrences of a specific value.
Example:
numbers = [1, 2, 3, 2, 4, 2]
numbers = [x for x in numbers if x != 2]
print(numbers) # Output: [1, 3, 4]
Each method is useful based on whether you need to remove elements by index, value, or conditionally
filter elements.
(b) Differences Between List, Tuple, Set, and Dictionary in Python
Python provides four key collection data types: List, Tuple, Set, and Dictionary. Each has unique
properties and use cases.
1. List (list)
• Definition: An ordered, mutable collection of elements.
• Characteristics:
oAllows duplicate values.
o Supports indexing and slicing.
o Can store different data types.
• Example:
• my_list = [1, 2, 3, 4, 2]
• my_list.append(5) # Adding an element
• print(my_list) # Output: [1, 2, 3, 4, 2, 5]
2. Tuple (tuple)
• Definition: An ordered, immutable collection of elements.
• Characteristics:
o Cannot be modified after creation.
o Supports indexing and slicing.
o Faster than lists due to immutability.
• Example:
• my_tuple = (1, 2, 3, 4, 2)
• print(my_tuple[1]) # Output: 2
3. Set (set)
• Definition: An unordered collection of unique elements.
• Characteristics:
o Does not allow duplicates.
o Does not support indexing.
o Supports mathematical set operations like union and intersection.
• Example:
• my_set = {1, 2, 3, 4, 2}
• print(my_set) # Output: {1, 2, 3, 4}
4. Dictionary (dict)
• Definition: A collection of key-value pairs.
• Characteristics:
o Keys must be unique.
o Fast lookups using keys.
o Order is maintained (since Python 3.7+).
• Example:
• my_dict = {"name": "Alice", "age": 25}
• print(my_dict["name"]) # Output: Alice
Key Differences
Type Ordered Mutable Allows Duplicates Indexing Unique Elements
List Yes Yes Yes Yes No
Tuple Yes No Yes Yes No
Set No Yes No No Yes
Dict Yes Yes Keys: No, Values: Yes Keys: No Keys: Yes
Each data type serves different purposes based on requirements for mutability, ordering, and
uniqueness.
SET 2
4. a) What is lambda function? Why is it used?
b) Explain differences between remove(), discard( ) and pop( ) method for deleting elements from set.
Ans - Lambda Function in Python
A lambda function in Python is an anonymous (nameless) function that is defined using the lambda
keyword. It is a single-expression function that returns a value automatically without using the return
statement.
Syntax of Lambda Function
lambda arguments: expression
• lambda → Defines the lambda function.
• arguments → Input parameters (optional).
• expression → The computation to be performed (must be a single expression).
Why Use Lambda Functions?
1. Concise and Readable: Lambda functions are shorter than regular functions.
2. Useful for One-Time Use: Ideal for small tasks that don’t require a named function.
3. Works Well with Higher-Order Functions: Used with functions like map(), filter(), and sorted().
4. Improves Code Efficiency: Avoids unnecessary function definitions.
Examples
1. Basic Lambda Function
square = lambda x: x ** 2
print(square(5)) # Output: 25
2. Using Lambda with map()
numbers = [1, 2, 3, 4]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16]
3. Using Lambda with filter()
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]
Conclusion
Lambda functions are lightweight, anonymous, and efficient, making them useful for short and
simple operations. However, for complex logic, regular functions (def) are preferred for better
readability.
(b) Differences Between remove(), discard(), and pop() in Sets
Python provides three methods to delete elements from a set: remove(), discard(), and pop(). While
all three methods are used to delete elements, they have different behaviors in certain situations.
1. remove() Method
• Removes a specific element from the set.
• Raises a KeyError if the element is not found.
Example:
my_set = {1, 2, 3, 4}
my_set.remove(3)
print(my_set) # Output: {1, 2, 4}
# Removing a non-existent element raises an error
my_set.remove(5) # KeyError: 5
2. discard() Method
• Removes a specific element from the set.
• Does not raise an error if the element is missing.
Example:
my_set = {1, 2, 3, 4}
my_set.discard(3)
print(my_set) # Output: {1, 2, 4}
# Removing a non-existent element does nothing (no error)
my_set.discard(5) # No error
print(my_set) # Output: {1, 2, 4}
3. pop() Method
• Removes and returns a random element from the set.
• Raises a KeyError if the set is empty.
Example:
my_set = {10, 20, 30, 40}
removed_element = my_set.pop()
print(removed_element) # Random element (depends on internal order)
print(my_set) # Remaining elements
If the set is empty:
empty_set = set()
empty_set.pop() # KeyError
Key Differences
Removes Specific Raises Error If Element Not Removes Random
Method
Element? Found? Element?
remove() Yes Yes No
discard() Yes No No
pop() No Yes (if empty) Yes
Use remove() when ensuring the element exists, discard() when avoiding errors, and pop() when
removing an arbitrary element.
5. What is exception handling? Write a Python program which would throw exception if the value
entered by user is less than zero or zero otherwise print it.
Ans - Exception Handling in Python
Exception handling is a mechanism in Python used to handle runtime errors and prevent program
crashes. When an error occurs, Python generates an exception, which can be handled using the
try-except block.
Why Use Exception Handling?
1. Prevents Program Crashes: Handles unexpected errors gracefully.
2. Improves User Experience: Provides meaningful error messages.
3. Allows Safe Execution: Ensures critical code continues running even if an error occurs.
Syntax of Exception Handling
try:
# Code that may cause an exception
except ExceptionType:
# Code to handle the exception
else:
# Code to execute if no exception occurs
finally:
# Code that executes regardless of an exception
Python Program: Handling Negative or Zero Input
This program takes user input, checks if it is less than or equal to zero, and raises an exception if
necessary.
# Exception Handling Program
try:
# Taking input from user
num = int(input("Enter a positive number: "))
# Checking if number is zero or negative
if num <= 0:
raise ValueError("Error: Number must be greater than zero!")
# Printing the valid number
print("You entered:", num)
except ValueError as e:
# Handling exception and printing error message
print(e)
finally:
print("Program execution completed.")
Explanation of the Code
1. try Block:
o Takes user input and converts it to an integer.
o If the number is ≤ 0, it raises a ValueError with a custom message.
2. except Block:
o Catches the ValueError and prints the error message.
3. finally Block:
o Executes always, whether an exception occurs or not.
Example Outputs
Case 1: Valid Input
Enter a positive number: 5
You entered: 5
Program execution completed.
Case 2: Zero Input
Enter a positive number: 0
Error: Number must be greater than zero!
Program execution completed.
Case 3: Negative Input
Enter a positive number: -10
Error: Number must be greater than zero!
Program execution completed.
Key Takeaways
• Exception handling prevents program crashes by catching errors.
• The raise keyword allows us to manually trigger exceptions.
• The finally block executes no matter what, ensuring proper cleanup.
This approach ensures the program handles invalid inputs gracefully while allowing correct values
to proceed normally.