0% found this document useful (0 votes)
3 views18 pages

Python Chit

The document outlines significant features of Python programming, including its simple syntax, dynamic typing, and support for various data types. It also explains math operators in Python, their precedence, and provides examples of control statements like if, else, and break. Additionally, it covers user-defined functions, local and global scope, dictionaries, and list operations with corresponding Python code examples.

Uploaded by

aparnadesai757
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

Python Chit

The document outlines significant features of Python programming, including its simple syntax, dynamic typing, and support for various data types. It also explains math operators in Python, their precedence, and provides examples of control statements like if, else, and break. Additionally, it covers user-defined functions, local and global scope, dictionaries, and list operations with corresponding Python code examples.

Uploaded by

aparnadesai757
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.1.a.

List and explain the significant Math Operators in Python from Highest to
features of Python Programming Language. Lowest Precedence
1. Simple and Readable SyntaxFeature: 1. ** (Exponen a on)
Python’s syntax is clear and easy to read, o Example: 2 ** 3 evaluates to 8
resembling plain English. 2. *, /, //, % (Mul plica on, Division,
2. Dynamic TypingFeature: Python uses Floor Division, Modulus)
dynamic typing, meaning variable types are o Example: 4 * 3 evaluates to 12
determined at run me. 3. Interpreted o Example: 10 / 2 evaluates to 5.0
LanguageFeature: Python is an o Example: 10 // 3 evaluates to 3
interpreted language, which means code is o Example: 10 % 3 evaluates to 1
executed line by line. 4. Object-Oriented 3. +, - (Addi on, Subtrac on)
Programming (OOP)Feature: Python o Example: 5 + 2 evaluates to 7
supports OOP principles such as classes, o Example: 5 - 2 evaluates to 3
objects, inheritance, and encapsula on. Steps to Evaluate the Expression (5 - 1) * ((7
5. Func ons and ParametersFeature: + 1) / (3 - 1))
Python allows defining and calling func ons 1. Evaluate the innermost parentheses:
with parameters. 6. Built-in Func ons and o 7 + 1 evaluates to 8
LibrariesFeature: Python comes with a o 3 - 1 evaluates to 2
rich standard library and many built-in The expression now looks like: (5 - 1) * (8 /
func ons like print(), len(), etc. 7. Support 2)
for Various Data TypesFeature: Python 2. Evaluate the division inside the
supports several data types including parentheses:
integers, floats, strings, lists, tuples, o 8 / 2 evaluates to 4.0
dic onaries, and sets. 8. Easy The expression now looks like: (5 - 1) * 4.0
Integra onFeature: Python can easily 3. Evaluate the subtrac on inside the
integrate with other languages and parentheses:
technologies, including C/C++, Java, and web o 5 - 1 evaluates to 4
technologies,tes ng. 9 Interac ve The expression now looks like: 4 * 4.0
ShellFeature: Python offers an interac ve 4. Evaluate the mul plica on:
shell (REPL) for immediate code execu on. o 4 * 4.0 evaluates to 16.0
10 Cross-Pla orm Compa bility Feature: Therefore, the final result of (5 - 1) * ((7 + 1)
Python is cross-pla orm and runs on various / (3 - 1)) is 16.0.
opera ng systems like Windows, macOS,
and Linux. [Link] Community and 1.2.c. Explain the local and global scope of
EcosystemFeature: Python has a large and the variable with a suitable example.
ac ve community, with numerous third- Local Scope:Variables defined inside a
party libraries and frameworks available. func on.Only accessible within that
func on.Created when the func on is
1.1.c. Write the math operators in Python called and destroyed when the func on
from highest to lowest Precedence with an finishes.
example for each. Write the steps how Global Scope:Variables defined outside all
Python is evalua ng the expression (5 - 1) * func ons.Accessible from any part of the
((7 + 1) / (3 - 1)) and reduces it to a single program.
value.
Local scope Example: elif condi on2:
def my_func on(): # code to execute if condi on1 is False
local_var = 10 # local variable and condi on2 is True
print(local_var) # This will print 10 Example:
my_func on() name = 'Carol'
print(local_var) # This will cause an error age = 3000
because local_var is not accessible outside if name == 'Alice':
the func on print('Hi, Alice.')
Global Scope Example: elif age < 12:
global_var = 20 # global variable print('You are not Alice, kiddo.')
def my_func on(): elif age > 2000:
print(global_var) # This will print 20 print('Unlike you, Alice is not an undead,
my_func on() immortal vampire.')
print(global_var) # This will also print 20 4. `break` Statement:
Syntax:
2.1.b. With proper syntax with example, while True:
explain the control statements (1) If (2) else # code
(3) elif (4) break statement. if condi on:
Control Statements in Python break
1. `if` Statement: Example:
Syntax: while True:
if condi on: name = input('Please type your name: ')
# code to execute if condi on is True if name == 'your name':
Example: break
name = 'Alice' print('Try again.')
if name == 'Alice': print('Thank you!')
print('Hi, Alice.')
2. `else` Statement: 1.2.b. Write a program to find the factorial
Syntax: of a number using a func on.
if condi on: Here's a Python program that defines a
# code to execute if condi on is True func on to find the factorial of a number:
else: def factorial(n):
# code to execute if condi on is False if n == 0:
Example: return 1
name = 'Bob' else:
if name == 'Alice': return n * factorial(n-1)
print('Hi, Alice.') # Example usage:
else: number = 5
print('Hello, stranger.') result = factorial(number)
3. `elif` Statement: print(f'The factorial of {number} is {result}')
Syntax: Output:
if condi on1: The factorial of 5 is 120
# code to execute if condi on1 is True
2.2.c. Develop a program to read the the Fibonacci numbers and then use this
student details like Name, USN and Marks func on to print the first N Fibonacci
in three subjects. Display the student numbers. Here is the modified program:
details, total marks and percentage with # Define the Fibonacci func on
suitable messages. def F(n):
# Read student details if n == 0:
name = input("Enter student's name: ") return 0
usn = input("Enter student's USN: ") elif n == 1:
# Ini alize marks for three subjects return 1
marks = [0, 0, 0] else:
# Input marks for each subject return F(n-1) + F(n-2)
for i in range(3): # Generate and print the first N Fibonacci
marks[i] = int(input(f"Enter marks for numbers
subject {i + 1}: ")) def generate_fibonacci(n):
# Calculate total marks for i in range(n):
total_marks = marks[0] + marks[1] + print(F(i))
marks[2] # Example usage:
# Calculate percentage N = 10
percentage = (total_marks / 300) * 100 # generate_fibonacci(N)
Assuming each subject is out of 100 marks output:0 1 1 2 3 5 8
# Display student details and results
print("\nStudent Details:") 2.2.b. What are user-defined func ons?
print(f"Name: {name}") How can we pass parameters in user-
print(f"USN: {usn}") defined func ons? Explain with a suitable
for i in range(3): example. User-defined func ons are
print(f"Marks in subject {i + 1}: {marks[i]}") func ons created by the programmer using
print(f"Total Marks: {total_marks}") the def keyword in Python. These func ons
print(f"Percentage: {percentage:.2f}%") can perform specific tasks and can be reused
Output: throughout the code. They are defined by
Enter student's name: Aditya specifying a func on name, any parameters
Enter student's USN: EC009 it takes, and a block of code that defines
Enter marks for subject 1: 90 what the func on does. To pass parameters
Enter marks for subject 2: 80 in user-defined func ons, you include them
Enter marks for subject 3: 70 in the parentheses a er the func on name
during the func on defini on. When the
2.1.c. Define a Python func on with func on is called, arguments corresponding
suitable parameters to generate first N to these parameters are provided, allowing
Fibonacci numbers. The first two Fibonacci the func on to operate on the passed
numbers are 0 and 1 and the Fibonacci values.
sequence is defined as a func on F as Fn = Example
Fn-1 + Fn-2. def greet(name):
To define the Fibonacci sequence as a print('Hello, ' + name)
func on F where F(n)=F(n−1)+F(n−2) , we greet('Alice')
can create a recursive func on to calculate greet('Bob')
MODULE2 char_count = {}
1.4.b. What is a dic onary? How it is # Iterate over each character in the string
different from List? Write a program to for char in s:
count the number of occurrences of # Increment the count for the character
characters in a string. in the dic onary
A dic onary is a mutable collec on of key- if char in char_count:
value pairs. Each key is unique and is used to char_count[char] += 1
access its corresponding value. Dic onaries else:
are defined using curly braces {}. For char_count[char] = 1
example: return char_count
myCat = {'size': 'fat', 'color': 'gray', # Example usage
'disposi on': 'loud'} input_string = "hello world"
n this dic onary, 'size', 'color', and result = count_characters(input_string)
'disposi on' are keys, and 'fat', 'gray', and print(result)
'loud' are their associated values. Example Output:
How is it Different from a List? {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd':
Syntax:Dic onary: Uses curly braces {} 1}
and key-value pairs. Example: {'key1':
'value1', 'key2': 'value2'} 2.3.b. Describe any two list opera ons and
List: Uses square brackets [] and indexed list methods. Write a Python program to
elements. Example: ['item1', 'item2'] accept ‘n’ numbers from the user. Find the
Indexing:Dic onary: Uses keys (which can sum of all even numbers and the product of
be of any immutable type, such as strings or all odd numbers in the entered list.
numbers) to access values. The keys are not List Opera ons and Methods
ordered. List Opera ons:
List: Uses integer indices star ng from 0 to 1. Indexing: Access individual elements
access elements. Lists are ordered. of a list using their index. Indexing
Ordering:Dic onary: Unordered in starts at 0. For example, spam[0]
versions prior to Python 3.7. From Python returns the first element of the list.
3.7 onwards, dic onaries remember the 2. Slicing: Retrieve a part of a list using a
inser on order of key-value pairs. slice. For example, spam[1:3] returns
List: Ordered. The order of elements ma ers a sublist from index 1 to 2.
and is maintained. List Methods:
Mutability:Both: Dic onaries and lists are 1. append(): Adds an item to the end of
mutable, meaning their contents can be the [Link] = [1, 2, 3]
changed. [Link](4) # spam becomes [1, 2, 3, 4]
Program to Count the Number of 2. remove(): Removes the first
Occurrences of Characters in a String occurrence of a specified value from
Here's a Python program that counts the the [Link] = [1, 2, 3, 4]
occurrences of each character in a string [Link](2) # spam becomes [1, 3, 4]
using a dic onary:
def count_characters(s):
# Create an empty dic onary to store
character count
Python Program (1, 2) < (1, 2, 3) # True, because (1, 2) is
# Ini alize variables shorter than (1, 2, 3)
sum_even = 0 (1, 2, 3) == (1, 2, 3) # True, because all
product_odd = 1 elements are the same
has_odd = False (1, 2, 3) > (1, 2, 2) # True, because 3 > 2
# Get the number of elements Working of sort() Func on
n = int(input("Enter the number of elements: The sort() method sorts the list in place. It
")) does not return a new list but rather
# Read numbers and process them modifies the original list. Here's a summary
for _ in range(n): of its behavior:
num = int(input("Enter a number: ")) 1. Sorts in Ascending Order: By default,
if num % 2 == 0: it sorts values from smallest to largest.
sum_even += num 2. Sorts in Place: Modifies the original
else: list.
product_odd *= num 3. Sor ng Mixed Types: Cannot sort lists
has_odd = True with mixed data types (e.g., integers
# Display results and strings).
print("Sum of all even numbers:", 4. Reverse Order: You can pass
sum_even) reverse=True to sort in descending
if has_odd: order.
print("Product of all odd numbers:", 5. Custom Sor ng: You can pass a key
product_odd) func on to determine the sort order.
else: 1) Examples: [Link] Sor ng:
print("No odd numbers entered.") spam = [2, 5, 3.14, 1, -7]
[Link]()
.4.b. Explain the concept of comparing print(spam) # Output: [-7, 1, 2, 3.14, 5]
tuples. Describe the working of sort 2) Sor ng Strings:
func on with python code. spam = ['ants', 'cats', 'dogs', 'badgers',
Comparing Tuples 'elephants']
Tuples are compared lexicographically in [Link]()
Python. This means that tuples are print(spam) # Output: ['ants', 'badgers',
compared element by element, from le to 'cats', 'dogs', 'elephants']
right. The comparison stops as soon as a 3) Sor ng in Reverse Order:
difference is found: [Link](reverse=True)
 If the elements at the current index print(spam) # Output: ['elephants', 'dogs',
are different, the tuple with the 'cats', 'badgers', 'ants']
smaller element at that index is 4) Handling Mixed Types:
considered smaller. spam = [1, 3, 2, 4, 'Alice', 'Bob']
 If all elements are equal up to the [Link]() # Raises TypeError: '<' not
length of the shorter tuple, the supported between instances of 'str' and
shorter tuple is considered smaller. 'int' 5Sor ng with key Argument:
For example: spam = ['a', 'z', 'A', 'Z']
(1, 2, 3) < (1, 2, 4) # True, because 3 < 4 [Link](key=[Link])
print(spam) # Output: ['a', 'A', 'z', 'Z']
1.3.a. What is a list? Explain the concept of print(spam) # Output: ['cat', 'bat',
list slicing and list traversing with an 'elephant']
example. 2. remove() Method
List in Python The remove() method removes the first
A list in Python is a collec on of items that occurrence of a specified value from the list.
can be of different data types. Lists are Example:
ordered and mutable (modifiable), and they spam = ['cat', 'bat', 'rat', 'elephant']
are defined by placing items inside square [Link]('bat')
brackets [], separated by commas. print(spam) # Output: ['cat', 'rat', 'elephant']
List Slicing
List slicing allows you to create a new list2.3.c. When do we encounter TypeError
from an exis ng list by specifying a range of
and ValueError and IndexError while
indices. The syntax for list slicing is: opera ng on Lists?
list[start:stop:step] Errors Encountered While Opera ng on
 start: the star ng index (inclusive). Lists
 stop: the ending index (exclusive). 1. TypeError: This error occurs when you
 step: the interval between indices. use a non-integer value (such as a
Example of List Slicing: float) as an index for a list. For
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] example:
# Slicing from index 2 to 5 spam = ['cat', 'bat', 'rat', 'elephant']
slice1 = numbers[2:6] # Output: [2, 3, 4, 5]spam[1.0] # This raises TypeError: list
# Slicing from the beginning to index 4 indices must be integers or slices, not float
slice2 = numbers[:5] # Output: [0, 1, 2, 3, 4] 2. ValueError: This error does not
List Traversing specifically apply to list opera ons in
List traversing is the process of accessing the provided context. Typically, a
each element of a list, typically using a loop. ValueError occurs when a func on
Example of List Traversing: receives an argument of the right type
fruits = ["apple", "banana", "cherry"] but inappropriate value, which is not
# Using a for loop to traverse the list directly related to list indexing.
for fruit in fruits: 3. IndexError: This error occurs when
print(fruit) you use an index that exceeds the
number of elements in the list. For
2.4.a. What are the different ways of example:
dele ng elements from a list? Discuss with spam = ['cat', 'bat', 'rat', 'elephant']
suitable func ons. spam[10000] # This raises IndexError: list
There are two primary methods to delete index out of range
items from a list in Python:
1. del Statement 2.4.b. Explain the concept of comparing
The del statement is used to delete an item tuples. Describe the working of sort
at a specific index. All values a er the func on with python code.
deleted item are moved up one index. Comparing Tuples
Example: Tuples are compared lexicographically in
spam = ['cat', 'bat', 'rat', 'elephant'] Python. This means that tuples are
del spam[2] compared element by element, from le to
right. The comparison stops as soon as a 1. Sor ng in Reverse Order:
difference is found: [Link](reverse=True)
 If the elements at the current index print(spam) # Output: ['elephants', 'dogs',
are different, the tuple with the 'cats', 'badgers', 'ants']
smaller element at that index is 2. Handling Mixed Types:
considered smaller. spam = [1, 3, 2, 4, 'Alice', 'Bob']
 If all elements are equal up to the [Link]() # Raises TypeError: '<' not
length of the shorter tuple, the supported between instances of 'str' and
shorter tuple is considered smaller. 'int'
For example: 3. Sor ng with key Argument:
(1, 2, 3) < (1, 2, 4) # True, because 3 < 4 spam = ['a', 'z', 'A', 'Z']
(1, 2) < (1, 2, 3) # True, because (1, 2) is [Link](key=[Link])
shorter than (1, 2, 3) print(spam) # Output: ['a', 'A', 'z', 'Z']
(1, 2, 3) == (1, 2, 3) # True, because all
elements are the same 1.3.c. For the following three ques ons,
(1, 2, 3) > (1, 2, 2) # True, because 3 > 2 let’s say spam contains the list ['a','b', 'c',
Working of sort() Func on 'd',[3,4]].
The sort() method sorts the list in place. It i. What does spam[int('3' * 2) / 11]
does not return a new list but rather evaluate to?
modifies the original list. Here's a summary ii. What does spam[-2] evaluate to?
of its behavior: iii. What does spam[4][1] evaluate to?
1. Sorts in Ascending Order: By default, i. What does spam[int('3' * 2) / 11] evaluate
it sorts values from smallest to largest. to?
2. Sorts in Place: Modifies the original 1. Understanding int('3' * 2):
list. o '3' * 2 results in '33', which is
3. Sor ng Mixed Types: Cannot sort lists the string '33'.
with mixed data types (e.g., integers o int('33') converts the string '33'
and strings). to the integer 33.
4. Reverse Order: You can pass 2. Calcula ng 33 / 11:
reverse=True to sort in descending o 33 / 11 results in 3.0 (a float).
order. 3. Using spam[3.0]:
5. Custom Sor ng: You can pass a key o List indices must be integers,
func on to determine the sort order. not floats, so spam[3.0] will
Examples: raise a TypeError.
1. Basic Sor ng: Answer: spam[int('3' * 2) / 11] raises a
spam = [2, 5, 3.14, 1, -7] TypeError because list indices must be
[Link]() integers.
print(spam) # Output: [-7, 1, 2, 3.14, 5] ii. What does spam[-2] evaluate to?
2. Sor ng Strings:  Nega ve Indexing:
spam = ['ants', 'cats', 'dogs', 'badgers', o spam[-2] accesses the second-
'elephants'] to-last element of the list spam.
[Link]() Result: spam[-2] evaluates to 'd'.
print(spam) # Output: ['ants', 'badgers', iii. What does spam[4][1] evaluate to?
'cats', 'dogs', 'elephants'] 1. Understanding spam[4]:
o spam[4] gives the value at index num = int(input("Enter a number: "))
4, which is [3, 4]. if num % 2 == 0:
2. Accessing Element [3, 4][1]: sum_even += num
[3, 4][1] refers to the element at index 1 of else:
the list [3, 4], which is4. Answer: product_odd *= num
spam[4][1] evaluates to 4. has_odd = True
# Display results
2.3.b. Describe any two list opera ons and print("Sum of all even numbers:",
list methods. Write a Python program to sum_even)
accept ‘n’ numbers from the user. Find the if has_odd:
sum of all even numbers and the product of print("Product of all odd numbers:",
all odd numbers in the entered list. product_odd)
List Opera ons and Methods else:
List Opera ons: print("No odd numbers entered.")
1. Indexing: Access individual elements
of a list using their index. Indexing 2.4.c. List merits of dic onary over list.
starts at 0. For example, spam[0] Merits of Dic onary Over List
returns the first element of the list. 1. Key-Value Pairs: Dic onaries store
2. Slicing: Retrieve a part of a list using a data as key-value pairs, making data
slice. For example, spam[1:3] returns retrieval based on a unique key
a sublist from index 1 to 2. efficient. Lists only store values and
List Methods: require searching through the en re
1. append(): Adds an item to the end of list to find an item.
the list. 2. Fast Lookup: Dic onaries provide
spam = [1, 2, 3] average O(1) me complexity for
[Link](4) # spam becomes [1, 2, 3, 4] lookups, inser ons, and dele ons
2. remove(): Removes the first based on keys. Lists require O(n) me
occurrence of a specified value from complexity for these opera ons
the list. because you need to search through
spam = [1, 2, 3, 4] the list.
[Link](2) # spam becomes [1, 3, 4] 3. Unordered Collec ons: Dic onaries
Python Program are inherently unordered, which
Here is a Python program that accepts n allows for more flexibility in data
numbers from the user, calculates the sum storage and retrieval. Lists maintain
of even numbers, and the product of odd the order of elements, which can be a
numbers: limita on if order is not important.
# Ini alize variables 4. Flexible Keys: Dic onaries use
sum_even = 0 immutable types (like strings or
product_odd = 1 numbers) as keys, allowing for more
has_odd = False complex data structures and easy
# Get the number of elements access by a meaningful key. Lists only
n = int(input("Enter the number of elements: use integer indexing, which may not
"))# Read numbers and process them be as intui ve.
for _ in range(n):
MODULE 3 Define your character set within square
2.5.a. Explain the basic steps for crea ng brackets: Include the specific characters or
and finding regular expression objects with ranges you want to match.
Python. vowelRegex = [Link](r'[aeiouAEIOU]')
The basic steps for crea ng and finding Use hyphens for ranges: Include ranges of
regular expression objects with Python are: le ers or numbers.
Import the regex module: Use import re. alphanumericRegex = [Link](r'[a-zA-Z0-
import re 9]') Create nega ve character
Create a Regex object: Use [Link]() classes with a caret (^): Place a caret
with your regular expression pa ern. immediately a er the opening bracket to
phoneNumRegex = [Link](r'\d\d\d- match characters not in the set.
\d\d\d-\d\d\d\d') consonantRegex =
Search for the pa ern in a string: Call [Link](r'[^aeiouAEIOU]')
search() on the Regex object with the string Example Outputs and Explana on
you want to search. This returns a Match import re
object if the pa ern is found or None if it is # Define character classes
not. vowelRegex = [Link](r'[aeiouAEIOU]')
mo = [Link]('My number print(vowelRegex.findall('RoboCop eats
is 415-555-4242.') baby food. BABY FOOD.'))
Retrieve the matched text: Use group() Output:
on the Match object to get the actual ['o', 'o', 'o', 'e', 'a', 'a', 'o', 'o', 'A', 'O', 'O']
matched text.
print('Phone number found: ' + [Link]()) 2.6.b. Explain the concept of file path. Also
discuss absolute and rela ve file path.
2.5.b. List shorthand codes for common Concept of File Path
character classes. Brief out the step A file path is a string that specifies the
involved in to making your own character loca on of a file or directory on a computer.
classes. It includes two key components:
Shorthand Codes for Common Character 1. Filename: The name of the file, o en
Classes including an extension (e.g.,
 \d: Any numeric digit from 0 to 9. [Link]).
 \D: Any character that is not a 2. Path: The sequence of directories
numeric digit from 0 to 9. leading to the file.
 \w: Any le er, numeric digit, or the For example, in the path
underscore character. C:\Users\Al\Documents\[Link]:
 \W: Any character that is not a le er,  C:\ is the root folder.
numeric digit, or the underscore  Users, Al, and Documents are
character. directories.
 \s: Any space, tab, or newline  [Link] is the filename.
character. Absolute vs. Rela ve File Path
 \S: Any character that is not a space, Absolute Path
tab, or newline. An absolute path specifies the complete
Steps to Make Your Own Character Classes loca on of a file or directory from the root
folder. It always begins with the root folder:
 On Windows: if text[3] != '-':
C:\Users\Al\Documents\[Link] return False
 On macOS/Linux: if not text[4:7].isdigit():
/Users/Al/Documents/[Link] return False
An absolute path provides the full path, if text[7] != '-':
making it independent of the current return False
working directory. if not text[8:].isdigit():
Rela ve Path A rela ve path specifies the return False
loca on of a file or directory rela ve to the return True
current working directory. It does not begin # Example usage
with the root folder: print('415-555-4242 is a phone number:')
If the current working directory is print(isPhoneNumber('415-555-4242'))
C:\Users\Al, the rela ve path to [Link] print('Moshi moshi is a phone number:')
in Documents is Documents\[Link]. print(isPhoneNumber('Moshi moshi'))
Special nota ons in rela ve paths:
o . refers to the current directory. 1.5.b. With example, explain the following
o .. refers to the parent directory. Pa ern Matching with Regular Expressions.
For example: Pa ern Matching with Regular Expressions
.\[Link] refers to [Link] in (1) Grouping with Parentheses
the current directory. Grouping in regular expressions allows you
..\Documents\[Link] refers to to capture and isolate specific parts of a
[Link] in the Documents directory, pa ern. This is done using parentheses ().
which is a sibling to the current directory. Example: Extrac ng Area Code and Main
Number Suppose you want to separate the
1.5.a. Explain the finding pa erns of text area code from the rest of a phone number.
without regular expressions with example. You can use parentheses to create groups:
Finding Pa erns of Text Without Using Regex Pa ern:
Regular Expressions (\d\d\d)-(\d\d\d-\d\d\d\d)
Pa ern matching without using regular Here, (\d\d\d) captures the area code, and
expressions involves using basic string (\d\d\d-\d\d\d\d) captures the main
opera ons to search for specific sequences number.
of characters. This approach is more Code: import re
straigh orward for simpler pa erns but can phoneNumRegex = [Link](r'(\d{3})-
become cumbersome for complex pa erns. (\d{3}-\d{4})')
Example: Finding a Phone Number mo = [Link]('My number
We'll write a func on isPhoneNumber() that is 415-555-4242.')
checks whether a string matches the pa ern print('Area code:', [Link](1))
of a phone number (e.g., '415-555-4242'). print('Main number:', [Link](2))
Code def isPhoneNumber(text): print('Full number:', [Link](0))(ii)
if len(text) != 12: Matching Mul ple Groups with the Pipe
return False The pipe | allows you to match one of
if not text[:3].isdigit(): several possible pa erns. It acts like a logical
return False OR.
Example: Matching Different Hero Names 1.6.c. Explain reading and saving python
Regex Pa ern: program variables with the
Batman|Tina Fey [Link]() Func on.
This pa ern matches either 'Batman' or To save Python program variables with the
'Tina Fey'. [Link]() func on, follow these
Code: import re steps: Import pprint: This module
heroRegex = [Link](r'Batman|Tina Fey') provides the pformat() func on, which
mo1 = [Link]('Batman and Tina formats data as a readable string. Use
Fey') [Link](): Convert the variable (e.g.,
mo2 = [Link]('Tina Fey and a list or dic onary) into a forma ed string.
Batman') This string is readable and syntac cally
print('First match:', [Link]()) correct Python code. Write to a .py file:
print('Second match:', [Link]()) Open a file in write mode, and write the
forma ed string to it. This file will be a
1.5.a. Explain with suitable Python program Python module. Import and use the
segments. (i) [Link]() module: A er saving the file, you can import
Func on: [Link](path) returns it as a module in your scripts to access the
the base name of the file or directory from saved variable. Example: 
the given path. Essen ally, it strips the import pprint
directory path and returns only the last part, # Your variable
which is the name of the file or directory. cats = [{'name': 'Zophie', 'desc': 'chubby'},
Example: import os {'name': 'Pooka', 'desc': 'fluffy'}]
calcFilePath = # Convert to a forma ed string
'C:\\Windows\\System32\\[Link]' forma ed_string = [Link](cats)
base_name = # Save to a .py file
[Link](calcFilePath) with open('[Link]', 'w') as fileObj:
print(base_name) # Output: '[Link]' fi[Link]('cats = ' + forma ed_string +
In this example, '\n')
[Link](calcFilePath) extracts Reading the variable:
'[Link]' from the full path import myCats
'C:\\Windows\\System32\\[Link]'. # Access the variable
(ii) [Link]() Func on: print([Link])
[Link](path1, path2, ...) combines This way, you can save and later retrieve
mul ple path components into a single path. variables by impor ng the generated Python
It automa cally handles the correct path module.
separators for different opera ng systems,
making it safer and more portable than 1.6.a. Also explain reading and wri ng
manually concatena ng paths. process with suitable example.
Example: import os Reading and Wri ng Files
folder = 'C:\\Windows\\System32' 1. Reading Files: Open a File: Use open()
file = '[Link]' to open a file and obtain a File object.
full_path = [Link](folder, file) Read Contents: Use read() to get the
print(full_path) # Output: en re content as a string or readlines() to get
'C:\\Windows\\System32\\[Link]' a list of lines.
Example:  from pathlib import Path num_uppercase += 1
# Open the file in read mode elif [Link]():
file_path = [Link]() / '[Link]' num_lowercase += 1
with open(file_path, 'r') as file: return num_words, num_digits,
content = fi[Link]() num_uppercase, num_lowercase
print(content) # Output: 'Hello, world!' # Get user input
2. Wri ng Files: Open a File: Use open() user_sentence = input("Enter a sentence: ")
with mode 'w' (write) to overwrite or 'a' # Analyze the sentence
(append) to add to the exis ng file. words, digits, uppercase, lowercase =
Write Contents: Use write() to write text analyze_sentence(user_sentence)
to the file. Example: # Output the results
from pathlib import Path print(f"Number of words: {words}")
# Write to a file print(f"Number of digits: {digits}")
file_path = [Link]() / '[Link]' print(f"Number of uppercase le ers:
with open(file_path, 'w') as file: {uppercase}")
fi[Link]('Hello, world!\n') print(f"Number of lowercase le ers:
# Append to the file {lowercase}")
with open(file_path, 'a') as file:
fi[Link]('Bacon is not a vegetable.') 2.6.a. Explain reading and saving python
# Read the file to check the content program variables using shelve module
with open(file_path, 'r') as file: with suitable Python program.
content = fi[Link]() To read and save variables in Python using
print(content) # Output: 'Hello, the shelve module, follow these steps:
world!\nBacon is not a vegetable.' 1. Import the shelve module.
2. Open a shelf file.
2.6.c. Write a python program that accepts 3. Save variables to the shelf file.
a sentence and find the number of words, 4. Close the shelf file.
digits, uppercase le ers and lower case 5. Reopen the shelf file to read the
le ers. Program: variables.
def analyze_sentence(sentence): 6. Access and use the stored data.
# Ini alize counters Example Program import shelve
num_words = 0 # Step 1: Save variables to a shelf file
num_digits = 0 # Open the shelf file with [Link]()
num_uppercase = 0 shelfFile = [Link]('mydata')
num_lowercase = 0 # Create some variables to save
# Split the sentence into words cats = ['Zophie', 'Pooka', 'Simon']
words = [Link]() # Save the variables to the shelf file
num_words = len(words) shelfFile['cats'] = cats
# Count digits, uppercase, and lowercase # Close the shelf file
le ers [Link]()
for char in sentence: # Step 2: Read variables from the shelf file
if [Link](): # Reopen the shelf file
num_digits += 1 shelfFile = [Link]('mydata')
elif [Link](): # Access the stored variables
stored_cats = shelfFile['cats'] Example:
# Print the stored variables to verify class Rectangle:
print(stored_cats) # Output: ['Zophie', """Represents a rectangle."""
'Pooka', 'Simon'] def __init__(self, width, height):
# Close the shelf file [Link] = width # A ribute width
[Link]() [Link] = height # A ribute height
# List all keys and values in the shelf file # Crea ng an object of Rectangle
shelfFile = [Link]('mydata') box = Rectangle(150, 300)
print(list([Link]())) # Output: ['cats'] print([Link], [Link]) # Output: 150,
print(list([Link]())) # Output: 300 # Modifying the object's a ributes
[['Zophie', 'Pooka', 'Simon']] [Link] += 50
[Link]() [Link] += 100
print([Link], [Link]) # Output: 200,
MODULE  4 400
2.7.a. Define Class, Objects and A ributes 2.7.b. Write a program to create a class
with an example. called Rectangle with the help of a corner
Class: A class in Python is a blueprint for point, width and height. Write the
crea ng objects. It defines a set of a ributes following func ons and demonstrate their
and methods that the objects created from working:
the class will have. a. To find and display center of the
Objects: An object is an instance of a class. It rectangle b. To display point as an ordered
is a concrete en ty that has its own copy of pair c. To resize the rectangle
the a ributes defined in the class. d. To find area and perimeter of a rectangle
A ributes: A ributes are variables that class Rectangle:
belong to an object and store the state or def __init__(self, width, height,
data of the object. Example: corner_x=0, corner_y=0):
class Point: """Ini alizes the Rectangle with width,
"""Represents a point in 2-D space.""" height, and the coordinates of the corner
def __init__(self, x=0, y=0): (corner_x, corner_y)."""
self.x = x # A ribute x [Link] = width
self.y = y # A ribute y [Link] = height
point1 = Point(3, 4) # Object of the class self.corner_x = corner_x
Point self.corner_y = corner_y
print(point1.x) # Output: 3 (Accessing def find_center(self):
a ribute x) """Finds and displays the center of the
print(point1.y) # Output: 4 (Accessing rectangle."""
a ribute y) center_x = self.corner_x + [Link] / 2
center_y = self.corner_y + [Link] / 2
2.7.c. Jus fy the statement “Objects are print(f"Center: ({center_x},
mutable” with suitable examples. {center_y})")
Jus fica on of "Objects are mutable": def display_point(self):
The statement "Objects are mutable" means """Displays the corner point of the
that you can change the state or a ributes rectangle as an ordered pair."""
of an object a er it has been created.
print(f"Corner point: ({self.corner_x}, is created, se ng up ini al values for the
{self.corner_y})") object's a ributes. Example:
def resize(self, new_width, new_height): class Time:
"""Resizes the rectangle to the new def __init__(self, hour=0, minute=0,
width and height.""" second=0):
[Link] = new_width [Link] = hour
[Link] = new_height [Link] = minute
def area(self): [Link] = second
"""Finds and returns the area of the # Crea ng Time objects
rectangle.""" me1 = Time()
return [Link] * [Link] print( [Link], [Link],
def perimeter(self): [Link]) # Output: 0 0 0
"""Finds and returns the perimeter of me2 = Time(9)
the rectangle.""" print( [Link], [Link],
return 2 * ([Link] + [Link]) [Link]) # Output: 9 0 0
# Example usage me3 = Time(9, 45)
rect = Rectangle(10, 5, 2, 3) print( [Link], [Link],
# a. Find and display the center of the [Link]) # Output: 9 45 0
rectangle me4 = Time(9, 45, 30)
rect.find_center() # Output:Center:(7.0, 5.5) print( [Link], [Link],
# b. Display the corner point as an ordered [Link]) # Output: 9 45 30
pair __str__ Method
rect.display_point() # Output: Corner point: Purpose: Returns a string representa on of
(2, 3) # c. Resize the rectangle the object, useful for display and debugging.
[Link](20, 10) Usage: Called automa cally when the print()
print(f"New size - Width: {[Link]}, func on is used on an object. Example:
Height: {[Link]}") # Output: New size - class Time:
Width: 20, Height: 10 def __str__(self):
# d. Find area and perimeter of the rectangle return '%.2d:%.2d:%.2d' % ([Link],
area = [Link]() [Link], [Link])
perimeter = [Link]() # Crea ng and prin ng Time objects
print(f"Area: {area}") # Output: Area: 200 me = Time(9, 45, 30)
print(f"Perimeter: {perimeter}") # Output: print( me) # Output: 09:45:30
Perimeter: 60
1.8.b. Explain operator overloading and
1.8.a. Explain – in t( ) and – str( ) methods polymorphism with examples.
with an example. Operator Overloading
The __init__ and __str__ methods are Operator overloading allows you to define
special methods in Python used for object custom behaviors for standard operators
ini aliza on and string representa on, (like +, -, etc.) when used with user-defined
respec vely. classes. This is done by defining special
__init__ Method methods in your [Link]: For the Time
Purpose: Ini alizes a new object of a class. class, you can overload the + operator to add
Usage: Called automa cally when an object two Time objects together.
class Time: else:
def __init__(self, hour=0, minute=0, d[c] += 1
second=0): return d
[Link] = hour # Example usage with a string
[Link] = minute print(histogram('spamspamspam')) #
[Link] = second Output: {'s': 3, 'p': 3, 'a': 3, 'm': 3}
def me_to_int(self): # Example usage with a list
minutes = [Link] * 60 + [Link] print(histogram(['spam', 'egg', 'spam',
seconds = minutes * 60 + [Link] 'spam', 'bacon', 'spam']))
return seconds # Output: {'spam': 4, 'egg': 1, 'bacon': 1}
def int_to_ me(seconds):
me = Time() 1.7.b. Write a func on to called print me
minutes, [Link] = that takes a me object and print it in the
divmod(seconds, 60) form of hour: minute: second.
[Link], [Link] = class Time:
divmod(minutes, 60) def __init__(self, hour=0, minute=0,
return me second=0):
def __add__(self, other): """Ini alizes the Time object with hour,
seconds = self. me_to_int() + minute, and second."""
other. me_to_int() [Link] = hour
return self.int_to_ me(seconds) [Link] = minute
def __str__(self): [Link] = second
return '%.2d:%.2d:%.2d' % ([Link], def print_ me( me):
[Link], [Link]) """Prints the me in the format
# Example usage hour:minute:second."""
start = Time(9, 45) print(f”{ [Link]}:{ [Link]}
dura on = Time(1, 35) { [Link]}”)
print(start + dura on) # Output: 11:20:00 # Example usage
Polymorphism Polymorphism allows t1 = Time(14, 30, 45)
func ons to work with different types of print_ me(t1) # Output: 14:30:45
data. A func on is polymorphic if it can
handle arguments of various types, as long MODULE  5
as those types support the opera ons used 2.9.a. With an example, explain how to
in the func on. retrieve an image over HTTP.
Example: Consider a histogram func on that import socket
counts occurrences of elements in a import me
sequence. This func on works not only with HOST = '[Link]'
strings but also with lists or tuples of PORT = 80
hashable items. mysock = [Link](socket.AF_INET,
def histogram(s): socket.SOCK_STREAM)
d = dict() [Link]((HOST, PORT))
for c in s: [Link](b'GET
if c not in d: h p://[Link]/[Link]
d[c] = 1 HTTP/1.0\r\n\r\n')
count = 0 Output:
picture = b"" Name: Chuck
while True: A r: yes
data = [Link](5120) 1.9.a. Write a Python program that makes a
if len(data) < 1: break socket connec on to a web server and
count = count + len(data) follows the rules of the HTTP protocol to
print(len(data), count) request a document and display what the
picture = picture + data server sends back.
[Link]() import socket
# Look for the end of the header (2 CRLF) # Create a socket object
pos = picture.find(b"\r\n\r\n") mysock = [Link](socket.AF_INET,
print('Header length', pos) socket.SOCK_STREAM)
print(picture[:pos].decode()) # Skip past the # Connect to the web server
header and save the picture data [Link](('[Link]', 80))
picture = picture[pos+4:] # Send an HTTP GET request
and = open("stuff.jpg", "wb") cmd = 'GET h p://[Link]/[Link]
[Link](picture) HTTP/1.0\r\n\r\n'.encode()
[Link]() [Link](cmd)
# Receive and print the response data
2.9.b. Define XML. Write a Python code to while True:
pass and extract data elements from XML. data = [Link](512)
XML (eXtensible Markup Language) is a if len(data) < 1:
markup language that defines rules for break
encoding documents in a format that is both print([Link](), end='')
human-readable and machine-readable. # Close the socket connec on
XML documents are structured as a tree of [Link]()
elements with nested tags, a ributes, and
text content. Python Code to Parse and 2.10.b. Discuss various keys are used in the
Extract Data from XML: database model.
import [Link] as ET In the database model, various keys are used
# Sample XML data as follows:
data = ''' Primary Key: Uniquely iden fies each row in
<person> a table. It ensures that each record can be
<name>Chuck</name> uniquely iden fied. For example, id in the
<phone type="intl"> Ar st and Track tables.
+1 734 303 4456 Foreign Key: Links rows between tables,
</phone> establishing rela onships. For example,
<email hide="yes" /> ar st_id in the Track table refers to the id in
</person>''' the Ar st table.
# Parse the XML data Logical Key: Used for fast lookups and
tree = [Link](data) indexing. It improves query performance by
# Extract data elements indexing columns o en used in WHERE
print('Name:', tree.find('name').text) clauses, such as name in the Ar st table.
print('A r:', tree.find('email').get('hide'))
1.9.b. Illustrate with a python program how Foreign Key: A field in one table that
to retrieve web pages with urllib. refers to the primary key of another table,
import [Link] establishing a link between the tables (e.g.,
# Define the URL to retrieve ar st_id in the Track table linking to id in the
url = 'h p://[Link]/[Link]' Ar st table).
# Open the URL Data Model Example: Ar st Table:
response = [Link](url) DROP TABLE IF EXISTS Ar st;
# Read and print the contents of the web CREATE TABLE Ar st (id INTEGER PRIMARY
page KEY, name TEXT, eyes TEXT);
print("Contents of the web page:") INSERT INTO Ar st (id, name, eyes) VALUES
for line in response: (42, 'Frank Sinatra', 'blue'); Track Table:
# Decode bytes to string and strip any DROP TABLE IF EXISTS Track;
leading/trailing whitespace CREATE TABLE Track ( tle TEXT, plays
print([Link]().strip()) INTEGER, ar st_id INTEGER,
# Close the response FOREIGN KEY (ar st_id)
[Link]() REFERENCES Ar st(id));
INSERT INTO Track ( tle, plays, ar st_id)
1.10.b. Explain the concept of basic data VALUES ('My Way', 15, 42);
modelling. INSERT INTO Track ( tle, plays, ar st_id)
Basic Data Modeling involves structuring VALUES ('New York', 25, 42);
data into mul ple related tables to organize Querying Data:
and manage it efficiently within a rela onal  Use SQL JOIN to combine data from
database. This process involves breaking related tables:
down data into tables and defining the SELECT tle, plays, name, eyes
rela onships between them. Here are the FROM Track
key concepts: JOIN Ar st ON [Link] st_id = Ar [Link];
Tables and Rela onships: Tables: Data Model Diagrams: Crow's Foot
Represent en es (e.g., Track and Ar st Diagrams: Graphically represent the
tables) and contain rows (records) and rela onships between tables, indica ng
columns (a ributes). Rela onships: "one" and "many" ends of the rela onship.
Define how tables are linked. For instance, a
Track table might be linked to an Ar st table 2.10.c. Write the four SQL commands
through a foreign key. needed to create and maintain data.
Normaliza on: Goal: Avoid data Based on the informa on provided, the four
redundancy and ensure data integrity by SQL commands needed to create and
organizing data into separate tables based maintain data are:
on logical rela onships. Example: Instead of 1. CREATE TABLE - Used to create a new
repea ng ar st informa on in every track table in the database.
record, create a separate Ar st table with a CREATE TABLE Ar st (
unique iden fier (primary key) and link it to id INTEGER PRIMARY KEY,
the Track table using this iden fier. name TEXT,
Primary and Foreign Keys: Primary Key: A eyes TEXT
unique iden fier for each record in a table );
(e.g., id in the Ar st table).
1. INSERT INTO - Used to insert new can be uniquely iden fied. For example, id in
records into a table. the Ar st and Track tables.
INSERT INTO Ar st (id, name, eyes) [Link] Key: Links rows between tables,
VALUES (42, 'Frank Sinatra', 'blue'); establishing rela onships. For example,
2. SELECT - Used to retrieve data from ar st_id in the Track table refers to the id in
one or more tables. the Ar st table. [Link] Key: Used for fast
SELECT tle, plays, name, eyes lookups and indexing. It improves query
FROM Track performance by indexing columns o en used
JOIN Ar st ON [Link] st_id = Ar [Link]; in WHERE clauses, such as name in the Ar st
3. DROP TABLE - Used to delete an table.
exis ng table and its data.
DROP TABLE IF EXISTS Ar st; 1.10.a. Write a Python code to Read binary files
using urllib.
import [Link]
2.10.a. What is Service-oriented # Open the URL to retrieve the binary file
architecture (SOA). List out the img =
advantages of SOA. [Link]('[Link]
Service-Oriented Architecture (SOA) is an # Open a local file in binary write mode
fhand = open('[Link]', 'wb')
architectural pa ern where so ware # Read the data in blocks and write to the local file
func onali es are provided as services size = 0
that communicate over a network. These while True:
services are self-contained units and can # Read 100,000 bytes at a time
info = [Link](100000)
be combined to build complex # Break the loop if no more data is read
applica ons. if len(info) < 1:
Advantages of SOA: break
1. Reusability # Update the size of the copied data
size += len(info)
2. Interoperability # Write the block of data to the local file
3. Scalability [Link](info)
4. Flexibility and Agility # Print the total number of characters copied
5. Maintainability print(size, 'characters copied.')
# Close the local file
6. Cost Efficiency
[Link]()
7. Be er Alignment with Business
Processes
8. Enhanced Produc vity
9. Improved Reliability
[Link] on

2.10.b. Discuss various keys are used in


the database model.
In the database model, various keys are
used as follows:
[Link] Key: Uniquely iden fies each
row in a table. It ensures that each record.

You might also like