Python Module 2 Important Topics
Python Module 2 Important Topics
[Link]
Python-Module-2-Important-Topics
1. Strings
What is a string?
Subscript operator
Slicing
String Methods
2. Text files
Writing Text to a File
Example
3. Functions
What is a function?
Syntax of a function
Calling a function
4. Higher order functions
What is a higher order function?
Properties of high order functions in python
Types of HIgh order functions
Mapping
Filtering
Reducing
5. Lambda Functions
What is Lambda function?
Syntax of lambda function
Example
6. List
What is a List?
Example
List methods
7. Set
What is a set?
Example
Set Methods
Add items
Length of a set
Remove item
Other methods
8. Tuples
What is a tuple?
Example
Benefits of tuple?
9. Dictionaries
What is a dictionary?
Example
Adding keys and replacing values
Accessing Values
Removing keys
Python-Module-2-University-Questions-Part-A
1. Write Python code for the following statements
2. What are mutable and immutable properties in the case of Python datastructures?
3. Write the output of following python code :
4. Write a recursive function in python to find GCD of two numbers.
5. Differentiate between lists and tuples with the help of examples
6. Write a Python program to print all palindromes in a line of text.
7. Illustrate format specifiers and escape sequences with examples.
Python-Module-2-University-Question-Part-B
1. Write a Python program to implement Caesar cipher encryption and decryption on
a string of lowercase letters. Take distance value and the string as input.
2. Write a Python code segment that opens a file for input and prints the number of
four-letter words in the file.
3. Write a Python program to create a set of functions that compute the mean,median
and mode of a set of numbers. Each function should expect a list of numbers as an
argument and return a single number. Each function should return 0 if the list is
empty. Include a main function that tests the three functions with a given list.
4. Write a Python program to check whether a list contains a sublist.
5. Assume that the variable data refers to the string "Python rules!". Use a string
method to perform the following tasks:
6. Use higher order python function filter to extract a list of positive numbers from a
given list of numbers. You should use a lambda to create the auxiliary function
7. Assume that there is a text file named “[Link]”. Write a python program to
find the median of list of numbers in the file without using standard function for
median
8. Write a Python program to convert a decimal number to its binary equivalent.
9. Write a Python program to read a text file and store the count of occurrences of
each character in a dictionary
10. Write a Python code to create a function called listof frequency that takes a string
and prints the letters in non-increasing order of the frequency of their occurrences.
Use dictionaries.
11. Write a Python program to read a list of numbers and sort the list in a non-
decreasing order without using any built in functions. Separate function should be
written to sort the list wherein the name of the list is passed as the parameter.
12. Illustrate the following Set methods with an example.
13. Write a Python program to check the validity of a password given by the user.
[Link] a dictionary of names and birthdays. Write a Python program that asks the
user to enter a name, and the program display the birthday of that person
1. Strings
What is a string?
This returns 9
The positions of a string‘s characters are numbered from 0, on the left, to the length of the
string minus 1, on the right.
The string is an immutable data structure. This means that its internal data elements, the
characters, can be accessed, but cannot be replaced, inserted, or removed.
Subscript operator
Slicing
2. Text files
A text file is a software object that stores data on a permanent medium such as a disk, CD,
or flash memory.
Writing Text to a File
Example
f = open("[Link]", 'w')
Example-Reading a file
3. Functions
What is a function?
A function is a block of code which only runs when it is called. You can pass data, known
as parameters, into a function. A function can return data as a result.
In Python, a function is a group of related statements that performs a specific task
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
Syntax of a function
def function_name(parameters):
statement(s)
Calling a function
def my_function():
print("Hello from a function")
my_function() # calling a function
A function that is having another function as an argument or a function that returns another
function as a return in the output is called the high order function.
Mapping
Example
Filtering
A second type of higher-order function is called a filtering. In this process, a function called
a predicate is applied to each value in a list.
If the predicate returns True, the value passes the test and is added to a filter object
(similar to a map object).
The process is a bit like pouring hot water into a filter basket with coffee.
The good stuff to drink comes into the cup with the water, and the coffee grounds left
behind can be thrown on the garden.
Example
def odd(n):
return n%2 == 1
print(list(filter(odd,range(10))))
Output
[1, 3, 5, 7, 9]
This uses odd function as the predicate
The predicate checks whether the number is odd
So, only odd numbers will be there in the list
Reducing
Our final example of a higher-order function is called a reducing. Here we take a list of
values and repeatedly apply a function to accumulate a single data value.
A summation is a good example of this process. The first value is added to the second
value, then the sum is added to the third value, and so on, until the sum of all the values is
produced.
Example
def add(x,y)
return x+y
def multiply(x,y):
return x * y
data = [1,2,3,4]
print(reduce(add,data))
print(reduce(multiply,data))
Output
10
24
5. Lambda Functions
What is Lambda function?
A lambda is an anonymous function. It has no name of its own, but contains the names of
its arguments as well as a single expression.
When the lambda is applied to its arguments, its expression is evaluated, and its value is
returned.
Example
Example-1
z = lambda x,y:x+y
print(z(2,3))
Example-2
def myfunc(n):
return lambda a:a*n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
6. List
What is a List?
A list is a sequence of data values called items or elements. An item can be of any type.
Each of the items in a list is ordered by position.
Each item in a list has a unique index that specifies its position.
The index of the first item is 0, and the index of the last item is the length of the list minus
1.
In Python, a list is written as a sequence of data values separated by commas. The entire
sequence is enclosed in square brackets [ ] .
Example
List methods
7. Set
What is a set?
A set is a collection which is unordered and un-indexed. In Python, sets are written with
curly brackets { }
Sets are unordered, so you cannot be sure in which order the items will appear.
Accessing Items: You cannot access items in a set by referring to an index or a key.
Example
thisset = {"apple","banana","cherry"}
print(thisset)
Set Methods
Add items
To add one item to a set use the add() method. To add more than one item to a set use the
update() method.
# add() method
thisset = {"apple","banana","cherry"}
[Link]("orange")
print(thisset)
#Update() method
thisset = {"apple","banana","cherry"}
[Link](["orange","mango","grapes"])
print(thisset)
Output
Length of a set
Remove item
Other methods
8. Tuples
What is a tuple?
A tuple is a type of sequence that resembles a list, except that, unlike a list, a tuple is
immutable.(It cannot be modified)
You indicate a tuple in Python by enclosing its elements in parentheses ( ) instead of
square brackets [ ] .
Example
fruits = ("apple","banana")
Benefits of tuple?
9. Dictionaries
What is a dictionary?
Example
shop = {"pen":12,"paper":100}
info = {}
info["name"] = "Sandy"
info["occupation"] = "hacker"
print(info)
Output
{'name':Sandy,'occupation':'hacker'}
Accessing Values
>>> info["name"]
'Sandy'
Removing keys
[Link]("job")
Python-Module-2-University-Questions-
Part-A
1. Write Python code for the following statements
i)writes the text ”PROGRAMMING IN PYTHON” to a file with name [Link]
ii) then reads the text again and prints it to the screen
def write_and_read_text():
"""Writes text to a file and then reads it back, printing it to the
screen."""
# Text to write
text = "PROGRAMMING IN PYTHON"
Args:
a: The first non-negative integer.
b: The second non-negative integer.
Returns:
The GCD of a and b.
"""
# Example usage
result = gcd(12, 18)
print(f"The GCD of 12 and 18 is: {result}")
5. Differentiate between lists and tuples with the help of
examples
Lists and tuples are both fundamental data structures in Python used to store collections
of elements, but they differ in their mutability:
Mutability:
- Lists: Mutable - elements can be added, removed, or changed after creation.
- Tuples: Immutable - elements cannot be modified after creation.
Example
def is_palindrome(text):
"""
Checks if a given text is a palindrome (reads the same backward as
forward).
Args:
text: The text to be checked.
Returns:
True if the text is a palindrome, False otherwise.
"""
# Convert to lowercase and remove non-alphanumeric characters
return text == text[::-1]
def find_palindromes(text):
"""
Finds all palindromes in a line of text and prints them.
Args:
text: The line of text to search for palindromes.
"""
words = [Link]()
for word in words:
if is_palindrome(word):
print(word)
# Example usage
text = "level madam, i am adam."
find_palindromes(text)
{:s} - Strings
name = "Alice"
age = 30
print(f"Hello, my name is {name} and I am {age} years old.")
Escape Sequences:
Special sequences of characters that represent non-printable characters or modify how a
string is displayed.
Start with a backslash ( \ ) followed by another character.
Common examples:
\n - Newline character (inserts a line break)
\t - Horizontal tab
Example
Python-Module-2-University-Question-
Part-B
1. Write a Python program to implement Caesar cipher
encryption and decryption on a string of lowercase letters.
Take distance value and the string as input.
(Hint: Caesar cipher encryption strategy replaces each character in the plaintext with the
character that occurs a given distance away in the sequence.
Encryption:Eg. input: 3, “invade”, Eg. output: “lqydgh”
Decryption: Eg. input: 3, “lqydgh”, Eg. output: “invade”)
# Encrypt
plainText = input("Enter word")
distance = int(input("Enter distance value"))
code = ""
for ch in plainText:
ordvalue = ord(ch)
cipherValue = ordvalue + distance
if cipherValue > ord('z'):
cipherValue = ord('a') + distance - (ord('z') - ordvalue +
1)
code+=chr(cipherValue)
print(code)
#Decrypt
code = input("Enter text")
distance = int(input("Enter distance"))
plainText = ""
for ch in code:
ordvalue = ord(ch)
cipherValue = ordvalue - distance
if cipherValue < ord('a'):
cipherValue = ord('z') - (distance - ord('a')-ordvalue - 1)
plainText += chr(cipherValue)
print(plainText)
def count_four_letter_words(filename):
"""
Counts the number of four-letter words in a given file.
Args:
filename: The name of the file to read.
"""
count = 0
try:
with open(filename, 'r') as file:
for line in file:
words = [Link]()
for word in words:
# Check if word has 4 letters and is alphabetic (only letters)
if len(word) == 4 and [Link]():
count += 1
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
# Example usage
filename = "your_file.txt" # Replace with your actual filename
count_four_letter_words(filename)
def calculate_mean(numbers):
"""
Calculates the mean (average) of a list of numbers.
Args:
numbers: A list of numbers.
Returns:
The mean of the list, or 0 if the list is empty.
"""
if not numbers:
return 0
def calculate_median(numbers):
"""
Calculates the median of a list of numbers.
Args:
numbers: A list of numbers (assumed to be sortable).
Returns:
The median of the list, or 0 if the list is empty.
"""
if not numbers:
return 0
if len(sorted_numbers) % 2 == 0:
# Even number of elements, calculate average of middle two
return (sorted_numbers[midpoint - 1] + sorted_numbers[midpoint]) / 2
else:
# Odd number of elements, return middle element
return sorted_numbers[midpoint]
def calculate_mode(numbers):
"""
Calculates the mode (most frequent value) of a list of numbers.
Args:
numbers: A list of numbers.
Returns:
The mode of the list, or 0 if the list is empty or all elements are
unique.
"""
if not numbers:
return 0
if __name__ == "__main__":
main()
Args:
my_list: The main list to search.
sub_list: The sublist to be found.
Returns:
True if the sub_list is found within my_list, False otherwise.
"""
def calculate_median(numbers):
"""
Calculates the median of a list of numbers without using standard
functions.
Args:
numbers: A list of numbers.
Returns:
The median of the list.
"""
if length % 2 == 0:
# Even number of elements, calculate average of middle two
midpoint = length // 2
return (sorted_numbers[midpoint - 1] + sorted_numbers[midpoint]) / 2
else:
# Odd number of elements, return middle element
midpoint = length // 2
return sorted_numbers[midpoint]
def read_numbers_from_file(filename):
"""
Reads a list of numbers from a text file.
Args:
filename: The name of the text file.
Returns:
A list of numbers from the file, or an empty list if the file cannot
be read.
"""
numbers = []
try:
with open(filename, 'r') as file:
for line in file:
# Convert each line to a float (assuming numerical data)
number = float([Link]())
[Link](number)
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return numbers
# Example usage
filename = "[Link]"
numbers = read_numbers_from_file(filename)
if numbers:
median = calculate_median(numbers)
print(f"Median of numbers in '{filename}': {median}")
else:
print(f"Error: No numbers found in '{filename}'.")
def decimal_to_binary(decimal_number):
"""
Converts a decimal number to its binary equivalent.
Args:
decimal_number: An integer representing the decimal number.
Returns:
The binary equivalent of the decimal number as a string,
or "0" if the input is 0.
"""
if decimal_number == 0:
return "0"
binary_string = ""
while decimal_number > 0:
remainder = decimal_number % 2 # Get the remainder after division by 2
(binary digit)
binary_string = str(remainder) + binary_string # Prepend the remainder
to the string
decimal_number //= 2 # Divide the decimal number by 2 for the next
iteration
return binary_string
# Example usage
decimal_number = 10
binary_equivalent = decimal_to_binary(decimal_number)
print(f"{decimal_number} in binary: {binary_equivalent}") # Output: 10 in
binary: 1010
def count_char_occurrences(filename):
"""
Counts the occurrences of each character in a text file and stores them in
a dictionary.
Args:
filename: The name of the text file to read.
Returns:
A dictionary where the keys are characters and the values are their
counts.
"""
char_counts = {}
with open(filename, 'r') as file:
for line in file:
for char in line:
if char in char_counts:
char_counts[char] += 1
else:
char_counts[char] = 1
return char_counts
print("Character counts:")
for char, count in char_counts.items():
print(f"{char}: {count}")
def list_of_frequency(text):
"""
Prints the letters in a string from most frequent to least frequent.
Args:
text: The string to analyze.
"""
# Sort the list by the count (second element in each tuple), highest first
letter_and_counts.sort(key=lambda item: item[1], reverse=True)
# Example usage
text = "Mississippi"
list_of_frequency(text)
def sort_list(numbers):
"""
Sorts a list of numbers in increasing order.
Args:
numbers: The list of numbers to sort.
Returns:
The sorted list.
"""
return numbers
def main():
"""
Gets numbers from the user, sorts them, and prints the result.
"""
numbers = []
while True:
# Get a single number as input (assumes valid input)
num_str = input("Enter a number (or press Enter to finish): ")
# Check if user pressed Enter only
if not num_str:
break
[Link](float(num_str))
if not numbers:
print("No numbers entered.")
else:
# Sort the list using the sort_list function
sorted_numbers = sort_list([Link]()) # Avoid modifying the
original list
print("Sorted list:", sorted_numbers)
if __name__ == "__main__":
main()
12. Illustrate the following Set methods with an example.
i. intersection( ) ii. Union( ) iii. Issubset( ) iv. Difference( ) v. update( ) vi.
discard()
1. intersection()
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4, 6, 8}
intersection = [Link](set2)
print("Intersection:", intersection) # Output: Intersection: {2, 4}
2. union()
Returns a new set with elements from both sets (without duplicates).
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4, 6, 8}
union = [Link](set2)
print("Union:", union) # Output: Union: {1, 2, 3, 4, 5, 6, 8}
3. issubset()
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
is_subset = [Link](set2)
print("Is set1 subset of set2:", is_subset) # Output: Is set1 subset of
set2: True
4. difference()
difference = [Link](set2)
print("Difference:", difference) # Output: Difference: {1, 3, 5}
5. update()
set1 = {1, 2, 3}
set2 = {4, 5, 6}
[Link](set2)
print("set1 after update:", set1) # Output: set1 after update: {1, 2, 3, 4,
5, 6}
6. discard()
set1 = {1, 2, 3, 4}
[Link](2)
print("set1 after discard:", set1) # Output: set1 after discard: {1, 3, 4}
def is_valid_password(password):
"""
Checks if a password meets the following criteria:
Args:
password: The password string to validate.
Returns:
True if the password is valid, False otherwise.
"""
has_lowercase = False
has_uppercase = False
has_digit = False
has_special_char = False
def main():
"""
Prompts the user for a password and checks its validity.
"""
if __name__ == "__main__":
main()
birthdays = {
"Alice": "Jan 1, 2000",
"Bob": "Feb 14, 1990",
"Charlie": "March 3, 1985"
}
def find_birthday(name):
"""
Finds the birthday of a person in the dictionary.
Args:
name: The name of the person to search for.
Returns:
The birthday of the person if found, otherwise None.
"""
if name in birthdays:
return birthdays[name]
else:
return None
while True:
# Get user input for a name
name = input("Enter a name (or 'quit' to exit): ")