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

Python Notes

The document covers various programming concepts in Python, including structured vs unstructured programming, loops, functions, and file handling. It also discusses data types, error handling, and control statements, along with practical examples and flowcharts. Additionally, it addresses advanced topics like multiple inheritance, constructors, and memory hierarchy.

Uploaded by

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

Python Notes

The document covers various programming concepts in Python, including structured vs unstructured programming, loops, functions, and file handling. It also discusses data types, error handling, and control statements, along with practical examples and flowcharts. Additionally, it addresses advanced topics like multiple inheritance, constructors, and memory hierarchy.

Uploaded by

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

2022-2023(PYTHON)

GROUP A (1*10)
I. Differentiate structured and unstructured programming.
Structured Programming: Uses functions, loops, and conditional statements to
create a modular and organized code structure. Example: Python, C.
Unstructured Programming: Code flows without defined modules or structure,
typically using GOTO statements. Example: Assembly language.

II. Write the output


>>> minutes = 645
>>> hours = minutes // 60
>>> hours
10

III. Differentiate while and for loop.


While loop: Repeats as long as a condition is true.
For loop: Iterates over a sequence or a range for a defined number of steps.

IV. How do we convert the string to lowercase?


Use the .lower() method.
Example: "HELLO".lower() → hello.

V. How does a function retum values?


A function uses the return statement to send data back to the caller.
Example:
VI. How to delete a file?
Use the [Link]() function from the os module.
Example:

VII. How to express switch-case statements using flowchart?


Switch-case can be represented as a decision tree in a flowchart, with each
case branching out from a decision point based on the value of the expression.

VIII. What will happen if we write


>>>17=n
>>> print(n)
Error: SyntaxError. Assignment cannot be done to a literal value like 17.

IX. Define iterator.


An iterator is an object in Python that implements the __iter__() and
__next__() methods to allow sequential traversal of elements.
Example:

X. Explain the statement [Link](-3, 2)


Moves the file pointer 3 bytes backward from the end of the file.
 -3: Offset value.
 2: Reference point (end of file).
XI. What is the value of M and N respectively? If M39048458N is divisible by 8
& 11; where M & N are single digit integers?
 Divisibility by 8: Last 3 digits (58N) divisible by 8 → 584 satisfies (N = 4).
 Divisibility by 11: Difference between sums of alternating digits should be
divisible by 11. Using M = 7, N = 4 satisfies both conditions.

Answer: M = 7, N = 4.

XII. How to express subroutine calls using flowchart?


Use a rectangle with double vertical bars to denote the subroutine call, and
show an arrow connecting it to the calling and return points.

GROUP B (5*3)

1. Write a program to get the eigenvalues of a matrix.

Explanation:
 The [Link] function computes the eigenvalues and eigenvectors
of a matrix.
 Only the eigenvalues are printed here.
2. What is the difference between list and tuple in Python? Explain with
example.
List:
 Mutable (can be modified).
 Defined using square brackets [].
 Suitable for dynamic collections.
Example:

Tuple:
 Immutable (cannot be modified).
 Defined using parentheses ().
 Suitable for fixed collections.
Example:
3. Draw a flowchart to calculate the factorial of a number given by the user.
Steps:
1. Start.
2. Input the number n.
3. Initialize factorial = 1.
4. Check if n > 0:
o If True: Multiply factorial by n, decrement n, repeat.
o If False: Proceed to Step 5.
5. Output the factorial.
6. End.
(Note: You can draw this using standard flowchart symbols like rectangles,
diamonds, and arrows.)

4. Explain the use of modulus operator in python.


The modulus operator (%) returns the remainder of a division operation. It is
often used in:
1. Checking divisibility: if x % y == 0 checks if x is divisible by y.
2. Cyclic operations: In applications like circular arrays or rotations.
3. Working with time: Converting seconds to minutes and hours.
Example:
5. Explain the use of BCD and Gray code with examples.
BCD (Binary-Coded Decimal):
 Represents decimal numbers in binary form, where each decimal digit is
represented by 4 binary bits.
 Example:
Decimal 45 → BCD 0100 0101.
 Use:
Used in digital systems like calculators, digital clocks, and electronic meters
where binary-decimal conversions are frequent.
Gray Code:
 A binary numeral system where two successive values differ by only one bit.
 Example:
Binary 000 → Gray Code 000,
Binary 001 → Gray Code 001,
Binary 010 → Gray Code 011.
 Use:
Used in error correction, minimizing bit transitions in digital circuits, and
position encoders.
GROUP C (15*3)
6
a) Find the most frequent value in a NumPy array.

Explanation:
 The [Link]() function returns the mode (most frequent value) and
its count in an array.

b) Compute the covariance matrix of two given NumPy arrays.

Explanation:
 The [Link]() function calculates the covariance matrix, where the diagonal
represents the variance of each array, and the off-diagonal values represent
the covariance between arrays.
c) Write a program to replace NaN values with the average of columns.

Explanation:
 [Link]() computes the mean of each column, ignoring NaN values.
 [Link]() identifies the indices of NaN values, which are replaced with the
corresponding column average.

7
a) Does multiple inheritance is supported in Python? Explain with example.
Answer:
Yes, Python supports multiple inheritance. A class can inherit from multiple
parent classes.
Explanation:
 Class C inherits from both A and B, gaining access to their methods.

b) How can we create a constructor in Python programming?


A constructor is created using the __init__ method, which initializes an object’s
attributes when an instance of a class is created.
Example:

c) How do you copy an object in Python? Give example.

Objects can be copied using the copy module.

Example:

Explanation:
 Shallow Copy: Copies references of nested objects, so changes affect the
original.
 Deep Copy: Creates an independent copy of all objects.

8
a) Draw a flowchart and write an algorithm for blnary search.
Algorithm:
1. Start.
2. Input a sorted array and the target value.
3. Set low = 0 and high = len(array) - 1.
4. While low <= high:
o Compute mid = (low + high) // 2.
o If array[mid] == target, return mid.
o If array[mid] < target, set low = mid + 1.
o If array[mid] > target, set high = mid - 1.
5. If no match is found, return -1.
6. End.

b) Write the pseudocode for Iinear search.


Pseudocode:
1. Start.
2. Input an array and the target value.
3. For each element x in the array:
o If x == target, return its index.
4. If no match is found, return -1.
5. End.
9
a) Explain the difference between left hand side and right hand side of
assignment with an example.

Left-hand side (LHS): Variable where the value is stored.

Right-hand side (RHS): Expression or value to assign to the variable.

Example:

LHS (x) is assigned the result of RHS (15).

b) How are implicit and explicit type conversions done in python?


Implicit Conversion: Done automatically by Python, e.g., converting int to float.

Explicit Conversion: Done manually using type conversion functions like int(),
float(), etc

c) Explain the case sensitivity of python. How to take console input.


 Case Sensitivity: Python distinguishes between uppercase and lowercase letters in
identifiers.

 Console Input: Use input() to take user input.


10
a) Discuss about type conversion functions. What type of error will you receive
for the statement int("23 bottles")?
 Type Conversion Functions: Convert one data type to another (e.g., int(), float(),
str()).
 Error: A ValueError is raised when int("23 bottles") is attempted because the
string contains non-numeric characters.

b) Mention the points which should be followed while choosing mnemonic


variable names.
 Use descriptive and meaningful names (e.g., total_marks instead of tm).
 Keep names short and clear.
 Avoid special characters or spaces.
 Use consistent naming conventions (e.g., snake_case or camelCase).
 Avoid reserved keywords.

c) How to print different types of variables?


Use the print() function with string formatting for clarity.
Example:
2023-2024(PYTHON)
GROUP A (1*10)
I. Define package in Python.
A package in Python is a collection of modules organized in directories
containing a special __init__.py file.

II. Which keyword is used to raise an error in Python?

The raise keyword is used to explicitly raise an error.

Example:

III. Give one example of the use of_Init_() function.


The __init__() function is used as a constructor to initialize object attributes

IV. Explain IEEE-754 floating point representation for 32 bit numbers.


The IEEE-754 standard represents a 32-bit floating-point number as:
 1 bit for the sign (0 for positive, 1 for negative).
 8 bits for the exponent.
 23 bits for the mantissa (fraction).
.
V. Draw the input and output symbol for a flowchart.
 Input symbol: A parallelogram.
 Output symbol: A parallelogram (same as input).

VI. How to create a string variable in python?


Use quotes (', ", or ''').
Example:

VII. Write the types of control statements in Python.


 Conditional statements: if, if-else, if-elif-else.
 Loops: for, while.
 Control flow modifiers: break, continue, pass.

VIII. How to get a random number between 0 and 1.


Use the [Link]() function.
Example:

IX. How to set a default value in a function?


Assign a default value to a parameter in the function definition.

Example:

X. What happens when a function doesn't have a return statement? Is


this valid?

If a function has no return statement, it returns None by default. Yes, it is valid.

Example:

XI. Differentiate error and exception.


 Error: A problem in the code that prevents it from running (e.g., syntax
errors).
 Exception: An error that occurs during execution and can be handled (e.g.,
ValueError, ZeroDivisionError).

XII. Write the output


import re
[Link]('aa[cde]?', 'aacde aa aadcde')
Output:
['aac', 'aa', 'aad']
Explanation:
 'aa[cde]?' matches 'aa' followed by an optional character from [cde].
GROUP B(5*3)
1. Write a program to count the number of unique capital letters in a file?

Explanation:
 The file is read, and a set is created to store unique uppercase letters
([Link]() checks for capital letters).
 The length of the set gives the count of unique capital letters.

2. What is Index Out Of Range Error?

Answer:
An Index Out Of Range Error occurs when attempting to access an index that does not
exist in a sequence (like a list, tuple, or string).

Example:

Explanation:
In the above example, the list lst has indices 0, 1, 2, and accessing index 5 is
invalid.

3. How to remove values from a Python array? Explain with example


In Python, you can remove values from an array (or list) using methods like
remove(), pop(), or slicing.
Example:

4. Explain the computer memory hierarchy.

The computer memory hierarchy organizes memory components based on


speed, size, and cost:
1. Registers:
o Smallest and fastest memory.
o Located inside the CPU.
o Used to store immediate data and instructions.
2. Cache:
o Faster than main memory.
o Temporary storage for frequently accessed data.
3. Main Memory (RAM):
o Moderately fast.
o Volatile memory used to store running programs and data.
4. Secondary Storage (HDD, SSD):
o Non-volatile.
o Slower but larger capacity for long-term storage.
5. Tertiary Storage (Backup Devices):
o Used for archival and backup.
o Includes tape drives and optical disks.

5. Explain different types of loops in python with examples.


1. For Loop:
Iterates over a sequence (list, tuple, string, or range).
Example:

2. While Loop:
Repeats as long as a condition is True.
Example:

3. Nested Loops:
Loops inside another loop.
Example:

4. Loop Control Statements:


 Break: Exits the loop immediately.
Example:

 Continue: Skips the current iteration.


Example:

GROUP C(15*3)
6
a) Write a Python function to check whether a number falls in a given range.
We can write a Python function to check if a given number lies within a specified
range by comparing it with the lower and upper bounds of the range.

Explanation:
 The function is_in_range takes three arguments: the number to check, and
the start and end values of the range.
 It compares the number with the start and end values and returns True if
the number is within the range, otherwise False.

b) Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.
Answer:
This function will iterate over the string and count the number of uppercase and
lowercase letters using Python's built-in string methods isupper() and islower()
Explanation:
 The function count_case iterates through the string s and uses isupper() to
check for uppercase letters and islower() to check for lowercase letters.
 It returns the counts of uppercase and lowercase letters in the string.

c) Write a Python program to print the even numbers from a given list.
Answer:
To filter and print even numbers from a list, we can use a list comprehension or a
simple loop.
Explanation:
 The function print_even_numbers takes a list and uses a list comprehension
to filter out even numbers (num % 2 == 0).
 It returns a list of even numbers, which are then printed

7
a) Write a program to count the words "to" and "the" present in a text file
"[Link]".
Answer:
This program will read the contents of a file and count the occurrences of the
words "to" and "the".

Ex
planation:
 The function count_words_in_file opens the file and reads its contents.
 It converts the text to lowercase to make the search case-insensitive and
then counts occurrences of each word in the provided list of words.
 The results are returned in a dictionary.
b) Write a program to display all the lines in a file "[Link]" along with
line/record number.
Answer:
This program reads a file and prints each line along with its line number

Explanation:
 The function display_lines_with_numbers opens the file, reads all lines into
a list, and then iterates through them using enumerate(), which provides
both the index (line number) and the line content.
 It prints each line along with its line number.

c) Write a short note on flush() function.


Answer:
The flush() function is used in Python to flush the internal buffer of a file or
output stream, forcing any buffered data to be written to the file or displayed
immediately. By default, Python buffers output to optimize performance
(especially with files). When flush() is called, any data in the buffer is
immediately written.
Explanation:
 [Link]() ensures that the output is written to the console
immediately, even if the default buffering mechanism would have delayed
it.

8
a) Explain the basic computer architecture with a diagram.
Answer:
The basic computer architecture consists of the following major components:
1. Central Processing Unit (CPU):
o The brain of the computer that performs instructions. It contains the
Arithmetic Logic Unit (ALU) and Control Unit (CU).
2. Memory:
o Includes both Primary memory (RAM) and Secondary memory (Hard
Disk, SSD). RAM stores data temporarily, while secondary memory
stores data permanently.
3. Input Devices:
o Devices like keyboard, mouse, etc., used to input data into the
computer.
4. Output Devices:
o Devices like monitor, printer, etc., used to output the results.
Diagram:
b) Write differences between 1's and 2's complements in the binary number
system.
Answer:
1. 1's Complement:
o To find the 1's complement of a binary number, flip all the bits
(change 0 to 1 and 1 to 0).
o Example: The 1's complement of 1101 is 0010.
2. 2's Complement:
o To find the 2's complement of a binary number, first find the 1's
complement, then add 1 to the least significant bit (LSB).
o Example: The 2's complement of 1101 is obtained by inverting the
bits (0010) and adding 1 to get 0011.
Key Differences:
 1's complement allows two representations for zero (+0 and -0), while 2's
complement has a unique representation for zero.
 2's complement is used more commonly in computers for arithmetic
operations because it simplifies addition and subtraction.
c) What do you mean by Packed and unpacked BCD system? Explain with
examples.
Answer:
1. Packed BCD (Binary-Coded Decimal):
o In Packed BCD, each byte stores two decimal digits (4 bits per digit).
o Example: The decimal number 45 in Packed BCD would be stored as
01000101 in binary, where 0100 represents 4 and 0101 represents 5.
2. Unpacked BCD:
o In Unpacked BCD, each byte stores one decimal digit.
o Example: The decimal number 45 in Unpacked BCD would be stored
as 00000100 for 4 and 00000101 for 5.
Key Difference:
 Packed BCD uses one byte to store two digits, while Unpacked BCD uses one
byte per digit.

9
a) What are standard input, output and error streams?
Answer:
 Standard Input (stdin): The default source from which a program reads
input. It is usually the keyboard.
 Standard Output (stdout): The default destination for a program's output,
usually the terminal or console.
 Standard Error (stderr): The default stream for error messages and
diagnostics, separate from stdout.
Example:
b) Differentiate between Absolute Pathnames and Relative Pathnames.
Answer:
 Absolute Pathname:
o Specifies the complete path from the root directory to the target file
or directory.
o Example: /home/user/documents/[Link]
 Relative Pathname:
o Specifies the path relative to the current working directory.
o Example: documents/[Link] (if the current directory is /home/user).
Key Difference:
 Absolute pathnames give the full location, while relative pathnames depend
on the current directory.

c) Differentiate write() and writelines().


Answer:
 write():
o Writes a single string to a file.
o Example:
o

 writelines():
o Writes a list of strings to a file.
o Example:

Key Difference:
 write() writes one string, while writelines() writes a sequence of strings.

10
a) Draw a flowchart and write an algorithm for merge sort.
Answer:
Merge Sort Algorithm:
1. Divide the unsorted list into n sublists, each containing one element.
2. Repeatedly merge sublists to produce new sorted sublists until there is only
one sublist left.
b) Write the pseudocode for binary search.

You might also like