SEC1-P1 Computer Science 2021 PYQ NBU

0




UNIVERSITY OF NORTH BENGAL

B.Sc. Honours 3rd Semester Examination, 2021


SEC1-P1 - COMPUTER SCIENCE


SEC35-E3
PYTHON PROGRAMMING

GROUP-A

1. What are operators in Python? Give examples.

In Python, operators are special symbols that are used to perform operations on operands. Operands are the values or variables on which the operations are performed. Python supports various types of operators.
Here are examples of some commonly used operators in Python:
  1. Arithmetic Operators: '+', '-', '*', '/', '//', '%', '**'.
  2. Comparison Operators: '==', '!=', '>', '<', '>=', '<='.
  3. Logical Operators: 'and', 'or', 'not'.
  4. Assignment Operators: '=', '+=', '-='.

2. Explain identifiers in Python.

In Python, an identifier is a name given to entities such as variables, functions, classes, modules, or other objects. Identifiers are used to uniquely identify these entities within a program. 
Here are some rules and guidelines regarding identifiers in Python:
  1. Must start with a letter or underscore, can not start with a digit.
  2. Can include letters, underscores, and digits.
  3. Case-sensitive.
  4. Reserved words (e.g., if, else) cannot be used.

# Valid identifiers
my_variable = 10
total_score = 95
calculate_area = lambda r: 3.14 * r**2
MyClass = type('MyClass', (), {})

# Invalid identifiers
2count = 5  # Invalid: starts with a digit
my-var = "Hello"  # Invalid: contains a hyphen
if = 10  # Invalid: using a reserved word (code-box)

 

3. Discuss tuples with the help of examples.

A tuple in Python is an immutable, ordered collection of elements. Once a tuple is created, we cannot modify its contents - add, remove, or change elements. Tuples are defined using parentheses '()' and can contain elements of different data types.

Here's an example:


# Creating a tuple

my_tuple = (1, 2, 3, 'apple', 'banana') 


# Accessing elements

print(my_tuple[0])  # Output: 1

print(my_tuple[3])  # Output: apple


# Attempting to modify a tuple raises an error

my_tuple[0] = 10  # Error: 'tuple' object does not support item assignment (code-box)

 

4. Discuss bitwise operators in Python with the help of an example.

Bitwise operators in Python perform operations on the individual bits of binary representations of integers. These operators are often used in low-level programming and tasks where individual bits need to be manipulated.

Here are the bitwise operators in Python:
  1. Bitwise AND (&): Sets each bit to 1 if both bits are 1.
  2. Bitwise OR (|): Sets each bit to 1 if at least one bit is 1.
  3. Bitwise XOR (^): Sets each bit to 1 if only one of the bits is 1.
  4. Bitwise NOT (~): Inverts the bits, changing 1s to 0s and vice versa.
  5. Left Shift (<<): Shifts the bits to the left by a specified number of positions, filling in with zeros.
  6. Right Shift (>>): Shifts the bits to the right by a specified number of positions, filling in with the sign bit for signed integers.

# Example values
a = 10  # binary: 1010
b = 5   # binary: 0101

# Bitwise AND
result_and = a & b  # binary: 0000
print("Bitwise AND:", result_and)  # Output: 0

# Bitwise OR
result_or = a | b   # binary: 1111
print("Bitwise OR:", result_or)   # Output: 15

# Bitwise XOR
result_xor = a ^ b  # binary: 1111
print("Bitwise XOR:", result_xor)  # Output: 15

# Bitwise NOT
result_not_a = ~a   # binary: -1011 (Two's complement representation)
print("Bitwise NOT (a):", result_not_a)  # Output: -11

# Left Shift
result_left_shift = a << 1  # binary: 10100
print("Left Shift (a):", result_left_shift)  # Output: 20

# Right Shift
result_right_shift = a >> 1  # binary: 0101
print("Right Shift (a):", result_right_shift)  # Output: 5 (code-box)


5. Discuss expressions in Python.

In Python, an expression is a combination of values, variables, operators, and function calls that, when evaluated, produces a result. Expressions can be simple or complex, and they are the building blocks of Python programs. 

# Arithmetic expression
result = 5 + 3 * (2 - 1)

# String concatenation expression
greeting = "Hello" + " " + "World"

# Comparison expression
is_greater = 10 > 5

# Function call expression
length = len("Python") (code-box)


6. Discuss debugging in Python.

Debugging is the process of finding and fixing errors (bugs) in the code. Python provides several tools and techniques for debugging to help programmers identify and resolve issues in the programs. 

Here are some key aspects of debugging in Python:

Print Statements: One of the simplest and most commonly used debugging techniques is inserting print statements in the code to output variable values and intermediate results.

Using pdb (Python Debugger): Python has a built-in debugger module called pdb. We can insert pdb statements in our code or run our script with the -m pdb option to start the debugger.

IDE Debugging Tools: Integrated Development Environments (IDEs) like PyCharm, VSCode, and others offer sophisticated debugging tools. These tools allow us to set breakpoints, inspect variables, and step through the code line by line.

GROUP-B

7. Explain different data types available in Python with the help of examples.

Python supports several built-in data types that allow us to represent and manipulate different kinds of data. Here are some of the commonly used data types in Python, along with examples:

  • int: Integer type represents whole numbers.

x = 5 (code-box)

 

  • float: Float type represents floating-point numbers (decimal numbers).

y = 3.14 (code-box)

 

  •  complex: Complex type represents complex numbers.

z = 2 + 3j (code-box)

 

  •  str: String type represents sequences of characters enclosed in single or double quotes.

message = 'Hello, Python!' (code-box)

 

  •  list: List type represents ordered, mutable sequences of elements.

numbers = [1, 2, 3, 4, 5] (code-box)

 

  •  tuple: Tuple type represents ordered, immutable sequences of elements.

coordinates = (3, 4) (code-box)

 

  •  set: Set type represents an unordered collection of unique elements.

unique_numbers = {1, 2, 3, 4, 5} (code-box)

 

  •  dict: Dictionary type represents key-value pairs.

person = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'} (code-box)

 

8. Write a Python program to find the GCD of two numbers.

def GCD_Loop( a, b):  
    if a > b:  # define the if condition  
        temp = b  
    else:  
        temp = a  
    for i in range(1, temp + 1):  
        if (( a % i == 0) and (b % i == 0 )):  
            gcd = i  
    return gcd  
x = int(input (" Enter the first number: ") ) # take first no.   
y =int (input (" Enter the second number: ")) # take second no.   
num = GCD_Loop(x, y) # call the gcd_fun() to find the result  
print("GCD of two number is: ")  
print(num) # call num  (code-box)

 

Output:


c:\Users\ErAgOn\Python\gcdFile.py
Enter the first number: 60
Enter the second number: 48
GCD of two number is:
12 (code-box)

9. Write a Python program to check if a string is palindrome or not.

Python Program to Check if a String is Palindrome or Not Using Native Approach:

Here we will find the reverse of the string and then Check if the reverse and original are the same or not.

# function which return reverse of a string

def isPalindrome(s):
return s == s[::-1]


# Driver code
s = "malayalam"
ans = isPalindrome(s)

if ans:
print("Yes")
else:
print("No") (code-box)


Check if a String is Palindrome or Not Using Iterative Method:

Run a loop from starting to length/2 and check the first character to the last character of the string and second to second last one and so on …. If any character mismatches, the string wouldn’t be a palindrome.

# function to check string is
# palindrome or not
def isPalindrome(str):

# Run loop from 0 to len/2
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True

# main function
s = "malayalam"
ans = isPalindrome(s)

if (ans):
print("Yes")
else:
print("No") (code-box)


10. Write a Python program to add two matrix and find the transpose.

def add_matrices(matrix1, matrix2):
    result_matrix = []

    for i in range(len(matrix1)):
        row = []
        for j in range(len(matrix1[0])):
            row.append(matrix1[i][j] + matrix2[i][j])
        result_matrix.append(row)

    return result_matrix

def transpose_matrix(matrix):
    # Using zip to transpose the matrix
    transposed_matrix = [list(row) for row in zip(*matrix)]
    return transposed_matrix

# Input matrices
matrix1 = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

matrix2 = [
    [9, 8, 7],
    [6, 5, 4],
    [3, 2, 1]
]

# Adding matrices
result_sum_matrix = add_matrices(matrix1, matrix2)

# Finding the transpose of the sum matrix
result_transpose_matrix = transpose_matrix(result_sum_matrix)

# Displaying the matrices and their sum
print("Matrix 1:")
for row in matrix1:
    print(row)

print("\nMatrix 2:")
for row in matrix2:
    print(row)

print("\nSum of Matrices:")
for row in result_sum_matrix:
    print(row)

print("\nTranspose of the Sum Matrix:")
for row in result_transpose_matrix:
    print(row) (code-box)

Output:

Matrix 1:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Matrix 2:
[9, 8, 7]
[6, 5, 4]
[3, 2, 1]

Sum of Matrices:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]

Transpose of the Sum Matrix:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10] (code-box)

11. Write a Python program to check if the given number is Prime or Not.

# Program to check if a number is prime or not

# To take input from the user
num = int(input("Enter a number: "))

# define a flag variable
flag = False

if num == 1:
    print(num, "is not a prime number")
elif num > 1:
    # check for factors
    for i in range(2, num):
        if (num % i) == 0:
            # if factor is found, set flag to True
            flag = True
            # break out of loop
            break

    # check if flag is True
    if flag:
        print(num, "is not a prime number")
    else:
        print(num, "is a prime number") (code-box)

Output:

Enter a number: 29
29  is a prime number (code-box)

12. Write a Python program to check whether a given number is Armstrong or not.

# take input from the user
num = int(input("Enter a number: "))

# Changed num variable to string, 
# and calculated the length (number of digits)
order = len(str(num))

# initialize sum
sum = 0

# find the sum of the cube of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10

# display the result
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number") (code-box)

Output 1:

Enter a number: 663
663 is not an Armstrong number (code-box)

Output 2:

Enter a number: 407
407 is an Armstrong number (code-box)

 

GROUP-C

13. Explain arrays in Python. Write a program in Python to demonstrate the
implementation of arrays.

In Python, arrays are not built into the core language like in other programming languages. Instead, Python provides a powerful and flexible built-in data type called a list, which can be used to create arrays and perform array-like operations. Lists in Python can contain elements of different data types that are mutable, meaning you can change their size and modify elements.

Here's a program demonstrating the implementation of arrays using lists in Python:

# Creating an array (list) of integers
integer_array = [1, 2, 3, 4, 5]

# Creating an array (list) of strings
string_array = ["apple", "banana", "orange", "grape"]

# Accessing elements of the arrays
print("Integer Array:", integer_array)
print("Element at index 2:", integer_array[2])

print("\nString Array:", string_array)
print("Element at index 1:", string_array[1])

# Modifying elements of the arrays
integer_array[3] = 8
string_array[0] = "cherry"

# Adding elements to the arrays
integer_array.append(6)
string_array.insert(2, "kiwi")

# Removing elements from the arrays
integer_array.pop(1)
string_array.remove("banana")

# Displaying the modified arrays
print("\nModified Integer Array:", integer_array)
print("Modified String Array:", string_array) (code-box)

 

Output:


Integer Array: [1, 2, 3, 4, 5]
Element at index 2: 3

String Array: ['apple', 'banana', 'orange', 'grape']
Element at index 1: banana
 
Modified Integer Array: [1, 3, 8, 5, 6]
Modified String Array: ['cherry', 'kiwi', 'orange', 'grape'] (code-box)

 

14. Write a program in Python to calculate total marks, percentage and grade of a student. Marks obtained in each of the three subjects are to be input by the user.

Assign grades according to the following criteria.

(a) Grade A: Percentage > = 80

(b) Grade B: Percentage > = 70 and < 80

(c) Grade C: Percentage > = 60 and < 70

(d) Grade D: Percentage > 40 and < 60

(e) Grade E: Percentage < 40

# Input marks from the user
subject1 = float(input("Enter marks for Subject 1: "))
subject2 = float(input("Enter marks for Subject 2: "))
subject3 = float(input("Enter marks for Subject 3: "))

# Calculate total marks and percentage
total_marks = subject1 + subject2 + subject3
percentage = (total_marks / 300) * 100

# Assign grades based on percentage
if percentage >= 80:
    grade = 'A'
elif 70 <= percentage < 80:
    grade = 'B'
elif 60 <= percentage < 70:
    grade = 'C'
elif 40 <= percentage < 60:
    grade = 'D'
else:
    grade = 'E'

# Display results
print("\n----- Results -----")
print("Total Marks:", total_marks)
print("Percentage:", percentage, "%")
print("Grade:", grade) (code-box)

Output:

Enter marks for Subject 1: 98
Enter marks for Subject 2: 99
Enter marks for Subject 3: 96
----- Results -----
Total Marks: 293.0
Percentage: 97.66666666666667 %
Grade: A  (code-box)

15. Explain loops in Python with the help of examples.

Loops in Python are used to repeatedly execute a block of code until a certain condition is met. Python supports two main types of loops: 'for' loop and 'while' loop.

'for' Loop: The for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or other iterable objects.

#Iterating over a List
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit) (code-box)

Output:

apple
banana
cherry (code-box)

#Using range() for Numerical Range
for i in range(5):
    print(i) (code-box)

Output:

0
1
2
3
4 (code-box)

'while' Loop: The while loop continues to execute a block of code as long as a specified condition is True.

count = 1

while count <= 5:
    print(count)
    count += 1 (code-box)

Output:

1
2
3
4
5 (code-box)

Loop Control Statements: Python provides loop control statements that allow us to modify the execution of a loop. The key control statements are break and continue.

Example: Using 'break' to Exit the Loop

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    if fruit == "banana":
        break
    print(fruit) (code-box)

Output:

apple (code-box)

In this example, the loop is terminated when the value of 'fruit' becomes "banana."

Example: Using 'continue' to Skip Iteration

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    if fruit == "banana":
        continue
    print(fruit) (code-box)

Output:

apple
cherry (code-box)

In this example, the loop skips the iteration when the value of 'fruit' is "banana."

16. Write a program in Python to generate Fibonacci series up to n-terms.

# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid
if nterms <= 0:
   print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
# generate fibonacci sequence
else:
   print("Fibonacci sequence:")
   while count < nterms:
       print(n1)
       nth = n1 + n2
       # update values
       n1 = n2
       n2 = nth
       count += 1 (code-box)

Output:

How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8 (code-box)

Hope it helps :)


Post a Comment

0Comments
Post a Comment (0)